file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
pragma solidity ^0.5.3;
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./interfaces/ILockedGold.sol";
import "./interfaces/IGovernance.sol";
import "./interfaces/IValidators.sol";
import "../common/Initializable.sol";
import "../common/UsingRegistry.sol";
import "../common/FixidityLib.sol";
import "../common/interfaces/IERC20Token.sol";
import "../common/Signatures.sol";
import "../common/FractionUtil.sol";
contract LockedGold is ILockedGold, ReentrancyGuard, Initializable, UsingRegistry {
using FixidityLib for FixidityLib.Fraction;
using FractionUtil for FractionUtil.Fraction;
using SafeMath for uint256;
// TODO(asa): Remove index for gas efficiency if two updates to the same slot costs extra gas.
struct Commitment {
uint128 value;
uint128 index;
}
struct Commitments {
// Maps a notice period in seconds to a Locked Gold commitment.
mapping(uint256 => Commitment) locked;
// Maps an availability time in seconds since epoch to a notified commitment.
mapping(uint256 => Commitment) notified;
uint256[] noticePeriods;
uint256[] availabilityTimes;
}
struct Account {
bool exists;
// The weight of the account in validator elections, governance, and block rewards.
uint256 weight;
// Each account may delegate their right to receive rewards, vote, and register a Validator or
// Validator group to exactly one address each, respectively. This address must not hold an
// account and must not be delegated to by any other account or by the same account for any
// other purpose.
address[3] delegates;
// Frozen accounts may not vote, but may redact votes.
bool votingFrozen;
// The timestamp of the last time that rewards were redeemed.
uint96 rewardsLastRedeemed;
Commitments commitments;
}
// TODO(asa): Add minNoticePeriod
uint256 public maxNoticePeriod;
uint256 public totalWeight;
mapping(address => Account) private accounts;
// Maps voting, rewards, and validating delegates to the account that delegated these rights.
mapping(address => address) public delegations;
// Maps a block number to the cumulative reward for an account with weight 1 since genesis.
mapping(uint256 => FixidityLib.Fraction) public cumulativeRewardWeights;
event MaxNoticePeriodSet(
uint256 maxNoticePeriod
);
event RoleDelegated(
DelegateRole role,
address indexed account,
address delegate
);
event VotingFrozen(
address indexed account
);
event VotingUnfrozen(
address indexed account
);
event NewCommitment(
address indexed account,
uint256 value,
uint256 noticePeriod
);
event CommitmentNotified(
address indexed account,
uint256 value,
uint256 noticePeriod,
uint256 availabilityTime
);
event CommitmentExtended(
address indexed account,
uint256 value,
uint256 noticePeriod,
uint256 availabilityTime
);
event Withdrawal(
address indexed account,
uint256 value
);
event NoticePeriodIncreased(
address indexed account,
uint256 value,
uint256 noticePeriod,
uint256 increase
);
function initialize(address registryAddress, uint256 _maxNoticePeriod) external initializer {
_transferOwnership(msg.sender);
setRegistry(registryAddress);
maxNoticePeriod = _maxNoticePeriod;
}
/**
* @notice Sets the cumulative block reward for 1 unit of account weight.
* @param blockReward The total reward allocated to bonders for this block.
* @dev Called by the EVM at the end of the block.
*/
function setCumulativeRewardWeight(uint256 blockReward) external {
require(blockReward > 0, "placeholder to suppress warning");
return;
// TODO(asa): Modify ganache to set cumulativeRewardWeights.
// TODO(asa): Make inheritable `onlyVm` modifier.
// Only callable by the EVM.
// require(msg.sender == address(0), "sender was not vm (reserved addr 0x0)");
// FractionUtil.Fraction storage previousCumulativeRewardWeight = cumulativeRewardWeights[
// block.number.sub(1)
// ];
// // This will be true the first time this is called by the EVM.
// if (!previousCumulativeRewardWeight.exists()) {
// previousCumulativeRewardWeight.denominator = 1;
// }
// if (totalWeight > 0) {
// FractionUtil.Fraction memory currentRewardWeight = FractionUtil.Fraction(
// blockReward,
// totalWeight
// ).reduce();
// cumulativeRewardWeights[block.number] = previousCumulativeRewardWeight.add(
// currentRewardWeight
// );
// } else {
// cumulativeRewardWeights[block.number] = previousCumulativeRewardWeight;
// }
}
/**
* @notice Sets the maximum notice period for an account.
* @param _maxNoticePeriod The new maximum notice period.
*/
function setMaxNoticePeriod(uint256 _maxNoticePeriod) external onlyOwner {
maxNoticePeriod = _maxNoticePeriod;
emit MaxNoticePeriodSet(maxNoticePeriod);
}
/**
* @notice Creates an account.
* @return True if account creation succeeded.
*/
function createAccount()
external
returns (bool)
{
require(isNotAccount(msg.sender) && isNotDelegate(msg.sender));
Account storage account = accounts[msg.sender];
account.exists = true;
account.rewardsLastRedeemed = uint96(block.number);
return true;
}
/**
* @notice Redeems rewards accrued since the last redemption for the specified account.
* @return The amount of accrued rewards.
* @dev Fails if `msg.sender` is not the owner or rewards recipient of the account.
*/
function redeemRewards() external nonReentrant returns (uint256) {
require(false, "Disabled");
address account = getAccountFromDelegateAndRole(msg.sender, DelegateRole.Rewards);
return _redeemRewards(account);
}
/**
* @notice Freezes the voting power of `msg.sender`'s account.
*/
function freezeVoting() external {
require(isAccount(msg.sender));
Account storage account = accounts[msg.sender];
require(account.votingFrozen == false);
account.votingFrozen = true;
emit VotingFrozen(msg.sender);
}
/**
* @notice Unfreezes the voting power of `msg.sender`'s account.
*/
function unfreezeVoting() external {
require(isAccount(msg.sender));
Account storage account = accounts[msg.sender];
require(account.votingFrozen == true);
account.votingFrozen = false;
emit VotingUnfrozen(msg.sender);
}
/**
* @notice Delegates the validating power of `msg.sender`'s account to another address.
* @param delegate The address to delegate to.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Fails if the address is already a delegate or has an account .
* @dev Fails if the current account is already participating in validation.
* @dev v, r, s constitute `delegate`'s signature on `msg.sender`.
*/
function delegateRole(
DelegateRole role,
address delegate,
uint8 v,
bytes32 r,
bytes32 s
)
external
nonReentrant
{
// TODO: split and add error messages for better dev feedback
require(isAccount(msg.sender) && isNotAccount(delegate) && isNotDelegate(delegate));
address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s);
require(signer == delegate);
if (role == DelegateRole.Validating) {
require(isNotValidating(msg.sender));
} else if (role == DelegateRole.Voting) {
require(!isVoting(msg.sender));
} else if (role == DelegateRole.Rewards) {
_redeemRewards(msg.sender);
}
Account storage account = accounts[msg.sender];
delegations[account.delegates[uint256(role)]] = address(0);
account.delegates[uint256(role)] = delegate;
delegations[delegate] = msg.sender;
emit RoleDelegated(role, msg.sender, delegate);
}
/**
* @notice Adds a Locked Gold commitment to `msg.sender`'s account.
* @param noticePeriod The notice period for the commitment.
* @return The account's new weight.
*/
function newCommitment(
uint256 noticePeriod
)
external
nonReentrant
payable
returns (uint256)
{
require(isAccount(msg.sender) && !isVoting(msg.sender));
// _redeemRewards(msg.sender);
require(msg.value > 0 && noticePeriod <= maxNoticePeriod);
Account storage account = accounts[msg.sender];
Commitment storage locked = account.commitments.locked[noticePeriod];
updateLockedCommitment(account, uint256(locked.value).add(msg.value), noticePeriod);
emit NewCommitment(msg.sender, msg.value, noticePeriod);
return account.weight;
}
/**
* @notice Notifies a Locked Gold commitment, allowing funds to be withdrawn after the notice
* period.
* @param value The amount of the commitment to eventually withdraw.
* @param noticePeriod The notice period of the Locked Gold commitment.
* @return The account's new weight.
*/
function notifyCommitment(
uint256 value,
uint256 noticePeriod
)
external
nonReentrant
returns (uint256)
{
require(isAccount(msg.sender) && isNotValidating(msg.sender) && !isVoting(msg.sender));
// _redeemRewards(msg.sender);
Account storage account = accounts[msg.sender];
Commitment storage locked = account.commitments.locked[noticePeriod];
require(locked.value >= value && value > 0);
updateLockedCommitment(account, uint256(locked.value).sub(value), noticePeriod);
// solhint-disable-next-line not-rely-on-time
uint256 availabilityTime = now.add(noticePeriod);
Commitment storage notified = account.commitments.notified[availabilityTime];
updateNotifiedDeposit(account, uint256(notified.value).add(value), availabilityTime);
emit CommitmentNotified(msg.sender, value, noticePeriod, availabilityTime);
return account.weight;
}
/**
* @notice Rebonds a notified commitment, with notice period >= the remaining time to
* availability.
* @param value The amount of the commitment to rebond.
* @param availabilityTime The availability time of the notified commitment.
* @return The account's new weight.
*/
function extendCommitment(
uint256 value,
uint256 availabilityTime
)
external
nonReentrant
returns (uint256)
{
require(isAccount(msg.sender) && !isVoting(msg.sender));
// solhint-disable-next-line not-rely-on-time
require(availabilityTime > now);
// _redeemRewards(msg.sender);
Account storage account = accounts[msg.sender];
Commitment storage notified = account.commitments.notified[availabilityTime];
require(notified.value >= value && value > 0);
updateNotifiedDeposit(account, uint256(notified.value).sub(value), availabilityTime);
// solhint-disable-next-line not-rely-on-time
uint256 noticePeriod = availabilityTime.sub(now);
Commitment storage locked = account.commitments.locked[noticePeriod];
updateLockedCommitment(account, uint256(locked.value).add(value), noticePeriod);
emit CommitmentExtended(msg.sender, value, noticePeriod, availabilityTime);
return account.weight;
}
/**
* @notice Withdraws a notified commitment after the duration of the notice period.
* @param availabilityTime The availability time of the notified commitment.
* @return The account's new weight.
*/
function withdrawCommitment(
uint256 availabilityTime
)
external
nonReentrant
returns (uint256)
{
require(isAccount(msg.sender) && !isVoting(msg.sender));
// _redeemRewards(msg.sender);
// solhint-disable-next-line not-rely-on-time
require(now >= availabilityTime);
_redeemRewards(msg.sender);
Account storage account = accounts[msg.sender];
Commitment storage notified = account.commitments.notified[availabilityTime];
uint256 value = notified.value;
require(value > 0);
updateNotifiedDeposit(account, 0, availabilityTime);
IERC20Token goldToken = IERC20Token(registry.getAddressFor(GOLD_TOKEN_REGISTRY_ID));
require(goldToken.transfer(msg.sender, value));
emit Withdrawal(msg.sender, value);
return account.weight;
}
/**
* @notice Increases the notice period for all or part of a Locked Gold commitment.
* @param value The amount of the Locked Gold commitment to increase the notice period for.
* @param noticePeriod The notice period of the Locked Gold commitment.
* @param increase The amount to increase the notice period by.
* @return The account's new weight.
*/
function increaseNoticePeriod(
uint256 value,
uint256 noticePeriod,
uint256 increase
)
external
nonReentrant
returns (uint256)
{
require(isAccount(msg.sender) && !isVoting(msg.sender));
// _redeemRewards(msg.sender);
require(value > 0 && increase > 0);
Account storage account = accounts[msg.sender];
Commitment storage locked = account.commitments.locked[noticePeriod];
require(locked.value >= value);
updateLockedCommitment(account, uint256(locked.value).sub(value), noticePeriod);
uint256 increasedNoticePeriod = noticePeriod.add(increase);
uint256 increasedValue = account.commitments.locked[increasedNoticePeriod].value;
updateLockedCommitment(account, increasedValue.add(value), increasedNoticePeriod);
emit NoticePeriodIncreased(msg.sender, value, noticePeriod, increase);
return account.weight;
}
/**
* @notice Returns whether or not an account's voting power is frozen.
* @param account The address of the account.
* @return Whether or not the account's voting power is frozen.
* @dev Frozen accounts can retract existing votes but not make future votes.
*/
function isVotingFrozen(address account) external view returns (bool) {
return accounts[account].votingFrozen;
}
/**
* @notice Returns the timestamp of the last time the account redeemed block rewards.
* @param _account The address of the account.
* @return The timestamp of the last time `_account` redeemed block rewards.
*/
function getRewardsLastRedeemed(address _account) external view returns (uint96) {
Account storage account = accounts[_account];
return account.rewardsLastRedeemed;
}
function isValidating(address validator) external view returns (bool) {
IValidators validators = IValidators(registry.getAddressFor(VALIDATORS_REGISTRY_ID));
return validators.isValidating(validator);
}
/**
* @notice Returns the notice periods of all Locked Gold for an account.
* @param _account The address of the account.
* @return The notice periods of all Locked Gold for `_account`.
*/
function getNoticePeriods(address _account) external view returns (uint256[] memory) {
Account storage account = accounts[_account];
return account.commitments.noticePeriods;
}
/**
* @notice Returns the availability times of all notified commitments for an account.
* @param _account The address of the account.
* @return The availability times of all notified commitments for `_account`.
*/
function getAvailabilityTimes(address _account) external view returns (uint256[] memory) {
Account storage account = accounts[_account];
return account.commitments.availabilityTimes;
}
/**
* @notice Returns the value and index of a specified Locked Gold commitment.
* @param _account The address of the account.
* @param noticePeriod The notice period of the Locked Gold commitment.
* @return The value and index of the specified Locked Gold commitment.
*/
function getLockedCommitment(
address _account,
uint256 noticePeriod
)
external
view
returns (uint256, uint256)
{
Account storage account = accounts[_account];
Commitment storage locked = account.commitments.locked[noticePeriod];
return (locked.value, locked.index);
}
/**
* @notice Returns the value and index of a specified notified commitment.
* @param _account The address of the account.
* @param availabilityTime The availability time of the notified commitment.
* @return The value and index of the specified notified commitment.
*/
function getNotifiedCommitment(
address _account,
uint256 availabilityTime
)
external
view
returns (uint256, uint256)
{
Account storage account = accounts[_account];
Commitment storage notified = account.commitments.notified[availabilityTime];
return (notified.value, notified.index);
}
/**
* @notice Returns the account associated with the provided delegate and role.
* @param accountOrDelegate The address of the account or voting delegate.
* @param role The delegate role to query for.
* @dev Fails if the `accountOrDelegate` is a non-voting delegate.
* @return The associated account.
*/
function getAccountFromDelegateAndRole(
address accountOrDelegate,
DelegateRole role
)
public
view
returns (address)
{
address delegatingAccount = delegations[accountOrDelegate];
if (delegatingAccount != address(0)) {
require(accounts[delegatingAccount].delegates[uint256(role)] == accountOrDelegate);
return delegatingAccount;
} else {
return accountOrDelegate;
}
}
/**
* @notice Returns the weight of a specified account.
* @param _account The address of the account.
* @return The weight of the specified account.
*/
function getAccountWeight(address _account) external view returns (uint256) {
Account storage account = accounts[_account];
return account.weight;
}
/**
* @notice Returns whether or not a specified account is voting.
* @param account The address of the account.
* @return Whether or not the account is voting.
*/
function isVoting(address account) public view returns (bool) {
address voter = getDelegateFromAccountAndRole(account, DelegateRole.Voting);
IGovernance governance = IGovernance(registry.getAddressFor(GOVERNANCE_REGISTRY_ID));
IValidators validators = IValidators(registry.getAddressFor(VALIDATORS_REGISTRY_ID));
return (governance.isVoting(voter) || validators.isVoting(voter));
}
/**
* @notice Returns the weight of a commitment for a given notice period.
* @param value The value of the commitment.
* @param noticePeriod The notice period of the commitment.
* @return The weight of the commitment.
* @dev A commitment's weight is (1 + sqrt(noticePeriodDays) / 30) * value.
*/
function getCommitmentWeight(uint256 value, uint256 noticePeriod) public pure returns (uint256) {
uint256 precision = 10000;
uint256 noticeDays = noticePeriod.div(1 days);
uint256 preciseMultiplier = sqrt(noticeDays).mul(precision).div(30).add(precision);
return preciseMultiplier.mul(value).div(precision);
}
/**
* @notice Returns the delegate for a specified account and role.
* @param account The address of the account.
* @param role The role to query for.
* @return The rewards recipient for the account.
*/
function getDelegateFromAccountAndRole(
address account,
DelegateRole role
)
public
view
returns (address)
{
address delegate = accounts[account].delegates[uint256(role)];
if (delegate == address(0)) {
return account;
} else {
return delegate;
}
}
// TODO(asa): Factor in governance, validator election participation.
/**
* @notice Redeems rewards accrued since the last redemption for a specified account.
* @param _account The address of the account to redeem rewards for.
* @return The amount of accrued rewards.
*/
function _redeemRewards(address _account) private returns (uint256) {
Account storage account = accounts[_account];
uint256 rewardBlockNumber = block.number.sub(1);
FixidityLib.Fraction memory previousCumulativeRewardWeight = cumulativeRewardWeights[
account.rewardsLastRedeemed
];
FixidityLib.Fraction memory cumulativeRewardWeight = cumulativeRewardWeights[
rewardBlockNumber
];
// We should never get here except in testing, where cumulativeRewardWeight will not be set.
if (previousCumulativeRewardWeight.unwrap() == 0 || cumulativeRewardWeight.unwrap() == 0) {
return 0;
}
FixidityLib.Fraction memory rewardWeight = cumulativeRewardWeight.subtract(
previousCumulativeRewardWeight
);
require(rewardWeight.unwrap() != 0, "Rewards weight does not exist");
uint256 value = rewardWeight.multiply(FixidityLib.wrap(account.weight)).fromFixed();
account.rewardsLastRedeemed = uint96(rewardBlockNumber);
if (value > 0) {
address recipient = getDelegateFromAccountAndRole(_account, DelegateRole.Rewards);
IERC20Token goldToken = IERC20Token(registry.getAddressFor(GOLD_TOKEN_REGISTRY_ID));
require(goldToken.transfer(recipient, value));
emit Withdrawal(recipient, value);
}
return value;
}
/**
* @notice Updates the Locked Gold commitment for a given notice period to a new value.
* @param account The account to update the Locked Gold commitment for.
* @param value The new value of the Locked Gold commitment.
* @param noticePeriod The notice period of the Locked Gold commitment.
*/
function updateLockedCommitment(
Account storage account,
uint256 value,
uint256 noticePeriod
)
private
{
Commitment storage locked = account.commitments.locked[noticePeriod];
require(value != locked.value);
uint256 weight;
if (locked.value == 0) {
locked.index = uint128(account.commitments.noticePeriods.length);
locked.value = uint128(value);
account.commitments.noticePeriods.push(noticePeriod);
weight = getCommitmentWeight(value, noticePeriod);
account.weight = account.weight.add(weight);
totalWeight = totalWeight.add(weight);
} else if (value == 0) {
weight = getCommitmentWeight(locked.value, noticePeriod);
account.weight = account.weight.sub(weight);
totalWeight = totalWeight.sub(weight);
deleteCommitment(locked, account.commitments, CommitmentType.Locked);
} else {
uint256 originalWeight = getCommitmentWeight(locked.value, noticePeriod);
weight = getCommitmentWeight(value, noticePeriod);
uint256 difference;
if (weight >= originalWeight) {
difference = weight.sub(originalWeight);
account.weight = account.weight.add(difference);
totalWeight = totalWeight.add(difference);
} else {
difference = originalWeight.sub(weight);
account.weight = account.weight.sub(difference);
totalWeight = totalWeight.sub(difference);
}
locked.value = uint128(value);
}
}
/**
* @notice Updates the notified commitment for a given availability time to a new value.
* @param account The account to update the notified commitment for.
* @param value The new value of the notified commitment.
* @param availabilityTime The availability time of the notified commitment.
*/
function updateNotifiedDeposit(
Account storage account,
uint256 value,
uint256 availabilityTime
)
private
{
Commitment storage notified = account.commitments.notified[availabilityTime];
require(value != notified.value);
if (notified.value == 0) {
notified.index = uint128(account.commitments.availabilityTimes.length);
notified.value = uint128(value);
account.commitments.availabilityTimes.push(availabilityTime);
account.weight = account.weight.add(notified.value);
totalWeight = totalWeight.add(notified.value);
} else if (value == 0) {
account.weight = account.weight.sub(notified.value);
totalWeight = totalWeight.sub(notified.value);
deleteCommitment(notified, account.commitments, CommitmentType.Notified);
} else {
uint256 difference;
if (value >= notified.value) {
difference = value.sub(notified.value);
account.weight = account.weight.add(difference);
totalWeight = totalWeight.add(difference);
} else {
difference = uint256(notified.value).sub(value);
account.weight = account.weight.sub(difference);
totalWeight = totalWeight.sub(difference);
}
notified.value = uint128(value);
}
}
/**
* @notice Deletes a commitment from an account.
* @param _commitment The commitment to delete.
* @param commitments The struct containing the account's commitments.
* @param commitmentType Whether the deleted commitment is locked or notified.
*/
function deleteCommitment(
Commitment storage _commitment,
Commitments storage commitments,
CommitmentType commitmentType
)
private
{
uint256 lastIndex;
if (commitmentType == CommitmentType.Locked) {
lastIndex = commitments.noticePeriods.length.sub(1);
commitments.locked[commitments.noticePeriods[lastIndex]].index = _commitment.index;
deleteElement(commitments.noticePeriods, _commitment.index, lastIndex);
} else {
lastIndex = commitments.availabilityTimes.length.sub(1);
commitments.notified[commitments.availabilityTimes[lastIndex]].index = _commitment.index;
deleteElement(commitments.availabilityTimes, _commitment.index, lastIndex);
}
// Delete commitment info.
_commitment.index = 0;
_commitment.value = 0;
}
/**
* @notice Deletes an element from a list of uint256s.
* @param list The list of uint256s.
* @param index The index of the element to delete.
* @param lastIndex The index of the last element in the list.
*/
function deleteElement(uint256[] storage list, uint256 index, uint256 lastIndex) private {
list[index] = list[lastIndex];
list[lastIndex] = 0;
list.length = lastIndex;
}
/**
* @notice Check if an account already exists.
* @param account The address of the account
* @return Returns `true` if account exists. Returns `false` otherwise.
* In particular it will return `false` if a delegate with given address exists.
*/
function isAccount(address account) public view returns (bool) {
return (accounts[account].exists);
}
/**
* @notice Check if a delegate already exists.
* @param account The address of the delegate
* @return Returns `true` if delegate exists. Returns `false` otherwise.
*/
function isDelegate(address account) external view returns (bool) {
return (delegations[account] != address(0));
}
function isNotAccount(address account) internal view returns (bool) {
return (!accounts[account].exists);
}
// Reverts if rewards, voting, or validating rights have been delegated to `account`.
function isNotDelegate(address account) internal view returns (bool) {
return (delegations[account] == address(0));
}
// TODO(asa): Allow users to notify if they would continue to meet the registration
// requirements.
function isNotValidating(address account) internal view returns (bool) {
address validator = getDelegateFromAccountAndRole(account, DelegateRole.Validating);
IValidators validators = IValidators(registry.getAddressFor(VALIDATORS_REGISTRY_ID));
return (!validators.isValidating(validator));
}
// TODO: consider using Fixidity's roots
/**
* @notice Approxmiates the square root of x using the Bablyonian method.
* @param x The number to take the square root of.
* @return An approximation of the square root of x.
* @dev The error can be large for smaller numbers, so we multiply by the square of `precision`.
*/
function sqrt(uint256 x) private pure returns (FractionUtil.Fraction memory) {
uint256 precision = 100;
uint256 px = x.mul(precision.mul(precision));
uint256 z = px.add(1).div(2);
uint256 y = px;
while (z < y) {
y = z;
z = px.div(z).add(z).div(2);
}
return FractionUtil.Fraction(y, precision);
}
}
| TODO(asa): Factor in governance, validator election participation. Redeems rewards accrued since the last redemption for a specified account. _account The address of the account to redeem rewards for. return The amount of accrued rewards./ We should never get here except in testing, where cumulativeRewardWeight will not be set. | function _redeemRewards(address _account) private returns (uint256) {
Account storage account = accounts[_account];
uint256 rewardBlockNumber = block.number.sub(1);
FixidityLib.Fraction memory previousCumulativeRewardWeight = cumulativeRewardWeights[
account.rewardsLastRedeemed
];
FixidityLib.Fraction memory cumulativeRewardWeight = cumulativeRewardWeights[
rewardBlockNumber
];
if (previousCumulativeRewardWeight.unwrap() == 0 || cumulativeRewardWeight.unwrap() == 0) {
return 0;
}
FixidityLib.Fraction memory rewardWeight = cumulativeRewardWeight.subtract(
previousCumulativeRewardWeight
);
require(rewardWeight.unwrap() != 0, "Rewards weight does not exist");
uint256 value = rewardWeight.multiply(FixidityLib.wrap(account.weight)).fromFixed();
account.rewardsLastRedeemed = uint96(rewardBlockNumber);
if (value > 0) {
address recipient = getDelegateFromAccountAndRole(_account, DelegateRole.Rewards);
IERC20Token goldToken = IERC20Token(registry.getAddressFor(GOLD_TOKEN_REGISTRY_ID));
require(goldToken.transfer(recipient, value));
emit Withdrawal(recipient, value);
}
return value;
}
| 14,091,308 |
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-asset-proxy/contracts/src/interfaces/IUniswapExchangeFactory.sol";
import "@0x/contracts-erc20/contracts/src/LibERC20Token.sol";
import "@0x/contracts-exchange/contracts/src/interfaces/IExchange.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "./IERC20BridgeSampler.sol";
import "./IEth2Dai.sol";
import "./IKyberNetwork.sol";
import "./IUniswapExchangeQuotes.sol";
import "./DeploymentConstants.sol";
contract ERC20BridgeSampler is
IERC20BridgeSampler,
DeploymentConstants
{
bytes4 constant internal ERC20_PROXY_ID = 0xf47261b0; // bytes4(keccak256("ERC20Token(address)"));
/// @dev Query native orders and sample sell quotes on multiple DEXes at once.
/// @param orders Native orders to query.
/// @param sources Address of each DEX. Passing in an unsupported DEX will throw.
/// @param takerTokenAmounts Taker token sell amount for each sample.
/// @return orderInfos `OrderInfo`s for each order in `orders`.
/// @return makerTokenAmountsBySource Maker amounts bought for each source at
/// each taker token amount. First indexed by source index, then sample
/// index.
function queryOrdersAndSampleSells(
LibOrder.Order[] memory orders,
address[] memory sources,
uint256[] memory takerTokenAmounts
)
public
view
returns (
LibOrder.OrderInfo[] memory orderInfos,
uint256[][] memory makerTokenAmountsBySource
)
{
require(orders.length != 0, "EMPTY_ORDERS");
orderInfos = queryOrders(orders);
makerTokenAmountsBySource = sampleSells(
sources,
_assetDataToTokenAddress(orders[0].takerAssetData),
_assetDataToTokenAddress(orders[0].makerAssetData),
takerTokenAmounts
);
}
/// @dev Query native orders and sample buy quotes on multiple DEXes at once.
/// @param orders Native orders to query.
/// @param sources Address of each DEX. Passing in an unsupported DEX will throw.
/// @param makerTokenAmounts Maker token buy amount for each sample.
/// @return orderInfos `OrderInfo`s for each order in `orders`.
/// @return takerTokenAmountsBySource Taker amounts sold for each source at
/// each maker token amount. First indexed by source index, then sample
/// index.
function queryOrdersAndSampleBuys(
LibOrder.Order[] memory orders,
address[] memory sources,
uint256[] memory makerTokenAmounts
)
public
view
returns (
LibOrder.OrderInfo[] memory orderInfos,
uint256[][] memory makerTokenAmountsBySource
)
{
require(orders.length != 0, "EMPTY_ORDERS");
orderInfos = queryOrders(orders);
makerTokenAmountsBySource = sampleBuys(
sources,
_assetDataToTokenAddress(orders[0].takerAssetData),
_assetDataToTokenAddress(orders[0].makerAssetData),
makerTokenAmounts
);
}
/// @dev Queries the status of several native orders.
/// @param orders Native orders to query.
/// @return orderInfos Order info for each respective order.
function queryOrders(LibOrder.Order[] memory orders)
public
view
returns (LibOrder.OrderInfo[] memory orderInfos)
{
uint256 numOrders = orders.length;
orderInfos = new LibOrder.OrderInfo[](numOrders);
for (uint256 i = 0; i < numOrders; i++) {
orderInfos[i] = _getExchangeContract().getOrderInfo(orders[i]);
}
}
/// @dev Sample sell quotes on multiple DEXes at once.
/// @param sources Address of each DEX. Passing in an unsupported DEX will throw.
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param takerTokenAmounts Taker token sell amount for each sample.
/// @return makerTokenAmountsBySource Maker amounts bought for each source at
/// each taker token amount. First indexed by source index, then sample
/// index.
function sampleSells(
address[] memory sources,
address takerToken,
address makerToken,
uint256[] memory takerTokenAmounts
)
public
view
returns (uint256[][] memory makerTokenAmountsBySource)
{
uint256 numSources = sources.length;
makerTokenAmountsBySource = new uint256[][](numSources);
for (uint256 i = 0; i < numSources; i++) {
makerTokenAmountsBySource[i] = _sampleSellSource(
sources[i],
takerToken,
makerToken,
takerTokenAmounts
);
}
}
/// @dev Query native orders and sample buy quotes on multiple DEXes at once.
/// @param sources Address of each DEX. Passing in an unsupported DEX will throw.
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param makerTokenAmounts Maker token buy amount for each sample.
/// @return takerTokenAmountsBySource Taker amounts sold for each source at
/// each maker token amount. First indexed by source index, then sample
/// index.
function sampleBuys(
address[] memory sources,
address takerToken,
address makerToken,
uint256[] memory makerTokenAmounts
)
public
view
returns (uint256[][] memory takerTokenAmountsBySource)
{
uint256 numSources = sources.length;
takerTokenAmountsBySource = new uint256[][](numSources);
for (uint256 i = 0; i < numSources; i++) {
takerTokenAmountsBySource[i] = _sampleBuySource(
sources[i],
takerToken,
makerToken,
makerTokenAmounts
);
}
}
/// @dev Sample sell quotes from Kyber.
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param takerTokenAmounts Taker token sell amount for each sample.
/// @return makerTokenAmounts Maker amounts bought at each taker token
/// amount.
function sampleSellsFromKyberNetwork(
address takerToken,
address makerToken,
uint256[] memory takerTokenAmounts
)
public
view
returns (uint256[] memory makerTokenAmounts)
{
_assertValidPair(makerToken, takerToken);
address _takerToken = takerToken == _getWETHAddress() ? KYBER_ETH_ADDRESS : takerToken;
address _makerToken = makerToken == _getWETHAddress() ? KYBER_ETH_ADDRESS : makerToken;
uint256 takerTokenDecimals = _getTokenDecimals(takerToken);
uint256 makerTokenDecimals = _getTokenDecimals(makerToken);
uint256 numSamples = takerTokenAmounts.length;
makerTokenAmounts = new uint256[](numSamples);
for (uint256 i = 0; i < numSamples; i++) {
(uint256 rate,) = _getKyberNetworkContract().getExpectedRate(
_takerToken,
_makerToken,
takerTokenAmounts[i]
);
makerTokenAmounts[i] =
rate *
takerTokenAmounts[i] *
10 ** makerTokenDecimals /
10 ** takerTokenDecimals /
10 ** 18;
}
}
/// @dev Sample sell quotes from Eth2Dai/Oasis.
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param takerTokenAmounts Taker token sell amount for each sample.
/// @return makerTokenAmounts Maker amounts bought at each taker token
/// amount.
function sampleSellsFromEth2Dai(
address takerToken,
address makerToken,
uint256[] memory takerTokenAmounts
)
public
view
returns (uint256[] memory makerTokenAmounts)
{
_assertValidPair(makerToken, takerToken);
uint256 numSamples = takerTokenAmounts.length;
makerTokenAmounts = new uint256[](numSamples);
for (uint256 i = 0; i < numSamples; i++) {
makerTokenAmounts[i] = _getEth2DaiContract().getBuyAmount(
makerToken,
takerToken,
takerTokenAmounts[i]
);
}
}
/// @dev Sample buy quotes from Eth2Dai/Oasis.
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param takerTokenAmounts Maker token sell amount for each sample.
/// @return takerTokenAmounts Taker amounts sold at each maker token
/// amount.
function sampleBuysFromEth2Dai(
address takerToken,
address makerToken,
uint256[] memory makerTokenAmounts
)
public
view
returns (uint256[] memory takerTokenAmounts)
{
_assertValidPair(makerToken, takerToken);
uint256 numSamples = makerTokenAmounts.length;
takerTokenAmounts = new uint256[](numSamples);
for (uint256 i = 0; i < numSamples; i++) {
takerTokenAmounts[i] = _getEth2DaiContract().getPayAmount(
takerToken,
makerToken,
makerTokenAmounts[i]
);
}
}
/// @dev Sample sell quotes from Uniswap.
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param takerTokenAmounts Taker token sell amount for each sample.
/// @return makerTokenAmounts Maker amounts bought at each taker token
/// amount.
function sampleSellsFromUniswap(
address takerToken,
address makerToken,
uint256[] memory takerTokenAmounts
)
public
view
returns (uint256[] memory makerTokenAmounts)
{
_assertValidPair(makerToken, takerToken);
uint256 numSamples = takerTokenAmounts.length;
makerTokenAmounts = new uint256[](numSamples);
IUniswapExchangeQuotes takerTokenExchange = takerToken == _getWETHAddress() ?
IUniswapExchangeQuotes(0) : _getUniswapExchange(takerToken);
IUniswapExchangeQuotes makerTokenExchange = makerToken == _getWETHAddress() ?
IUniswapExchangeQuotes(0) : _getUniswapExchange(makerToken);
for (uint256 i = 0; i < numSamples; i++) {
if (makerToken == _getWETHAddress()) {
makerTokenAmounts[i] = takerTokenExchange.getTokenToEthInputPrice(
takerTokenAmounts[i]
);
} else if (takerToken == _getWETHAddress()) {
makerTokenAmounts[i] = makerTokenExchange.getEthToTokenInputPrice(
takerTokenAmounts[i]
);
} else {
uint256 ethBought = takerTokenExchange.getTokenToEthInputPrice(
takerTokenAmounts[i]
);
makerTokenAmounts[i] = makerTokenExchange.getEthToTokenInputPrice(
ethBought
);
}
}
}
/// @dev Sample buy quotes from Uniswap.
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param makerTokenAmounts Maker token sell amount for each sample.
/// @return takerTokenAmounts Taker amounts sold at each maker token
/// amount.
function sampleBuysFromUniswap(
address takerToken,
address makerToken,
uint256[] memory makerTokenAmounts
)
public
view
returns (uint256[] memory takerTokenAmounts)
{
_assertValidPair(makerToken, takerToken);
uint256 numSamples = makerTokenAmounts.length;
takerTokenAmounts = new uint256[](numSamples);
IUniswapExchangeQuotes takerTokenExchange = takerToken == _getWETHAddress() ?
IUniswapExchangeQuotes(0) : _getUniswapExchange(takerToken);
IUniswapExchangeQuotes makerTokenExchange = makerToken == _getWETHAddress() ?
IUniswapExchangeQuotes(0) : _getUniswapExchange(makerToken);
for (uint256 i = 0; i < numSamples; i++) {
if (makerToken == _getWETHAddress()) {
takerTokenAmounts[i] = takerTokenExchange.getTokenToEthOutputPrice(
makerTokenAmounts[i]
);
} else if (takerToken == _getWETHAddress()) {
takerTokenAmounts[i] = makerTokenExchange.getEthToTokenOutputPrice(
makerTokenAmounts[i]
);
} else {
uint256 ethSold = makerTokenExchange.getEthToTokenOutputPrice(
makerTokenAmounts[i]
);
takerTokenAmounts[i] = takerTokenExchange.getTokenToEthOutputPrice(
ethSold
);
}
}
}
/// @dev Overridable way to get token decimals.
/// @param tokenAddress Address of the token.
/// @return decimals The decimal places for the token.
function _getTokenDecimals(address tokenAddress)
internal
view
returns (uint8 decimals)
{
return LibERC20Token.decimals(tokenAddress);
}
/// @dev Samples a supported sell source, defined by its address.
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param takerTokenAmounts Taker token sell amount for each sample.
/// @return makerTokenAmounts Maker amounts bought at each taker token
/// amount.
function _sampleSellSource(
address source,
address takerToken,
address makerToken,
uint256[] memory takerTokenAmounts
)
private
view
returns (uint256[] memory makerTokenAmounts)
{
if (source == address(_getEth2DaiContract())) {
return sampleSellsFromEth2Dai(takerToken, makerToken, takerTokenAmounts);
}
if (source == address(_getUniswapExchangeFactoryContract())) {
return sampleSellsFromUniswap(takerToken, makerToken, takerTokenAmounts);
}
if (source == address(_getKyberNetworkContract())) {
return sampleSellsFromKyberNetwork(takerToken, makerToken, takerTokenAmounts);
}
revert("UNSUPPORTED_SOURCE");
}
/// @dev Samples a supported buy source, defined by its address.
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param makerTokenAmounts Maker token sell amount for each sample.
/// @return takerTokenAmounts Taker amounts sold at each maker token
/// amount.
function _sampleBuySource(
address source,
address takerToken,
address makerToken,
uint256[] memory makerTokenAmounts
)
private
view
returns (uint256[] memory takerTokenAmounts)
{
if (source == address(_getEth2DaiContract())) {
return sampleBuysFromEth2Dai(takerToken, makerToken, makerTokenAmounts);
}
if (source == address(_getUniswapExchangeFactoryContract())) {
return sampleBuysFromUniswap(takerToken, makerToken, makerTokenAmounts);
}
revert("UNSUPPORTED_SOURCE");
}
/// @dev Retrive an existing Uniswap exchange contract.
/// Throws if the exchange does not exist.
/// @param tokenAddress Address of the token contract.
/// @return exchange `IUniswapExchangeQuotes` for the token.
function _getUniswapExchange(address tokenAddress)
private
view
returns (IUniswapExchangeQuotes exchange)
{
exchange = IUniswapExchangeQuotes(
address(_getUniswapExchangeFactoryContract().getExchange(tokenAddress))
);
require(address(exchange) != address(0), "UNSUPPORTED_UNISWAP_EXCHANGE");
}
/// @dev Extract the token address from ERC20 proxy asset data.
/// @param assetData ERC20 asset data.
/// @return tokenAddress The decoded token address.
function _assetDataToTokenAddress(bytes memory assetData)
private
pure
returns (address tokenAddress)
{
require(assetData.length == 36, "INVALID_ASSET_DATA");
bytes4 selector;
assembly {
selector := and(mload(add(assetData, 0x20)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
tokenAddress := mload(add(assetData, 0x24))
}
require(selector == ERC20_PROXY_ID, "UNSUPPORTED_ASSET_PROXY");
}
function _assertValidPair(address makerToken, address takerToken)
private
pure
{
require(makerToken != takerToken, "INVALID_TOKEN_PAIR");
}
}
| Sample sell quotes on multiple DEXes at once. sources Address of each DEX. Passing in an unsupported DEX will throw. takerToken Address of the taker token (what to sell). makerToken Address of the maker token (what to buy). takerTokenAmounts Taker token sell amount for each sample. return makerTokenAmountsBySource Maker amounts bought for each source at each taker token amount. First indexed by source index, then sample index. | function sampleSells(
address[] memory sources,
address takerToken,
address makerToken,
uint256[] memory takerTokenAmounts
)
public
view
returns (uint256[][] memory makerTokenAmountsBySource)
{
uint256 numSources = sources.length;
makerTokenAmountsBySource = new uint256[][](numSources);
for (uint256 i = 0; i < numSources; i++) {
makerTokenAmountsBySource[i] = _sampleSellSource(
sources[i],
takerToken,
makerToken,
takerTokenAmounts
);
}
}
| 5,377,154 |
pragma solidity ^0.4.16;
pragma experimental "v0.5.0";
pragma experimental "ABIEncoderV2";
import {Memory} from "../unsafe/Memory.sol";
library Bytes {
// Check if two 'bytes memory' are equal. Equality is defined as such:
// firstBytes.length == secondBytes.length (= length)
// for 0 <= i < length, firstBytes[i] == secondBytes[i]
function equals(bytes memory self, bytes memory other) internal pure returns (bool equal) {
if (self.length != other.length) {
return false;
}
uint addr;
uint addr2;
assembly {
addr := add(self, 0x20)
addr2 := add(other, 0x20)
}
equal = Memory.equals(addr, addr2, self.length);
}
// Check if two bytes references are the same, i.e. has the same memory address.
// If 'equals(self, other) == true', but 'equalsRef(self, other) == false', then
// 'self' and 'other' must be independent copies of each other.
function equalsRef(bytes memory self, bytes memory other) internal pure returns (bool equal) {
equal = Memory.ptr(self) == Memory.ptr(other);
}
function copy(bytes memory self) internal pure returns (bytes memory) {
if (self.length == 0) {
return;
}
var addr = Memory.dataPtr(self);
return Memory.toBytes(addr, self.length);
}
function copy(bytes memory self, uint startIdx) internal pure returns (bytes memory) {
require(startIdx < self.length);
var len = self.length - startIdx;
var addr = Memory.dataPtr(self);
return Memory.toBytes(addr + startIdx, len);
}
function copy(bytes memory self, uint startIdx, uint len) internal pure returns (bytes memory) {
require(startIdx < self.length && startIdx + len <= self.length);
if (len == 0) {
return;
}
var addr = Memory.dataPtr(self);
return Memory.toBytes(addr + startIdx, len);
}
function concat(bytes memory self, bytes memory other) internal pure returns (bytes memory) {
bytes memory ret = new bytes(self.length + other.length);
var (src, srcLen) = Memory.fromBytes(self);
var (src2, src2Len) = Memory.fromBytes(other);
var (dest,) = Memory.fromBytes(ret);
var dest2 = dest + src2Len;
Memory.copy(src, dest, srcLen);
Memory.copy(src2, dest2, src2Len);
return ret;
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*
*/
function lowestByteSet(bytes32 self) internal pure returns (uint) {
require(self != 0);
uint ret;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) >> 128);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) >> 64);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) >> 32);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) >> 16);
}
if (self & 0xff == 0) {
ret += 1;
}
return ret;
}
function highestByteSet(bytes32 self) internal pure returns (uint) {
require(self != 0);
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000 != 0) {
ret += 16;
self = bytes32(uint(self) >> 128);
}
if (self & 0xffffffffffffffff0000000000000000 != 0) {
ret += 8;
self = bytes32(uint(self) >> 64);
}
if (self & 0xffffffff00000000 != 0) {
ret += 4;
self = bytes32(uint(self) >> 32);
}
if (self & 0xffff0000 != 0) {
ret += 2;
self = bytes32(uint(self) >> 16);
}
if (self & 0xff00 != 0) {
ret += 1;
}
return ret;
}
// Shaves of leading 0 bytes and writes the remaining string to a 'memory bytes'
function toBytes(bytes32 b32) internal pure returns (bytes memory bts) {
if (b32 == 0) {
return;
}
uint lbs = lowestByteSet(b32);
uint bu = uint(b32);
bts = new bytes(32 - lbs);
assembly {
mstore(add(bts, 0x20), bu)
}
return bts;
}
} | Returns the length of a null-terminated bytes32 string. self The value to find the length of. return The length of the string, from 0 to 32./ | function lowestByteSet(bytes32 self) internal pure returns (uint) {
require(self != 0);
uint ret;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) >> 128);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) >> 64);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) >> 32);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) >> 16);
}
if (self & 0xff == 0) {
ret += 1;
}
return ret;
}
| 12,992,532 |
./full_match/43114/0xb15CbBb6A9C79C957452C847DAec313542149E19/sources/PUMPKINS/subchef.sol | 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);
pool.lpSupply = pool.lpSupply.sub(user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
| 4,566,927 |
pragma solidity ^0.5.0;
import "./ApplicationRegistryMetadata.sol";
import "./interfaces/IApplicationRegistry.sol";
import "./interfaces/IARStorage.sol";
import "../../request-verification-layer/permission-module/Protected.sol";
import "../../common/libraries/SafeMath.sol";
import "../../common/component/SystemComponent.sol";
/**
* @title Application registry
*/
contract ApplicationRegistry is IApplicationRegistry, Protected, SystemComponent, ApplicationRegistryMetadata {
// Declare libraries
using SafeMath for uint;
// Stora storage address
address arStorage;
// Initialize contract
constructor(address componentsRegistry, address storageAddr)
public
WithComponentsRegistry(componentsRegistry)
{
componentName = APPLICATION_REGISTRY_NAME;
componentId = APPLICATION_REGISTRY_ID;
arStorage = storageAddr;
}
/**
* @notice Create application in the "CAT registry"
* @param app Application address
*/
function createCATApp(address app)
public
verifyPermission(msg.sig, msg.sender)
{
require(app != address(0), "Invalid application address.");
IARStorage s = ARSStorage();
uint index = s.getCATAppsLength();
s.pushNewCATApp(app);
s.setCATAppIndex(app, index);
s.setCATAppRegistrationStatus(app, true);
s.emitCATAppCreated(app);
}
/**
* @notice Remove application from the "CAT registry"
* @param app Application to be removed
*/
function removeCATApp(address app)
public
verifyPermission(msg.sig, msg.sender)
{
require(app != address(0), "Invalid application address.");
IARStorage s = ARSStorage();
uint index = s.getCATAppIndex(app);
uint last = s.getCATAppsLength().sub(1);
if (last > 0) {
address toUpdate = s.getCATAppByIndex(last);
s.addCATAppToIndex(toUpdate, index);
s.setCATAppIndex(toUpdate, index);
}
s.deleteCATAppFromTheList(last);
s.deleteCATAppIndex(app);
s.setCATAppsLength(last);
s.setCATAppRegistrationStatus(app, false);
s.emitCATAppRemoved(app);
}
/**
* @notice Pause application in the "CAT registry"
* @param app Application to be paused
* @param status New application status
*/
function changeCATAppStatus(address app, bool status)
public
verifyPermission(msg.sig, msg.sender)
{
require(app != address(0), "Invalid application address.");
IARStorage s = ARSStorage();
uint index = s.getCATAppIndex(app);
s.setCATAppStatus(index, status);
s.emitCATAppStatusUpdated(app, status);
}
/**
* @notice Create application in the "Token registry"
* @param app Application address
* @param token Token address
*/
function createTokenApp(address app, address token)
public
verifyPermissionForToken(msg.sig, msg.sender, token)
{
require(app != address(0), "Invalid application address.");
require(token != address(0), "Invalid token address.");
IARStorage s = ARSStorage();
uint index = s.getTokenAppsLength(token);
s.pushNewTokenApp(app, token);
s.setTokenAppIndex(app, token, index);
s.setTokenAppStatus(index, token, true);
s.emitTokenAppCreated(app, token);
}
/**
* @notice Remove application from the "Token registry"
* @param app Application to be removed
* @param token Token address
*/
function removeTokenApp(address app, address token)
public
verifyPermissionForToken(msg.sig, msg.sender, token)
{
require(app != address(0), "Invalid application address.");
require(token != address(0), "Invalid token address.");
IARStorage s = ARSStorage();
uint index = s.getTokenAppIndex(app, token);
uint last = s.getTokenAppsLength(token).sub(1);
if (last > 0) {
address toUpdate = s.getTokenAppByIndex(last, token);
s.addTokenAppToIndex(toUpdate, token, index);
s.setTokenAppIndex(toUpdate, token, index);
}
s.setTokenAppStatus(last, token, false);
s.deleteTokenAppFromTheList(last, token);
s.deleteTokenAppIndex(app, token);
s.setTokenAppsLength(last, token);
s.emitTokenAppRemoved(app, token);
}
/**
* @notice Change application status in the "Token registry"
* @param app Application address
* @param token Token address
* @param status New application status
*/
function changeTokenAppStatus(address app, address token, bool status)
public
verifyPermissionForToken(msg.sig, msg.sender, token)
{
require(app != address(0), "Invalid application address.");
require(token != address(0), "Invalid token address.");
IARStorage s = ARSStorage();
uint index = s.getTokenAppIndex(app, token);
s.setTokenAppStatus(index, token, status);
s.emitTokenAppStatusUpdated(app, token, status);
}
/**
* @notice Checks whether an application is registered or not
* @param app Application address
*/
function isRegisteredApp(address app, address token) public view returns (bool) {
IARStorage s = ARSStorage();
bool result = s.getCATAppStatusByAddress(app);
if (!result && token != address(0)) {
return s.getTokenAppStatusByAddress(app, token);
}
return result;
}
/**
* @notice Returns IARStorage instance
*/
function ARSStorage() internal view returns (IARStorage) {
return IARStorage(arStorage);
}
} | Create application in the "Token registry" app Application address token Token address/ | function createTokenApp(address app, address token)
public
verifyPermissionForToken(msg.sig, msg.sender, token)
{
require(app != address(0), "Invalid application address.");
require(token != address(0), "Invalid token address.");
IARStorage s = ARSStorage();
uint index = s.getTokenAppsLength(token);
s.pushNewTokenApp(app, token);
s.setTokenAppIndex(app, token, index);
s.setTokenAppStatus(index, token, true);
s.emitTokenAppCreated(app, token);
}
| 2,569,097 |
./partial_match/1/0x891696CCa87aa2f175124b412198c23D54680E31/sources/NFTWinner.sol | Returns the `nextInitialized` flag set if `quantity` equals 1./ For branchless setting of the `nextInitialized` flag. `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`. | function _nextInitializedFlag(uint256 quantity)
private
pure
returns (uint256 result)
{
assembly {
result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
| 3,585,515 |
// File: zos-lib/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.6.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-eth/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.2;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is Initializable, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @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 A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to 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) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(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 value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.2;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.2;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is Initializable, ERC20 {
/**
* @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);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/access/Roles.sol
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-eth/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.2;
contract PauserRole is Initializable {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.2;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Initializable, PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
function initialize(address sender) public initializer {
PauserRole.initialize(sender);
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.5.2;
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is Initializable, ERC20, Pausable {
function initialize(address sender) public initializer {
Pausable.initialize(sender);
}
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/math/Math.sol
pragma solidity ^0.5.2;
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: openzeppelin-eth/contracts/utils/Arrays.sol
pragma solidity ^0.5.2;
/**
* @title Arrays
* @dev Utility library of inline array functions
*/
library Arrays {
/**
* @dev Upper bound search function which is kind of binary search algorithm. It searches sorted
* array to find index of the element value. If element is found then returns its index otherwise
* it returns index of first element which is greater than searched value. If searched element is
* bigger than any array element function then returns first index after last element (i.e. all
* values inside the array are smaller than the target). Complexity O(log n).
* @param array The array sorted in ascending order.
* @param element The element's value to be found.
* @return The calculated index value. Returns 0 for empty array.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// File: openzeppelin-eth/contracts/drafts/Counters.sol
pragma solidity ^0.5.2;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: openzeppelin-eth/contracts/drafts/ERC20Snapshot.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 token with snapshots.
* @dev Inspired by Jordi Baylina's MiniMeToken to record historical balances:
* https://github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
* When a snapshot is made, the balances and totalSupply at the time of the snapshot are recorded for later
* access.
*
* To make a snapshot, call the `snapshot` function, which will emit the `Snapshot` event and return a snapshot id.
* To get the total supply from a snapshot, call the function `totalSupplyAt` with the snapshot id.
* To get the balance of an account from a snapshot, call the `balanceOfAt` function with the snapshot id and the
* account address.
* @author Validity Labs AG <[email protected]>
*/
contract ERC20Snapshot is Initializable, ERC20 {
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnaphots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
event Snapshot(uint256 id);
// Creates a new snapshot id. Balances are only stored in snapshots on demand: unless a snapshot was taken, a
// balance change will not be recorded. This means the extra added cost of storing snapshotted balances is only paid
// when required, but is also flexible enough that it allows for e.g. daily snapshots.
function snapshot() public returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnaphots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0);
require(snapshotId <= _currentSnapshotId.current());
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnaphots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.2;
contract MinterRole is Initializable {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.2;
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
uint256[50] private ______gap;
}
// File: contracts/CircuitsOfValue.sol
// contracts/CustomERC20.sol
pragma solidity ^0.5.0;
contract CircuitsOfValue is Initializable, ERC20, ERC20Detailed, ERC20Burnable, ERC20Pausable, ERC20Snapshot, ERC20Mintable {
bool private _pausableInitialized;
function initialize( string memory name, string memory symbol, uint8 decimals, uint256 initialSupply, address initialHolder )
public initializer {
// require(initialSupply > 0, "");
ERC20Detailed.initialize(name, symbol, decimals);
ERC20Mintable.initialize(msg.sender);
initializePausable(msg.sender);
// _mint(initialHolder, initialSupply);
}
function initializePausable(address sender) public {
require(!_pausableInitialized, "pausable has already been initialized");
_pausableInitialized = true;
_addPauser(sender);
}
}
| _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. The same is true for the total supply and _mint and _burn. | function _transfer(address from, address to, uint256 value) internal {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
| 1,156,844 |
/**
*Submitted for verification at Etherscan.io on 2020-04-17
*/
pragma solidity ^0.6.2;
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/GSN/GSNRecipient.sol
// But kept minimalist.
contract MsgSender {
address public relayHub;
/**
* @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions,
* and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`).
*
* IMPORTANT: Contracts derived from {MsgSender} should never use `msg.sender`, and use {_msgSender} instead.
*/
function _msgSender() internal view virtual returns (address payable) {
if (msg.sender != relayHub) {
return msg.sender;
} else {
return _getRelayedCallSender();
}
}
function _getRelayedCallSender() private pure returns (address payable result) {
// We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array
// is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing
// so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would
// require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20
// bytes. This can always be done due to the 32-byte prefix.
// The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the
// easiest/most-efficient way to perform this operation.
// These fields are not accessible from assembly
bytes memory array = msg.data;
uint256 index = msg.data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
}
// Fetch beacon
contract CommunityOracle is MsgSender {
// Used to count submissions
mapping (address => bool) public appointedOracle;
mapping (address => bool) public oracleSubmitted;
mapping (string => uint) public proposals;
string[] public proposalList;
uint public submitted;
uint public minimumOracles;
event Beacon(string bls, uint beacon);
/**
* Sets up the community oracle service for CyberDice.
* @param _oracles A list of appointed oracles.
* @param _minimumOracles Minimum number of votes required for a beacon proposal.
**/
constructor(address[] memory _oracles, uint _minimumOracles, address _relayHub) public {
require(_oracles.length > _minimumOracles, "More appointed oracles are required");
for(uint i=0; i<_oracles.length; i++) {
appointedOracle[_oracles[i]] = true;
}
minimumOracles = _minimumOracles;
relayHub = _relayHub;
}
/**
* Collect beacon proposal from an appointed oracle
*/
function submitBeacon(string memory _proposal) public {
require(appointedOracle[_msgSender()], "Only appointed oracle");
require(!oracleSubmitted[_msgSender()], "Appointed oracle has already submitted");
oracleSubmitted[_msgSender()] = true;
submitted = submitted + 1;
// Easy to iterate list.
if(proposals[_proposal] == 0) {
proposalList.push(_proposal);
}
proposals[_proposal] = proposals[_proposal] + 1;
}
// Count submissions by the oracles
// Returns 0 if beacon is not yet ready.
function getBeacon() public returns (uint) {
require(submitted >= minimumOracles, "A minimum number of oracles must respond before fetching beacon");
string memory winningProposal = proposalList[0];
// Compare votes for each unique solution sent
for(uint i=1; i<proposalList.length; i++) {
string memory proposal = proposalList[i];
// More votes?
if(proposals[proposal] > proposals[winningProposal]) {
winningProposal = proposal;
}
}
uint beacon = uint(keccak256(abi.encode(winningProposal)));
emit Beacon(winningProposal, beacon);
return beacon;
}
}
/*
* Author: Patrick McCorry (anydot)
*
* An on-chain competition to win prize money.
*
* How to enter:
* Developers simply need to call submit() and send it via the any.sender service.
*
* - Skills required to play:
* All tickets must be sent via the any.sender service, so it requires techncial skill (e.g. developer)
* to participate in the competition. We have added some extra "ticket bumps" during the game,
* so it might be worth writing a script that can watch out for the bumps to purchase extra tickets.
*
* - How it works:
* Users can have one or more tickets, and all tickets are appended to a list.
* When the game ends, we'll use the blockhash as a random beacon and it will
* a random index in the list of tickets. Whoever owns that ticket is the winner.
* We took inspiration from https://www.cl.cam.ac.uk/~fms27/papers/2008-StajanoCla-cyberdice.pdf
*
* - Minting tickets:
* We have added rules on how the tickets are minted, so please
* check out getNoTickets() for up to date information.
*
* - Why did we make a competition?
* It really demonstrates the power of Ethereum and the any.sender service.
*
*/
contract CyberDice is MsgSender {
// Let thy explode
mapping(address => uint) public userTickets;
address[] public entries;
// any.sender relayers
mapping(address => bool) public relayers;
uint public startBlock; // used for the bumping feature
uint public deadline; // competition end-time
// senpai
address public oracleCon;
address public winner;
// League of Entropy
uint public roundNumber;
// Beacon details
uint public beacon;
// Notify world of new entry
event Entry(address signer, uint newTickets, string message);
event Deposit(address depositor, uint deposit);
event RequestBeacon();
event Winner(uint winningTicket, address winner, uint prize);
/**
* Hard-codes the relevant contracts and the competition's finish time (block).
* @param _deadline Random beacon is computed based on this block.
*/
constructor(address[] memory _relayers, address _relayHub, address _oracleCon, uint _deadline, uint _roundNumber) public {
// Register the any.sender relayers
for(uint i=0; i<_relayers.length; i++) {
relayers[_relayers[i]] = true;
}
relayHub = _relayHub; // Relay hub address
startBlock = block.number; // Used for the bump feature
deadline = _deadline; // Unix timestamp (to sync with League of Entropy)
oracleCon = _oracleCon; // Oracle contract
roundNumber = _roundNumber; // League of Entropy round number
}
/*
* Fetch the beacon and then compute the winner.
* Must be called within 256 blocks of deadline
* Just in case there is spam near end of competition,
* all expired entries will auto-call computeWinner().
*/
function computeWinner() public {
require(now > deadline, "We must wait until the competition deadline before computing the winner.");
require(winner == address(0), "Winner already set");
beacon = CommunityOracle(oracleCon).getBeacon();
require(beacon != 0, "Beacon is not ready");
uint winningTicket = beacon % entries.length;
winner = entries[winningTicket];
emit Winner(winningTicket, winner, address(this).balance);
}
/*
* @param _signer Ticket owner
* @param _tickets New tickets
*
* We append the owner's tickets to the global pool!
*/
function appendTickets(address _signer, uint _tickets) internal {
userTickets[_signer] = userTickets[_signer] + _tickets;
for(uint i=0; i<_tickets; i++) {
entries.push(_signer);
}
}
/**
* Mints new tickets for the user and posts a message to the board.
* @param _message Message to broadcast
*/
function submit(string memory _message) public
{
require(relayers[tx.origin], "All entries must be sent via any.sender");
require(msg.sender == relayHub, "All entries must be sent via the RelayHub");
require(deadline > now, "You have missed your chance to submit a ticket!");
address ticketOwner = _msgSender();
uint tickets = getNoTickets();
appendTickets(ticketOwner, tickets);
// Post message
emit Entry(ticketOwner, tickets, _message);
}
/**
* Ticket issuance is based on the progress of lottery.
* - Favours early in the game
* - Periodic bumps of tickets
*
* ~240 blocks an hour
* ~5760 blocks a day
*/
function getNoTickets() internal view returns (uint) {
// We offer high ticket issueance during the first day
if(5760 > block.number - startBlock) {
return 3;
}
// Four hour period of bumps
if(block.number % 5760 < 960) {
return 2;
}
// Four hour period of bumps
if(block.number % 5760 > 1920 && block.number % 5760 < 2880) {
return 2;
}
// Period bumps
return 1;
}
// Total tickets minted
function totalTickets() public view returns(uint) {
return entries.length;
}
/**
* Winner authorises withdrawal of prize
*/
function sendPrize() public payable {
require(true, "Winner must be set");
payable(winner).transfer(address(this).balance);
msg.sender.transfer(address(this).balance); } //injected WASTEFUL CONTRACT
// Deposit function
receive() external payable {
emit Deposit(msg.sender, msg.value);
}
} | We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20 bytes. This can always be done due to the 32-byte prefix. The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the easiest/most-efficient way to perform this operation. These fields are not accessible from assembly solhint-disable-next-line no-inline-assembly Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. | function _getRelayedCallSender() private pure returns (address payable result) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
| 12,896,155 |
./partial_match/1/0xd81b3000D6Cad7af85E9939AfAb1243B56618EA9/sources/VFIN.sol | Token Issuance / Perform the issuance of tokens. operator Address which triggered the issuance. to Token recipient. value Number of tokens issued. data Information attached to the issuance, and intended for the recipient (to)./ | function _issue(address operator, address to, uint256 value, bytes memory data)
internal
isNotMigratedToken
{
_totalSupply = _totalSupply + value;
_balances[to] = _balances[to] + value;
emit Issued(operator, to, value, data);
}
| 4,032,146 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.6;
// interfaces
import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
import {IERC725X} from "@erc725/smart-contracts/contracts/interfaces/IERC725X.sol";
import {ILSP6KeyManager} from "./ILSP6KeyManager.sol";
// modules
import {OwnableUnset} from "@erc725/smart-contracts/contracts/custom/OwnableUnset.sol";
import {IClaimOwnership} from "../Custom/IClaimOwnership.sol";
import {ERC725Y} from "@erc725/smart-contracts/contracts/ERC725Y.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
// libraries
import {BytesLib} from "solidity-bytes-utils/contracts/BytesLib.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ErrorHandlerLib} from "@erc725/smart-contracts/contracts/utils/ErrorHandlerLib.sol";
import {ERC165Checker} from "../Custom/ERC165Checker.sol";
import {LSP2Utils} from "../LSP2ERC725YJSONSchema/LSP2Utils.sol";
import {LSP6Utils} from "./LSP6Utils.sol";
// errors
import "./LSP6Errors.sol";
// constants
// prettier-ignore
import {
OPERATION_CALL,
OPERATION_CREATE,
OPERATION_CREATE2,
OPERATION_STATICCALL,
OPERATION_DELEGATECALL
} from "@erc725/smart-contracts/contracts/constants.sol";
import {_INTERFACEID_ERC1271, _ERC1271_MAGICVALUE, _ERC1271_FAILVALUE} from "../LSP0ERC725Account/LSP0Constants.sol";
import "./LSP6Constants.sol";
/**
* @title Core implementation of a contract acting as a controller of an ERC725 Account, using permissions stored in the ERC725Y storage
* @author Fabian Vogelsteller <frozeman>, Jean Cavallera (CJ42), Yamen Merhi (YamenMerhi)
* @dev all the permissions can be set on the ERC725 Account using `setData(...)` with the keys constants below
*/
abstract contract LSP6KeyManagerCore is ERC165, ILSP6KeyManager {
using LSP2Utils for *;
using LSP6Utils for *;
using Address for address;
using ECDSA for bytes32;
using ERC165Checker for address;
address public override target;
mapping(address => mapping(uint256 => uint256)) internal _nonceStore;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == _INTERFACEID_LSP6 ||
interfaceId == _INTERFACEID_ERC1271 ||
super.supportsInterface(interfaceId);
}
/**
* @inheritdoc ILSP6KeyManager
*/
function getNonce(address _from, uint256 _channel) public view override returns (uint256) {
uint128 nonceId = uint128(_nonceStore[_from][_channel]);
return (uint256(_channel) << 128) | nonceId;
}
/**
* @inheritdoc IERC1271
*/
function isValidSignature(bytes32 _hash, bytes memory _signature)
public
view
override
returns (bytes4 magicValue)
{
address recoveredAddress = _hash.recover(_signature);
return (
ERC725Y(target).getPermissionsFor(recoveredAddress).hasPermission(_PERMISSION_SIGN)
? _ERC1271_MAGICVALUE
: _ERC1271_FAILVALUE
);
}
/**
* @inheritdoc ILSP6KeyManager
*/
function execute(bytes calldata _calldata) external payable override returns (bytes memory) {
_verifyPermissions(msg.sender, _calldata);
// solhint-disable avoid-low-level-calls
(bool success, bytes memory result) = target.call{value: msg.value, gas: gasleft()}(
_calldata
);
if (!success) {
ErrorHandlerLib.revertWithParsedError(result);
}
emit Executed(msg.value, bytes4(_calldata));
return result.length != 0 ? abi.decode(result, (bytes)) : result;
}
/**
* @inheritdoc ILSP6KeyManager
*/
function executeRelayCall(
bytes memory _signature,
uint256 _nonce,
bytes calldata _calldata
) external payable override returns (bytes memory) {
bytes memory blob = abi.encodePacked(
block.chainid,
address(this), // needs to be signed for this keyManager
_nonce,
_calldata
);
address signer = keccak256(blob).toEthSignedMessageHash().recover(_signature);
require(_isValidNonce(signer, _nonce), "executeRelayCall: Invalid nonce");
// increase nonce after successful verification
_nonceStore[signer][_nonce >> 128]++;
_verifyPermissions(signer, _calldata);
// solhint-disable avoid-low-level-calls
(bool success, bytes memory result) = target.call{value: msg.value, gas: gasleft()}(
_calldata
);
if (!success) {
ErrorHandlerLib.revertWithParsedError(result);
}
emit Executed(msg.value, bytes4(_calldata));
return result.length != 0 ? abi.decode(result, (bytes)) : result;
}
/**
* @notice verify the nonce `_idx` for `_from` (obtained via `getNonce(...)`)
* @dev "idx" is a 256bits (unsigned) integer, where:
* - the 128 leftmost bits = channelId
* and - the 128 rightmost bits = nonce within the channel
* @param _from caller address
* @param _idx (channel id + nonce within the channel)
*/
function _isValidNonce(address _from, uint256 _idx) internal view returns (bool) {
// idx % (1 << 128) = nonce
// (idx >> 128) = channel
// equivalent to: return (nonce == _nonceStore[_from][channel]
return (_idx % (1 << 128)) == (_nonceStore[_from][_idx >> 128]);
}
/**
* @dev verify the permissions of the _from address that want to interact with the `target`
* @param _from the address making the request
* @param _calldata the payload that will be run on `target`
*/
function _verifyPermissions(address _from, bytes calldata _calldata) internal view {
bytes4 erc725Function = bytes4(_calldata[:4]);
// get the permissions of the caller
bytes32 permissions = ERC725Y(target).getPermissionsFor(_from);
if (permissions == bytes32(0)) revert NoPermissionsSet(_from);
// prettier-ignore
if (erc725Function == setDataSingleSelector) {
(bytes32 inputKey, bytes memory inputValue) = abi.decode(_calldata[4:], (bytes32, bytes));
if (
// CHECK for permission keys
bytes6(inputKey) == _LSP6KEY_ADDRESSPERMISSIONS_PREFIX ||
bytes16(inputKey) == _LSP6KEY_ADDRESSPERMISSIONS_ARRAY_PREFIX
) {
_verifyCanSetPermissions(inputKey, inputValue, _from, permissions);
} else {
bytes32[] memory inputKeys = new bytes32[](1);
inputKeys[0] = inputKey;
_verifyCanSetData(_from, permissions, inputKeys);
}
} else if (erc725Function == setDataMultipleSelector) {
(bytes32[] memory inputKeys, bytes[] memory inputValues) = abi.decode(_calldata[4:], (bytes32[], bytes[]));
bool isSettingERC725YKeys = false;
// loop through each ERC725Y data keys
for (uint256 ii = 0; ii < inputKeys.length; ii++) {
bytes32 key = inputKeys[ii];
bytes memory value = inputValues[ii];
if (
// CHECK for permission keys
bytes6(key) == _LSP6KEY_ADDRESSPERMISSIONS_PREFIX ||
bytes16(key) == _LSP6KEY_ADDRESSPERMISSIONS_ARRAY_PREFIX
) {
_verifyCanSetPermissions(key, value, _from, permissions);
// "nullify" permission keys
// to not check them against allowed ERC725Y keys
inputKeys[ii] = bytes32(0);
} else {
// if the key is any other bytes32 key
isSettingERC725YKeys = true;
}
}
if (isSettingERC725YKeys) {
_verifyCanSetData(_from, permissions, inputKeys);
}
} else if (erc725Function == IERC725X.execute.selector) {
_verifyCanExecute(_from, permissions, _calldata);
} else if (
erc725Function == OwnableUnset.transferOwnership.selector ||
erc725Function == IClaimOwnership.claimOwnership.selector
) {
_requirePermissions(_from, permissions, _PERMISSION_CHANGEOWNER);
} else {
revert("_verifyPermissions: invalid ERC725 selector");
}
}
/**
* @dev verify if `_from` has the required permissions to set some keys
* on the linked ERC725Account
* @param _from the address who want to set the keys
* @param _permissions the permissions
* @param _inputKeys the data keys being set
* containing a list of keys-value pairs
*/
function _verifyCanSetData(
address _from,
bytes32 _permissions,
bytes32[] memory _inputKeys
) internal view {
// Skip if caller has SUPER permissions
if (_permissions.hasPermission(_PERMISSION_SUPER_SETDATA)) return;
_requirePermissions(_from, _permissions, _PERMISSION_SETDATA);
_verifyAllowedERC725YKeys(_from, _inputKeys);
}
function _verifyCanSetPermissions(
bytes32 _key,
bytes memory _value,
address _from,
bytes32 _permissions
) internal view {
// prettier-ignore
if (bytes12(_key) == _LSP6KEY_ADDRESSPERMISSIONS_PERMISSIONS_PREFIX) {
// key = AddressPermissions:Permissions:<address>
_verifyCanSetBytes32Permissions(_key, _from, _permissions);
} else if (_key == _LSP6KEY_ADDRESSPERMISSIONS_ARRAY) {
// key = AddressPermissions[]
_verifyCanSetPermissionsArray(_key, _value, _from, _permissions);
} else if (bytes16(_key) == _LSP6KEY_ADDRESSPERMISSIONS_ARRAY_PREFIX) {
// key = AddressPermissions[index]
_requirePermissions(_from, _permissions, _PERMISSION_CHANGEPERMISSIONS);
} else if (bytes12(_key) == _LSP6KEY_ADDRESSPERMISSIONS_ALLOWEDADDRESSES_PREFIX) {
// AddressPermissions:AllowedAddresses:<address>
require(
LSP2Utils.isEncodedArrayOfAddresses(_value),
"LSP6KeyManager: invalid ABI encoded array of addresses"
);
bytes memory storedAllowedAddresses = ERC725Y(target).getData(_key);
if (storedAllowedAddresses.length == 0) {
_requirePermissions(_from, _permissions, _PERMISSION_ADDPERMISSIONS);
} else {
_requirePermissions(_from, _permissions, _PERMISSION_CHANGEPERMISSIONS);
}
} else if (
bytes12(_key) == _LSP6KEY_ADDRESSPERMISSIONS_ALLOWEDFUNCTIONS_PREFIX ||
bytes12(_key) == _LSP6KEY_ADDRESSPERMISSIONS_ALLOWEDSTANDARDS_PREFIX
) {
// AddressPermissions:AllowedFunctions:<address>
// AddressPermissions:AllowedStandards:<address>
require(
LSP2Utils.isBytes4EncodedArray(_value),
"LSP6KeyManager: invalid ABI encoded array of bytes4"
);
bytes memory storedAllowedBytes4 = ERC725Y(target).getData(_key);
if (storedAllowedBytes4.length == 0) {
_requirePermissions(_from, _permissions, _PERMISSION_ADDPERMISSIONS);
} else {
_requirePermissions(_from, _permissions, _PERMISSION_CHANGEPERMISSIONS);
}
} else if (bytes12(_key) == _LSP6KEY_ADDRESSPERMISSIONS_ALLOWEDERC725YKEYS_PREFIX) {
// AddressPermissions:AllowedERC725YKeys:<address>
require(
LSP2Utils.isEncodedArray(_value),
"LSP6KeyManager: invalid ABI encoded array of bytes32"
);
bytes memory storedAllowedERC725YKeys = ERC725Y(target).getData(_key);
if (storedAllowedERC725YKeys.length == 0) {
_requirePermissions(_from, _permissions, _PERMISSION_ADDPERMISSIONS);
} else {
_requirePermissions(_from, _permissions, _PERMISSION_CHANGEPERMISSIONS);
}
}
}
function _verifyCanSetBytes32Permissions(
bytes32 _key,
address _from,
bytes32 _callerPermissions
) internal view {
if (bytes32(ERC725Y(target).getData(_key)) == bytes32(0)) {
// if there is nothing stored under this data key,
// we are trying to ADD permissions for a NEW address
_requirePermissions(_from, _callerPermissions, _PERMISSION_ADDPERMISSIONS);
} else {
// if there are already some permissions stored under this data key,
// we are trying to CHANGE the permissions of an address
// (that has already some EXISTING permissions set)
_requirePermissions(_from, _callerPermissions, _PERMISSION_CHANGEPERMISSIONS);
}
}
function _verifyCanSetPermissionsArray(
bytes32 _key,
bytes memory _value,
address _from,
bytes32 _permissions
) internal view {
uint256 arrayLength = uint256(bytes32(ERC725Y(target).getData(_key)));
uint256 newLength = uint256(bytes32(_value));
if (newLength > arrayLength) {
_requirePermissions(_from, _permissions, _PERMISSION_ADDPERMISSIONS);
} else {
_requirePermissions(_from, _permissions, _PERMISSION_CHANGEPERMISSIONS);
}
}
function _verifyAllowedERC725YKeys(address _from, bytes32[] memory _inputKeys) internal view {
bytes memory allowedERC725YKeysEncoded = ERC725Y(target).getAllowedERC725YKeysFor(_from);
// whitelist any ERC725Y key
if (
// if nothing in the list
allowedERC725YKeysEncoded.length == 0 ||
// if not correctly abi-encoded array
!LSP2Utils.isEncodedArray(allowedERC725YKeysEncoded)
) return;
bytes32[] memory allowedERC725YKeys = abi.decode(allowedERC725YKeysEncoded, (bytes32[]));
uint256 zeroBytesCount;
bytes32 mask;
// loop through each allowed ERC725Y key retrieved from storage
for (uint256 ii = 0; ii < allowedERC725YKeys.length; ii++) {
// required to know which part of the input key to compare against the allowed key
zeroBytesCount = _countZeroBytes(allowedERC725YKeys[ii]);
// loop through each keys given as input
for (uint256 jj = 0; jj < _inputKeys.length; jj++) {
// skip permissions keys that have been previously "nulled"
if (_inputKeys[jj] == bytes32(0)) continue;
// solhint-disable no-inline-assembly
assembly {
// use a bitmask to discard the last `n` bytes of the input key
// so to compare only the relevant parts of each ERC725Y keys
//
// `n = zeroBytesCount`
//
// eg:
//
// allowed key = 0xcafecafecafecafecafecafecafecafe00000000000000000000000000000000
//
// compare this part
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// input key = 0xcafecafecafecafecafecafecafecafe00000000000000000000000011223344
//
// & discard this part
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// mask = 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000
//
// prettier-ignore
mask := shl(mul(8, zeroBytesCount), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
}
if (allowedERC725YKeys[ii] == (_inputKeys[jj] & mask)) {
// if the input key matches the allowed key
// make it null to mark it as allowed
_inputKeys[jj] = bytes32(0);
}
}
}
for (uint256 ii = 0; ii < _inputKeys.length; ii++) {
if (_inputKeys[ii] != bytes32(0)) revert NotAllowedERC725YKey(_from, _inputKeys[ii]);
}
}
/**
* @dev verify if `_from` has the required permissions to make an external call
* via the linked ERC725Account
* @param _from the address who want to run the execute function on the ERC725Account
* @param _permissions the permissions of the caller
* @param _calldata the ABI encoded payload `target.execute(...)`
*/
function _verifyCanExecute(
address _from,
bytes32 _permissions,
bytes calldata _calldata
) internal view {
uint256 operationType = uint256(bytes32(_calldata[4:36]));
require(operationType < 5, "LSP6KeyManager: invalid operation type");
// TODO: if re-enable delegatecall, add check to ensure owner() + initialized() are not overriden after delegatecall
require(
operationType != OPERATION_DELEGATECALL,
"LSP6KeyManager: operation DELEGATECALL is currently disallowed"
);
uint256 value = uint256(bytes32(_calldata[68:100]));
// prettier-ignore
bool isContractCreation = operationType == OPERATION_CREATE || operationType == OPERATION_CREATE2;
bool isCallDataPresent = _calldata.length > 164;
// SUPER operation only applies to contract call, not contract creation
bool hasSuperOperation = isContractCreation
? false
: _permissions.hasPermission(_extractSuperPermissionFromOperation(operationType));
if (isCallDataPresent) {
// prettier-ignore
hasSuperOperation || _requirePermissions(_from, _permissions, _extractPermissionFromOperation(operationType));
}
bool hasSuperTransferValue = _permissions.hasPermission(_PERMISSION_SUPER_TRANSFERVALUE);
if (value > 0) {
// prettier-ignore
hasSuperTransferValue || _requirePermissions(_from, _permissions, _PERMISSION_TRANSFERVALUE);
}
// Skip on contract creation (CREATE or CREATE2)
if (isContractCreation) return;
// Skip if caller has SUPER permissions for operations
if (hasSuperOperation && isCallDataPresent && value == 0) return;
// Skip if caller has SUPER permission for value transfers
if (hasSuperTransferValue && !isCallDataPresent && value > 0) return;
// Skip if both SUPER permissions are present
if (hasSuperOperation && hasSuperTransferValue) return;
// CHECK for ALLOWED ADDRESSES
address to = address(bytes20(_calldata[48:68]));
_verifyAllowedAddress(_from, to);
if (to.code.length > 0) {
// CHECK for ALLOWED STANDARDS
_verifyAllowedStandard(_from, to);
// CHECK for ALLOWED FUNCTIONS
// extract bytes4 function selector from payload passed to ERC725X.execute(...)
if (_calldata.length >= 168) _verifyAllowedFunction(_from, bytes4(_calldata[164:168]));
}
}
/**
* @dev extract the required permission + a descriptive string, based on the `_operationType`
* being run via ERC725Account.execute(...)
* @param _operationType 0 = CALL, 1 = CREATE, 2 = CREATE2, etc... See ERC725X docs for more infos.
* @return permissionsRequired_ (bytes32) the permission associated with the `_operationType`
*/
function _extractPermissionFromOperation(uint256 _operationType)
internal
pure
returns (bytes32 permissionsRequired_)
{
if (_operationType == OPERATION_CALL) return _PERMISSION_CALL;
else if (_operationType == OPERATION_CREATE) return _PERMISSION_DEPLOY;
else if (_operationType == OPERATION_CREATE2) return _PERMISSION_DEPLOY;
else if (_operationType == OPERATION_STATICCALL) return _PERMISSION_STATICCALL;
else if (_operationType == OPERATION_DELEGATECALL) return _PERMISSION_DELEGATECALL;
}
function _extractSuperPermissionFromOperation(uint256 _operationType)
internal
pure
returns (bytes32 superPermission_)
{
if (_operationType == OPERATION_CALL) return _PERMISSION_SUPER_CALL;
else if (_operationType == OPERATION_STATICCALL) return _PERMISSION_SUPER_STATICCALL;
else if (_operationType == OPERATION_DELEGATECALL) return _PERMISSION_SUPER_DELEGATECALL;
}
/**
* @dev verify if `_from` is authorised to interact with address `_to` via the linked ERC725Account
* @param _from the caller address
* @param _to the address to interact with
*/
function _verifyAllowedAddress(address _from, address _to) internal view {
bytes memory allowedAddresses = ERC725Y(target).getAllowedAddressesFor(_from);
// whitelist any address
if (
// if nothing in the list
allowedAddresses.length == 0 ||
// if not correctly abi-encoded array of address[]
!LSP2Utils.isEncodedArrayOfAddresses(allowedAddresses)
) return;
address[] memory allowedAddressesList = abi.decode(allowedAddresses, (address[]));
for (uint256 ii = 0; ii < allowedAddressesList.length; ii++) {
if (_to == allowedAddressesList[ii]) return;
}
revert NotAllowedAddress(_from, _to);
}
/**
* @dev if `_from` is restricted to interact with contracts that implement a specific interface,
* verify that `_to` implements one of these interface.
* @param _from the caller address
* @param _to the address of the contract to interact with
*/
function _verifyAllowedStandard(address _from, address _to) internal view {
bytes memory allowedStandards = ERC725Y(target).getAllowedStandardsFor(_from);
// whitelist any standard interface (ERC165)
if (
// if nothing in the list
allowedStandards.length == 0 ||
// if not correctly abi-encoded array of bytes4[]
!LSP2Utils.isBytes4EncodedArray(allowedStandards)
) return;
bytes4[] memory allowedStandardsList = abi.decode(allowedStandards, (bytes4[]));
for (uint256 ii = 0; ii < allowedStandardsList.length; ii++) {
if (_to.supportsERC165Interface(allowedStandardsList[ii])) return;
}
revert("Not Allowed Standards");
}
/**
* @dev verify if `_from` is authorised to use the linked ERC725Account
* to run a specific function `_functionSelector` at a target contract
* @param _from the caller address
* @param _functionSelector the bytes4 function selector of the function to run
* at the target contract
*/
function _verifyAllowedFunction(address _from, bytes4 _functionSelector) internal view {
bytes memory allowedFunctions = ERC725Y(target).getAllowedFunctionsFor(_from);
// whitelist any function
if (
// if nothing in the list
allowedFunctions.length == 0 ||
// if not correctly abi-encoded array of bytes4[]
!LSP2Utils.isBytes4EncodedArray(allowedFunctions)
) return;
bytes4[] memory allowedFunctionsList = abi.decode(allowedFunctions, (bytes4[]));
for (uint256 ii = 0; ii < allowedFunctionsList.length; ii++) {
if (_functionSelector == allowedFunctionsList[ii]) return;
}
revert NotAllowedFunction(_from, _functionSelector);
}
function _countZeroBytes(bytes32 _key) internal pure returns (uint256) {
uint256 index = 31;
// CHECK each bytes of the key, starting from the end (right to left)
// skip the empty bytes `0x00` to find the first non-empty bytes
while (_key[index] == 0x00) index--;
return 32 - (index + 1);
}
function _requirePermissions(
address _from,
bytes32 _addressPermissions,
bytes32 _permissionRequired
) internal pure returns (bool) {
if (!_addressPermissions.hasPermission(_permissionRequired)) {
string memory permissionErrorString = _getPermissionErrorString(_permissionRequired);
revert NotAuthorised(_from, permissionErrorString);
}
}
function _getPermissionErrorString(bytes32 _permission)
internal
pure
returns (string memory errorMessage)
{
if (_permission == _PERMISSION_CHANGEOWNER) return "TRANSFEROWNERSHIP";
if (_permission == _PERMISSION_CHANGEPERMISSIONS) return "CHANGEPERMISSIONS";
if (_permission == _PERMISSION_ADDPERMISSIONS) return "ADDPERMISSIONS";
if (_permission == _PERMISSION_SETDATA) return "SETDATA";
if (_permission == _PERMISSION_CALL) return "CALL";
if (_permission == _PERMISSION_STATICCALL) return "STATICCALL";
if (_permission == _PERMISSION_DELEGATECALL) return "DELEGATECALL";
// TODO: add support to display CREATE or CREATE2 in the revert error
if (_permission == _PERMISSION_DEPLOY) return "DEPLOY";
if (_permission == _PERMISSION_TRANSFERVALUE) return "TRANSFERVALUE";
if (_permission == _PERMISSION_SIGN) return "SIGN";
}
}
| verify if `_from` has the required permissions to set some keys on the linked ERC725Account _from the address who want to set the keys _permissions the permissions _inputKeys the data keys being set containing a list of keys-value pairs/ Skip if caller has SUPER permissions | function _verifyCanSetData(
address _from,
bytes32 _permissions,
bytes32[] memory _inputKeys
) internal view {
if (_permissions.hasPermission(_PERMISSION_SUPER_SETDATA)) return;
_requirePermissions(_from, _permissions, _PERMISSION_SETDATA);
_verifyAllowedERC725YKeys(_from, _inputKeys);
}
| 5,534,860 |
//Address: 0x43F27B4f518555Ff5612Ae248b51C1EdF76884f2
//Contract name: EKK
//Balance: 0 Ether
//Verification Date: 6/25/2018
//Transacion Count: 3
// CODE STARTS HERE
pragma solidity ^0.4.20;
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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
/**
* Token contract interface for external use
*/
contract ERC20TokenInterface {
function balanceOf(address _owner) public constant returns (uint256 value);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
}
/**
* @title Admin parameters
* @dev Define administration parameters for this contract
*/
contract admined { //This token contract is administered
address public admin; //Admin address is public
address public allowedAddress; //an address that can override lock condition
/**
* @dev Contract constructor
* define initial administrator
*/
function admined() internal {
admin = msg.sender; //Set initial admin to contract creator
Admined(admin);
}
/**
* @dev Function to set an allowed address
* @param _to The address to give privileges.
*/
function setAllowedAddress(address _to) onlyAdmin public {
allowedAddress = _to;
AllowedSet(_to);
}
modifier onlyAdmin() { //A modifier to define admin-only functions
require(msg.sender == admin);
_;
}
modifier crowdsaleonly() { //A modifier to lock transactions
require(allowedAddress == msg.sender);
_;
}
/**
* @dev Function to set new admin address
* @param _newAdmin The address to transfer administration to
*/
function transferAdminship(address _newAdmin) onlyAdmin public { //Admin can be transfered
require(_newAdmin != 0);
admin = _newAdmin;
TransferAdminship(admin);
}
//All admin actions have a log for public review
event AllowedSet(address _to);
event TransferAdminship(address newAdminister);
event Admined(address administer);
}
/**
* @title Token definition
* @dev Define token paramters including ERC20 ones
*/
contract ERC20Token is ERC20TokenInterface, admined { //Standard definition of a ERC20Token
using SafeMath for uint256;
uint256 public totalSupply;
mapping (address => uint256) balances; //A mapping of all balances per address
mapping (address => mapping (address => uint256)) allowed; //A mapping of all allowances
mapping (address => bool) frozen; //A mapping of frozen accounts
/**
* @dev Get the balance of an specified address.
* @param _owner The address to be query.
*/
function balanceOf(address _owner) public constant returns (uint256 value) {
return balances[_owner];
}
/**
* @dev transfer token to a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0)); //If you dont want that people destroy token
require(frozen[msg.sender]==false);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev transfer token from an address to another specified address using allowance
* @param _from The address where token comes.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != address(0)); //If you dont want that people destroy token
require(frozen[_from]==false);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Assign allowance to an specified address to use the owner balance
* @param _spender The address to be allowed to spend.
* @param _value The amount to be allowed.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0)); //exploit mitigation
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Get the allowance of an specified address to use another address balance.
* @param _owner The address of the owner of the tokens.
* @param _spender The address of the allowed spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* @dev Log Events
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* @title Asset
* @dev Initial supply creation
*/
contract EKK is ERC20Token {
string public name = 'EKK Token';
uint8 public decimals = 18;
string public symbol = 'EKK';
string public version = '1';
uint256 public totalSupply = 2000000000 * 10**uint256(decimals); //initial token creation
uint256 public publicAllocation = 1000000000 * 10 ** uint(decimals); // 50% Token sales & Distribution
uint256 public growthReserve = 700000000 * 10 ** uint(decimals); // 35% Platform Growth Reserve
uint256 public marketingAllocation= 100000000 * 10 ** uint(decimals); // 5% Markting/Promotion
uint256 public teamAllocation = 160000000 *10 ** uint(decimals); // 8% Team
uint256 public advisorsAllocation = 40000000 * 10 ** uint(decimals); // 2% Advisors
//address public owner;
function EKK() public {
balances[this] = totalSupply;
Transfer(0, this, totalSupply);
Transfer(this, msg.sender, balances[msg.sender]);
}
/**
*@dev Function to handle callback calls
*/
function() public {
revert();
}
/**
* @dev Get publicAllocation
*/
function getPublicAllocation() public view returns (uint256 value) {
return publicAllocation;
}
/**
* @dev setOwner for EKKcrowdsale contract only
*/
// function setOwner(address _owner) onlyAdmin public {
// owner = _owner;
// }
/**
* transfer, only can be called by crowdsale contract
*/
function transferFromPublicAllocation(address _to, uint256 _value) crowdsaleonly public returns (bool success) {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balances[this] >= _value && publicAllocation >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Save this for an assertion in the future
uint previousBalances = balances[this].add(balances[_to]);
// Subtract from the sender
balances[this] = balances[this].sub(_value);
publicAllocation = publicAllocation.sub(_value);
// Add the same to the recipient
balances[_to] = balances[_to].add(_value);
Transfer(this, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[this] + balances[_to] == previousBalances);
return true;
}
function growthReserveTokenSend(address to, uint256 _value) onlyAdmin public {
uint256 value = _value * 10 ** uint(decimals);
require(to != 0x0 && growthReserve >= value);
balances[this] = balances[this].sub(value);
balances[to] = balances[to].add(value);
growthReserve = growthReserve.sub(value);
Transfer(this, to, value);
}
function marketingAllocationTokenSend(address to, uint256 _value) onlyAdmin public {
uint256 value = _value * 10 ** uint(decimals);
require(to != 0x0 && marketingAllocation >= value);
balances[this] = balances[this].sub(value);
balances[to] = balances[to].add(value);
marketingAllocation = marketingAllocation.sub(value);
Transfer(this, to, value);
}
function teamAllocationTokenSend(address to, uint256 _value) onlyAdmin public {
uint256 value = _value * 10 ** uint(decimals);
require(to != 0x0 && teamAllocation >= value);
balances[this] = balances[this].sub(value);
balances[to] = balances[to].add(value);
teamAllocation = teamAllocation.sub(value);
Transfer(this, to, value);
}
function advisorsAllocationTokenSend(address to, uint256 _value) onlyAdmin public {
uint256 value = _value * 10 ** uint(decimals);
require(to != 0x0 && advisorsAllocation >= value);
balances[this] = balances[this].sub(value);
balances[to] = balances[to].add(value);
advisorsAllocation = advisorsAllocation.sub(value);
Transfer(this, to, value);
}
// unsold tokens back to Platform Growth Reserve
function transferToGrowthReserve() crowdsaleonly public {
growthReserve = growthReserve.add(publicAllocation);
publicAllocation = 0;
}
//refund tokens after crowdsale
function refundTokens(address _sender) crowdsaleonly public {
growthReserve = growthReserve.add(balances[_sender]);
//balances[_sender] = 0;
}
}
| transfer token to a specified address _to The address to transfer to. _value The amount to be transferred./ | function transfer(address _to, uint256 _value) public returns (bool success) {
require(frozen[msg.sender]==false);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| 5,535,801 |
./full_match/4/0x9D8166409294a72495aAC157D457051E8Ca7C3aB/sources/LotteryBNB.sol | Xem số dư của smart contract | function getBalance() public view returns (uint256) {
return address(this).balance;
}
| 690,781 |
// File: contracts/lib/math/SafeMath.sol
pragma solidity 0.5.12;
/**
* @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;
}
}
// File: contracts/lib/ownership/Ownable.sol
pragma solidity 0.5.12;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address public owner;
address public pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/lib/utils/ReentrancyGuard.sol
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 aplied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: contracts/Utils.sol
pragma solidity 0.5.12;
interface ERC20 {
function balanceOf(address account) external view returns (uint256);
}
interface MarketDapp {
// Returns the address to approve tokens for
function tokenReceiver(address[] calldata assetIds, uint256[] calldata dataValues, address[] calldata addresses) external view returns(address);
function trade(address[] calldata assetIds, uint256[] calldata dataValues, address[] calldata addresses, address payable recipient) external payable;
}
/// @title Util functions for the BrokerV2 contract for Switcheo Exchange
/// @author Switcheo Network
/// @notice Functions were moved from the BrokerV2 contract into this contract
/// so that the BrokerV2 contract would not exceed the maximum contract size of
/// 24 KB.
library Utils {
using SafeMath for uint256;
// The constants for EIP-712 are precompiled to reduce contract size,
// the original values are left here for reference and verification.
//
// bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract,",
// "bytes32 salt",
// ")"
// ));
// bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472;
//
// bytes32 public constant CONTRACT_NAME = keccak256("Switcheo Exchange");
// bytes32 public constant CONTRACT_VERSION = keccak256("2");
// uint256 public constant CHAIN_ID = 1;
// address public constant VERIFYING_CONTRACT = 0x7ee7Ca6E75dE79e618e88bDf80d0B1DB136b22D0;
// bytes32 public constant SALT = keccak256("switcheo-eth-salt");
// bytes32 public constant DOMAIN_SEPARATOR = keccak256(abi.encode(
// EIP712_DOMAIN_TYPEHASH,
// CONTRACT_NAME,
// CONTRACT_VERSION,
// CHAIN_ID,
// VERIFYING_CONTRACT,
// SALT
// ));
bytes32 public constant DOMAIN_SEPARATOR = 0x256c0713d13c6a01bd319a2f7edabde771b6c167d37c01778290d60b362ccc7d;
// bytes32 public constant OFFER_TYPEHASH = keccak256(abi.encodePacked(
// "Offer(",
// "address maker,",
// "address offerAssetId,",
// "uint256 offerAmount,",
// "address wantAssetId,",
// "uint256 wantAmount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant OFFER_TYPEHASH = 0xf845c83a8f7964bc8dd1a092d28b83573b35be97630a5b8a3b8ae2ae79cd9260;
// bytes32 public constant CANCEL_TYPEHASH = keccak256(abi.encodePacked(
// "Cancel(",
// "bytes32 offerHash,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// ")"
// ));
bytes32 public constant CANCEL_TYPEHASH = 0x46f6d088b1f0ff5a05c3f232c4567f2df96958e05457e6c0e1221dcee7d69c18;
// bytes32 public constant FILL_TYPEHASH = keccak256(abi.encodePacked(
// "Fill(",
// "address filler,",
// "address offerAssetId,",
// "uint256 offerAmount,",
// "address wantAssetId,",
// "uint256 wantAmount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant FILL_TYPEHASH = 0x5f59dbc3412a4575afed909d028055a91a4250ce92235f6790c155a4b2669e99;
// The Ether token address is set as the constant 0x00 for backwards
// compatibility
address private constant ETHER_ADDR = address(0);
uint256 private constant mask8 = ~(~uint256(0) << 8);
uint256 private constant mask16 = ~(~uint256(0) << 16);
uint256 private constant mask24 = ~(~uint256(0) << 24);
uint256 private constant mask32 = ~(~uint256(0) << 32);
uint256 private constant mask40 = ~(~uint256(0) << 40);
uint256 private constant mask48 = ~(~uint256(0) << 48);
uint256 private constant mask56 = ~(~uint256(0) << 56);
uint256 private constant mask120 = ~(~uint256(0) << 120);
uint256 private constant mask128 = ~(~uint256(0) << 128);
uint256 private constant mask136 = ~(~uint256(0) << 136);
uint256 private constant mask144 = ~(~uint256(0) << 144);
event Trade(
address maker,
address taker,
address makerGiveAsset,
uint256 makerGiveAmount,
address fillerGiveAsset,
uint256 fillerGiveAmount
);
/// @dev Calculates the balance increments for a set of trades
/// @param _values The _values param from the trade method
/// @param _incrementsLength Should match the value of _addresses.length / 2
/// from the trade method
/// @return An array of increments
function calculateTradeIncrements(
uint256[] memory _values,
uint256 _incrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory increments = new uint256[](_incrementsLength);
_creditFillBalances(increments, _values);
_creditMakerBalances(increments, _values);
_creditMakerFeeBalances(increments, _values);
return increments;
}
/// @dev Calculates the balance decrements for a set of trades
/// @param _values The _values param from the trade method
/// @param _decrementsLength Should match the value of _addresses.length / 2
/// from the trade method
/// @return An array of decrements
function calculateTradeDecrements(
uint256[] memory _values,
uint256 _decrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory decrements = new uint256[](_decrementsLength);
_deductFillBalances(decrements, _values);
_deductMakerBalances(decrements, _values);
return decrements;
}
/// @dev Calculates the balance increments for a set of network trades
/// @param _values The _values param from the networkTrade method
/// @param _incrementsLength Should match the value of _addresses.length / 2
/// from the networkTrade method
/// @return An array of increments
function calculateNetworkTradeIncrements(
uint256[] memory _values,
uint256 _incrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory increments = new uint256[](_incrementsLength);
_creditMakerBalances(increments, _values);
_creditMakerFeeBalances(increments, _values);
return increments;
}
/// @dev Calculates the balance decrements for a set of network trades
/// @param _values The _values param from the trade method
/// @param _decrementsLength Should match the value of _addresses.length / 2
/// from the networkTrade method
/// @return An array of decrements
function calculateNetworkTradeDecrements(
uint256[] memory _values,
uint256 _decrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory decrements = new uint256[](_decrementsLength);
_deductMakerBalances(decrements, _values);
return decrements;
}
/// @dev Validates `BrokerV2.trade` parameters to ensure trade fairness,
/// see `BrokerV2.trade` for param details.
/// @param _values Values from `trade`
/// @param _hashes Hashes from `trade`
/// @param _addresses Addresses from `trade`
function validateTrades(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses,
address _operator
)
public
returns (bytes32[] memory)
{
_validateTradeInputLengths(_values, _hashes);
_validateUniqueOffers(_values);
_validateMatches(_values, _addresses);
_validateFillAmounts(_values);
_validateTradeData(_values, _addresses, _operator);
// validate signatures of all offers
_validateTradeSignatures(
_values,
_hashes,
_addresses,
OFFER_TYPEHASH,
0,
_values[0] & mask8 // numOffers
);
// validate signatures of all fills
_validateTradeSignatures(
_values,
_hashes,
_addresses,
FILL_TYPEHASH,
_values[0] & mask8, // numOffers
(_values[0] & mask8) + ((_values[0] & mask16) >> 8) // numOffers + numFills
);
_emitTradeEvents(_values, _addresses, new address[](0), false);
return _hashes;
}
/// @dev Validates `BrokerV2.networkTrade` parameters to ensure trade fairness,
/// see `BrokerV2.networkTrade` for param details.
/// @param _values Values from `networkTrade`
/// @param _hashes Hashes from `networkTrade`
/// @param _addresses Addresses from `networkTrade`
/// @param _operator Address of the `BrokerV2.operator`
function validateNetworkTrades(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses,
address _operator
)
public
pure
returns (bytes32[] memory)
{
_validateNetworkTradeInputLengths(_values, _hashes);
_validateUniqueOffers(_values);
_validateNetworkMatches(_values, _addresses, _operator);
_validateTradeData(_values, _addresses, _operator);
// validate signatures of all offers
_validateTradeSignatures(
_values,
_hashes,
_addresses,
OFFER_TYPEHASH,
0,
_values[0] & mask8 // numOffers
);
return _hashes;
}
/// @dev Executes trades against external markets,
/// see `BrokerV2.networkTrade` for param details.
/// @param _values Values from `networkTrade`
/// @param _addresses Addresses from `networkTrade`
/// @param _marketDapps See `BrokerV2.marketDapps`
function performNetworkTrades(
uint256[] memory _values,
address[] memory _addresses,
address[] memory _marketDapps
)
public
returns (uint256[] memory)
{
uint256[] memory increments = new uint256[](_addresses.length / 2);
// i = 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
uint256 end = _values.length;
// loop matches
for(i; i < end; i++) {
uint256[] memory data = new uint256[](9);
data[0] = _values[i]; // match data
data[1] = data[0] & mask8; // offerIndex
data[2] = (data[0] & mask24) >> 16; // operator.surplusAssetIndex
data[3] = _values[data[1] * 2 + 1]; // offer.dataA
data[4] = _values[data[1] * 2 + 2]; // offer.dataB
data[5] = ((data[3] & mask16) >> 8); // maker.offerAssetIndex
data[6] = ((data[3] & mask24) >> 16); // maker.wantAssetIndex
// amount of offerAssetId to take from the offer is equal to the match.takeAmount
data[7] = data[0] >> 128;
// expected amount to receive is: matchData.takeAmount * offer.wantAmount / offer.offerAmount
data[8] = data[7].mul(data[4] >> 128).div(data[4] & mask128);
address[] memory assetIds = new address[](3);
assetIds[0] = _addresses[data[5] * 2 + 1]; // offer.offerAssetId
assetIds[1] = _addresses[data[6] * 2 + 1]; // offer.wantAssetId
assetIds[2] = _addresses[data[2] * 2 + 1]; // surplusAssetId
uint256[] memory dataValues = new uint256[](3);
dataValues[0] = data[7]; // the proportion of offerAmount to offer
dataValues[1] = data[8]; // the proportion of wantAmount to receive for the offer
dataValues[2] = data[0]; // match data
increments[data[2]] = _performNetworkTrade(
assetIds,
dataValues,
_marketDapps,
_addresses
);
}
_emitTradeEvents(_values, _addresses, _marketDapps, true);
return increments;
}
/// @dev Validates the signature of a cancel invocation
/// @param _values The _values param from the cancel method
/// @param _hashes The _hashes param from the cancel method
/// @param _addresses The _addresses param from the cancel method
function validateCancel(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses
)
public
pure
{
bytes32 offerHash = hashOffer(_values, _addresses);
bytes32 cancelHash = keccak256(abi.encode(
CANCEL_TYPEHASH,
offerHash,
_addresses[4],
_values[1] >> 128
));
validateSignature(
cancelHash,
_addresses[0], // maker
uint8((_values[2] & mask144) >> 136), // v
_hashes[0], // r
_hashes[1], // s
((_values[2] & mask136) >> 128) != 0 // prefixedSignature
);
}
/// @dev Hashes an offer for the cancel method
/// @param _values The _values param from the cancel method
/// @param _addresses THe _addresses param from the cancel method
/// @return The hash of the offer
function hashOffer(
uint256[] memory _values,
address[] memory _addresses
)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(
OFFER_TYPEHASH,
_addresses[0], // maker
_addresses[1], // offerAssetId
_values[0] & mask128, // offerAmount
_addresses[2], // wantAssetId
_values[0] >> 128, // wantAmount
_addresses[3], // feeAssetId
_values[1] & mask128, // feeAmount
_values[2] >> 144 // offerNonce
));
}
/// @notice Approves a token transfer
/// @param _assetId The address of the token to approve
/// @param _spender The address of the spender to approve
/// @param _amount The number of tokens to approve
function approveTokenTransfer(
address _assetId,
address _spender,
uint256 _amount
)
public
{
_validateContractAddress(_assetId);
// Some tokens have an `approve` which returns a boolean and some do not.
// The ERC20 interface cannot be used here because it requires specifying
// an explicit return value, and an EVM exception would be raised when calling
// a token with the mismatched return value.
bytes memory payload = abi.encodeWithSignature(
"approve(address,uint256)",
_spender,
_amount
);
bytes memory returnData = _callContract(_assetId, payload);
// Ensure that the asset transfer succeeded
_validateContractCallResult(returnData);
}
/// @notice Transfers tokens into the contract
/// @param _user The address to transfer the tokens from
/// @param _assetId The address of the token to transfer
/// @param _amount The number of tokens to transfer
/// @param _expectedAmount The number of tokens expected to be received,
/// this may not match `_amount`, for example, tokens which have a
/// proportion burnt on transfer will have a different amount received.
function transferTokensIn(
address _user,
address _assetId,
uint256 _amount,
uint256 _expectedAmount
)
public
{
_validateContractAddress(_assetId);
uint256 initialBalance = tokenBalance(_assetId);
// Some tokens have a `transferFrom` which returns a boolean and some do not.
// The ERC20 interface cannot be used here because it requires specifying
// an explicit return value, and an EVM exception would be raised when calling
// a token with the mismatched return value.
bytes memory payload = abi.encodeWithSignature(
"transferFrom(address,address,uint256)",
_user,
address(this),
_amount
);
bytes memory returnData = _callContract(_assetId, payload);
// Ensure that the asset transfer succeeded
_validateContractCallResult(returnData);
uint256 finalBalance = tokenBalance(_assetId);
uint256 transferredAmount = finalBalance.sub(initialBalance);
require(transferredAmount == _expectedAmount, "Invalid transfer");
}
/// @notice Transfers tokens from the contract to a user
/// @param _receivingAddress The address to transfer the tokens to
/// @param _assetId The address of the token to transfer
/// @param _amount The number of tokens to transfer
function transferTokensOut(
address _receivingAddress,
address _assetId,
uint256 _amount
)
public
{
_validateContractAddress(_assetId);
// Some tokens have a `transfer` which returns a boolean and some do not.
// The ERC20 interface cannot be used here because it requires specifying
// an explicit return value, and an EVM exception would be raised when calling
// a token with the mismatched return value.
bytes memory payload = abi.encodeWithSignature(
"transfer(address,uint256)",
_receivingAddress,
_amount
);
bytes memory returnData = _callContract(_assetId, payload);
// Ensure that the asset transfer succeeded
_validateContractCallResult(returnData);
}
/// @notice Returns the number of tokens owned by this contract
/// @param _assetId The address of the token to query
function externalBalance(address _assetId) public view returns (uint256) {
if (_assetId == ETHER_ADDR) {
return address(this).balance;
}
return tokenBalance(_assetId);
}
/// @notice Returns the number of tokens owned by this contract.
/// @dev This will not work for Ether tokens, use `externalBalance` for
/// Ether tokens.
/// @param _assetId The address of the token to query
function tokenBalance(address _assetId) public view returns (uint256) {
return ERC20(_assetId).balanceOf(address(this));
}
/// @dev Validates that the specified `_hash` was signed by the specified `_user`.
/// This method supports the EIP712 specification, the older Ethereum
/// signed message specification is also supported for backwards compatibility.
/// @param _hash The original hash that was signed by the user
/// @param _user The user who signed the hash
/// @param _v The `v` component of the `_user`'s signature
/// @param _r The `r` component of the `_user`'s signature
/// @param _s The `s` component of the `_user`'s signature
/// @param _prefixed If true, the signature will be verified
/// against the Ethereum signed message specification instead of the
/// EIP712 specification
function validateSignature(
bytes32 _hash,
address _user,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool _prefixed
)
public
pure
{
bytes32 eip712Hash = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
_hash
));
if (_prefixed) {
bytes32 prefixedHash = keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
eip712Hash
));
require(_user == ecrecover(prefixedHash, _v, _r, _s), "Invalid signature");
} else {
require(_user == ecrecover(eip712Hash, _v, _r, _s), "Invalid signature");
}
}
/// @dev Ensures that `_address` is not the zero address
/// @param _address The address to check
function validateAddress(address _address) public pure {
require(_address != address(0), "Invalid address");
}
/// @dev Credit fillers for each fill.wantAmount,and credit the operator
/// for each fill.feeAmount. See the `trade` method for param details.
/// @param _values Values from `trade`
function _creditFillBalances(
uint256[] memory _increments,
uint256[] memory _values
)
private
pure
{
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
// i + numFills * 2
uint256 end = i + ((_values[0] & mask16) >> 8) * 2;
// loop fills
for(i; i < end; i += 2) {
uint256 fillerWantAssetIndex = (_values[i] & mask24) >> 16;
uint256 wantAmount = _values[i + 1] >> 128;
// credit fill.wantAmount to filler
_increments[fillerWantAssetIndex] = _increments[fillerWantAssetIndex].add(wantAmount);
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
uint256 operatorFeeAssetIndex = ((_values[i] & mask40) >> 32);
// credit fill.feeAmount to operator
_increments[operatorFeeAssetIndex] = _increments[operatorFeeAssetIndex].add(feeAmount);
}
}
/// @dev Credit makers for each amount received through a matched fill.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _creditMakerBalances(
uint256[] memory _increments,
uint256[] memory _values
)
private
pure
{
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for(i; i < end; i++) {
// match.offerIndex
uint256 offerIndex = _values[i] & mask8;
// maker.wantAssetIndex
uint256 makerWantAssetIndex = (_values[1 + offerIndex * 2] & mask24) >> 16;
// match.takeAmount
uint256 amount = _values[i] >> 128;
// receiveAmount = match.takeAmount * offer.wantAmount / offer.offerAmount
amount = amount.mul(_values[2 + offerIndex * 2] >> 128)
.div(_values[2 + offerIndex * 2] & mask128);
// credit maker for the amount received from the match
_increments[makerWantAssetIndex] = _increments[makerWantAssetIndex].add(amount);
}
}
/// @dev Credit the operator for each offer.feeAmount if the offer has not
/// been recorded through a previous `trade` call.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _creditMakerFeeBalances(
uint256[] memory _increments,
uint256[] memory _values
)
private
pure
{
uint256 i = 1;
// i + numOffers * 2
uint256 end = i + (_values[0] & mask8) * 2;
// loop offers
for(i; i < end; i += 2) {
bool nonceTaken = ((_values[i] & mask128) >> 120) == 1;
if (nonceTaken) { continue; }
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
uint256 operatorFeeAssetIndex = (_values[i] & mask40) >> 32;
// credit make.feeAmount to operator
_increments[operatorFeeAssetIndex] = _increments[operatorFeeAssetIndex].add(feeAmount);
}
}
/// @dev Deduct tokens from fillers for each fill.offerAmount
/// and each fill.feeAmount.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _deductFillBalances(
uint256[] memory _decrements,
uint256[] memory _values
)
private
pure
{
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
// i + numFills * 2
uint256 end = i + ((_values[0] & mask16) >> 8) * 2;
// loop fills
for(i; i < end; i += 2) {
uint256 fillerOfferAssetIndex = (_values[i] & mask16) >> 8;
uint256 offerAmount = _values[i + 1] & mask128;
// deduct fill.offerAmount from filler
_decrements[fillerOfferAssetIndex] = _decrements[fillerOfferAssetIndex].add(offerAmount);
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
// deduct fill.feeAmount from filler
uint256 fillerFeeAssetIndex = (_values[i] & mask32) >> 24;
_decrements[fillerFeeAssetIndex] = _decrements[fillerFeeAssetIndex].add(feeAmount);
}
}
/// @dev Deduct tokens from makers for each offer.offerAmount
/// and each offer.feeAmount if the offer has not been recorded
/// through a previous `trade` call.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _deductMakerBalances(
uint256[] memory _decrements,
uint256[] memory _values
)
private
pure
{
uint256 i = 1;
// i + numOffers * 2
uint256 end = i + (_values[0] & mask8) * 2;
// loop offers
for(i; i < end; i += 2) {
bool nonceTaken = ((_values[i] & mask128) >> 120) == 1;
if (nonceTaken) { continue; }
uint256 makerOfferAssetIndex = (_values[i] & mask16) >> 8;
uint256 offerAmount = _values[i + 1] & mask128;
// deduct make.offerAmount from maker
_decrements[makerOfferAssetIndex] = _decrements[makerOfferAssetIndex].add(offerAmount);
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
// deduct make.feeAmount from maker
uint256 makerFeeAssetIndex = (_values[i] & mask32) >> 24;
_decrements[makerFeeAssetIndex] = _decrements[makerFeeAssetIndex].add(feeAmount);
}
}
/// @dev Emits trade events for easier tracking
/// @param _values The _values param from the trade / networkTrade method
/// @param _addresses The _addresses param from the trade / networkTrade method
/// @param _marketDapps The _marketDapps from BrokerV2
/// @param _forNetworkTrade Whether this is called from the networkTrade method
function _emitTradeEvents(
uint256[] memory _values,
address[] memory _addresses,
address[] memory _marketDapps,
bool _forNetworkTrade
)
private
{
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for(i; i < end; i++) {
uint256[] memory data = new uint256[](7);
data[0] = _values[i] & mask8; // match.offerIndex
data[1] = _values[1 + data[0] * 2] & mask8; // makerIndex
data[2] = (_values[1 + data[0] * 2] & mask16) >> 8; // makerOfferAssetIndex
data[3] = (_values[1 + data[0] * 2] & mask24) >> 16; // makerWantAssetIndex
data[4] = _values[i] >> 128; // match.takeAmount
// receiveAmount = match.takeAmount * offer.wantAmount / offer.offerAmount
data[5] = data[4].mul(_values[2 + data[0] * 2] >> 128)
.div(_values[2 + data[0] * 2] & mask128);
// match.fillIndex for `trade`, marketDappIndex for `networkTrade`
data[6] = (_values[i] & mask16) >> 8;
address filler;
if (_forNetworkTrade) {
filler = _marketDapps[data[6]];
} else {
uint256 fillerIndex = (_values[1 + data[6] * 2] & mask8);
filler = _addresses[fillerIndex * 2];
}
emit Trade(
_addresses[data[1] * 2], // maker
filler,
_addresses[data[2] * 2 + 1], // makerGiveAsset
data[4], // makerGiveAmount
_addresses[data[3] * 2 + 1], // fillerGiveAsset
data[5] // fillerGiveAmount
);
}
}
/// @notice Executes a trade against an external market.
/// @dev The initial Ether or token balance is compared with the
/// balance after the trade to ensure that the appropriate amounts of
/// tokens were taken and an appropriate amount received.
/// The trade will fail if the number of tokens received is less than
/// expected. If the number of tokens received is more than expected than
/// the excess tokens are transferred to the `BrokerV2.operator`.
/// @param _assetIds[0] The offerAssetId of the offer
/// @param _assetIds[1] The wantAssetId of the offer
/// @param _assetIds[2] The surplusAssetId
/// @param _dataValues[0] The number of tokens offerred
/// @param _dataValues[1] The number of tokens expected to be received
/// @param _dataValues[2] Match data
/// @param _marketDapps See `BrokerV2.marketDapps`
/// @param _addresses Addresses from `networkTrade`
function _performNetworkTrade(
address[] memory _assetIds,
uint256[] memory _dataValues,
address[] memory _marketDapps,
address[] memory _addresses
)
private
returns (uint256)
{
uint256 dappIndex = (_dataValues[2] & mask16) >> 8;
validateAddress(_marketDapps[dappIndex]);
MarketDapp marketDapp = MarketDapp(_marketDapps[dappIndex]);
uint256[] memory funds = new uint256[](6);
funds[0] = externalBalance(_assetIds[0]); // initialOfferTokenBalance
funds[1] = externalBalance(_assetIds[1]); // initialWantTokenBalance
if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) {
funds[2] = externalBalance(_assetIds[2]); // initialSurplusTokenBalance
}
uint256 ethValue = 0;
address tokenReceiver;
if (_assetIds[0] == ETHER_ADDR) {
ethValue = _dataValues[0]; // offerAmount
} else {
tokenReceiver = marketDapp.tokenReceiver(_assetIds, _dataValues, _addresses);
approveTokenTransfer(
_assetIds[0], // offerAssetId
tokenReceiver,
_dataValues[0] // offerAmount
);
}
marketDapp.trade.value(ethValue)(
_assetIds,
_dataValues,
_addresses,
// use uint160 to cast `address` to `address payable`
address(uint160(address(this))) // destAddress
);
funds[3] = externalBalance(_assetIds[0]); // finalOfferTokenBalance
funds[4] = externalBalance(_assetIds[1]); // finalWantTokenBalance
if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) {
funds[5] = externalBalance(_assetIds[2]); // finalSurplusTokenBalance
}
uint256 surplusAmount = 0;
// validate that the appropriate offerAmount was deducted
// surplusAssetId == offerAssetId
if (_assetIds[2] == _assetIds[0]) {
// surplusAmount = finalOfferTokenBalance - (initialOfferTokenBalance - offerAmount)
surplusAmount = funds[3].sub(funds[0].sub(_dataValues[0]));
} else {
// finalOfferTokenBalance == initialOfferTokenBalance - offerAmount
require(funds[3] == funds[0].sub(_dataValues[0]), "Invalid offer asset balance");
}
// validate that the appropriate wantAmount was credited
// surplusAssetId == wantAssetId
if (_assetIds[2] == _assetIds[1]) {
// surplusAmount = finalWantTokenBalance - (initialWantTokenBalance + wantAmount)
surplusAmount = funds[4].sub(funds[1].add(_dataValues[1]));
} else {
// finalWantTokenBalance == initialWantTokenBalance + wantAmount
require(funds[4] == funds[1].add(_dataValues[1]), "Invalid want asset balance");
}
// surplusAssetId != offerAssetId && surplusAssetId != wantAssetId
if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) {
// surplusAmount = finalSurplusTokenBalance - initialSurplusTokenBalance
surplusAmount = funds[5].sub(funds[2]);
}
// set the approved token amount back to zero
if (_assetIds[0] != ETHER_ADDR) {
approveTokenTransfer(
_assetIds[0],
tokenReceiver,
0
);
}
return surplusAmount;
}
/// @dev Validates input lengths based on the expected format
/// detailed in the `trade` method.
/// @param _values Values from `trade`
/// @param _hashes Hashes from `trade`
function _validateTradeInputLengths(
uint256[] memory _values,
bytes32[] memory _hashes
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
uint256 numFills = (_values[0] & mask16) >> 8;
uint256 numMatches = (_values[0] & mask24) >> 16;
// Validate that bits(24..256) are zero
require(_values[0] >> 24 == 0, "Invalid trade input");
// It is enforced by other checks that if a fill is present
// then it must be completely filled so there must be at least one offer
// and at least one match in this case.
// It is possible to have one offer with no matches and no fills
// but that is blocked by this check as there is no foreseeable use
// case for it.
require(
numOffers > 0 && numFills > 0 && numMatches > 0,
"Invalid trade input"
);
require(
_values.length == 1 + numOffers * 2 + numFills * 2 + numMatches,
"Invalid _values.length"
);
require(
_hashes.length == (numOffers + numFills) * 2,
"Invalid _hashes.length"
);
}
/// @dev Validates input lengths based on the expected format
/// detailed in the `networkTrade` method.
/// @param _values Values from `networkTrade`
/// @param _hashes Hashes from `networkTrade`
function _validateNetworkTradeInputLengths(
uint256[] memory _values,
bytes32[] memory _hashes
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
uint256 numFills = (_values[0] & mask16) >> 8;
uint256 numMatches = (_values[0] & mask24) >> 16;
// Validate that bits(24..256) are zero
require(_values[0] >> 24 == 0, "Invalid networkTrade input");
// Validate that numFills is zero because the offers
// should be filled against external orders
require(
numOffers > 0 && numMatches > 0 && numFills == 0,
"Invalid networkTrade input"
);
require(
_values.length == 1 + numOffers * 2 + numMatches,
"Invalid _values.length"
);
require(
_hashes.length == numOffers * 2,
"Invalid _hashes.length"
);
}
/// @dev See the `BrokerV2.trade` method for an explanation of why offer
/// uniquness is required.
/// The set of offers in `_values` must be sorted such that offer nonces'
/// are arranged in a strictly ascending order.
/// This allows the validation of offer uniqueness to be done in O(N) time,
/// with N being the number of offers.
/// @param _values Values from `trade`
function _validateUniqueOffers(uint256[] memory _values) private pure {
uint256 numOffers = _values[0] & mask8;
uint256 prevNonce;
for(uint256 i = 0; i < numOffers; i++) {
uint256 nonce = (_values[i * 2 + 1] & mask120) >> 56;
if (i == 0) {
// Set the value of the first nonce
prevNonce = nonce;
continue;
}
require(nonce > prevNonce, "Invalid offer nonces");
prevNonce = nonce;
}
}
/// @dev Validate that for every match:
/// 1. offerIndexes fall within the range of offers
/// 2. fillIndexes falls within the range of fills
/// 3. offer.offerAssetId == fill.wantAssetId
/// 4. offer.wantAssetId == fill.offerAssetId
/// 5. takeAmount > 0
/// 6. (offer.wantAmount * takeAmount) % offer.offerAmount == 0
/// @param _values Values from `trade`
/// @param _addresses Addresses from `trade`
function _validateMatches(
uint256[] memory _values,
address[] memory _addresses
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
uint256 numFills = (_values[0] & mask16) >> 8;
uint256 i = 1 + numOffers * 2 + numFills * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 fillIndex = (_values[i] & mask16) >> 8;
require(offerIndex < numOffers, "Invalid match.offerIndex");
require(fillIndex >= numOffers && fillIndex < numOffers + numFills, "Invalid match.fillIndex");
require(
_addresses[_values[1 + offerIndex * 2] & mask8] !=
_addresses[_values[1 + fillIndex * 2] & mask8],
"offer.maker cannot be the same as fill.filler"
);
uint256 makerOfferAssetIndex = (_values[1 + offerIndex * 2] & mask16) >> 8;
uint256 makerWantAssetIndex = (_values[1 + offerIndex * 2] & mask24) >> 16;
uint256 fillerOfferAssetIndex = (_values[1 + fillIndex * 2] & mask16) >> 8;
uint256 fillerWantAssetIndex = (_values[1 + fillIndex * 2] & mask24) >> 16;
require(
_addresses[makerOfferAssetIndex * 2 + 1] ==
_addresses[fillerWantAssetIndex * 2 + 1],
"offer.offerAssetId does not match fill.wantAssetId"
);
require(
_addresses[makerWantAssetIndex * 2 + 1] ==
_addresses[fillerOfferAssetIndex * 2 + 1],
"offer.wantAssetId does not match fill.offerAssetId"
);
// require that bits(16..128) are all zero for every match
require((_values[i] & mask128) >> 16 == uint256(0), "Invalid match data");
uint256 takeAmount = _values[i] >> 128;
require(takeAmount > 0, "Invalid match.takeAmount");
uint256 offerDataB = _values[2 + offerIndex * 2];
// (offer.wantAmount * takeAmount) % offer.offerAmount == 0
require(
(offerDataB >> 128).mul(takeAmount).mod(offerDataB & mask128) == 0,
"Invalid amounts"
);
}
}
/// @dev Validate that for every match:
/// 1. offerIndexes fall within the range of offers
/// 2. _addresses[surplusAssetIndexes * 2] matches the operator address
/// 3. takeAmount > 0
/// 4. (offer.wantAmount * takeAmount) % offer.offerAmount == 0
/// @param _values Values from `trade`
/// @param _addresses Addresses from `trade`
/// @param _operator Address of the `BrokerV2.operator`
function _validateNetworkMatches(
uint256[] memory _values,
address[] memory _addresses,
address _operator
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 surplusAssetIndex = (_values[i] & mask24) >> 16;
require(offerIndex < numOffers, "Invalid match.offerIndex");
require(_addresses[surplusAssetIndex * 2] == _operator, "Invalid operator address");
uint256 takeAmount = _values[i] >> 128;
require(takeAmount > 0, "Invalid match.takeAmount");
uint256 offerDataB = _values[2 + offerIndex * 2];
// (offer.wantAmount * takeAmount) % offer.offerAmount == 0
require(
(offerDataB >> 128).mul(takeAmount).mod(offerDataB & mask128) == 0,
"Invalid amounts"
);
}
}
/// @dev Validate that all fills will be completely filled by the specified
/// matches. See the `BrokerV2.trade` method for an explanation of why
/// fills must be completely filled.
/// @param _values Values from `trade`
function _validateFillAmounts(uint256[] memory _values) private pure {
// "filled" is used to store the sum of `takeAmount`s and `giveAmount`s.
// While a fill's `offerAmount` and `wantAmount` are combined to share
// a single uint256 value, each sum of `takeAmount`s and `giveAmount`s
// for a fill is tracked with an individual uint256 value.
// This is to prevent the verification from being vulnerable to overflow
// issues.
uint256[] memory filled = new uint256[](_values.length);
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 fillIndex = (_values[i] & mask16) >> 8;
uint256 takeAmount = _values[i] >> 128;
uint256 wantAmount = _values[2 + offerIndex * 2] >> 128;
uint256 offerAmount = _values[2 + offerIndex * 2] & mask128;
// giveAmount = takeAmount * wantAmount / offerAmount
uint256 giveAmount = takeAmount.mul(wantAmount).div(offerAmount);
// (1 + fillIndex * 2) would give the index of the first part
// of the data for the fill at fillIndex within `_values`,
// and (2 + fillIndex * 2) would give the index of the second part
filled[1 + fillIndex * 2] = filled[1 + fillIndex * 2].add(giveAmount);
filled[2 + fillIndex * 2] = filled[2 + fillIndex * 2].add(takeAmount);
}
// numOffers
i = _values[0] & mask8;
// i + numFills
end = i + ((_values[0] & mask16) >> 8);
// loop fills
for(i; i < end; i++) {
require(
// fill.offerAmount == (sum of given amounts for fill)
_values[i * 2 + 2] & mask128 == filled[i * 2 + 1] &&
// fill.wantAmount == (sum of taken amounts for fill)
_values[i * 2 + 2] >> 128 == filled[i * 2 + 2],
"Invalid fills"
);
}
}
/// @dev Validates that for every offer / fill
/// 1. user address matches address referenced by user.offerAssetIndex
/// 2. user address matches address referenced by user.wantAssetIndex
/// 3. user address matches address referenced by user.feeAssetIndex
/// 4. offerAssetId != wantAssetId
/// 5. offerAmount > 0 && wantAmount > 0
/// 6. Specified `operator` address matches the expected `operator` address,
/// 7. Specified `operator.feeAssetId` matches the offer's feeAssetId
/// @param _values Values from `trade`
/// @param _addresses Addresses from `trade`
function _validateTradeData(
uint256[] memory _values,
address[] memory _addresses,
address _operator
)
private
pure
{
// numOffers + numFills
uint256 end = (_values[0] & mask8) +
((_values[0] & mask16) >> 8);
for (uint256 i = 0; i < end; i++) {
uint256 dataA = _values[i * 2 + 1];
uint256 dataB = _values[i * 2 + 2];
uint256 feeAssetIndex = ((dataA & mask40) >> 32) * 2;
require(
// user address == user in user.offerAssetIndex pair
_addresses[(dataA & mask8) * 2] ==
_addresses[((dataA & mask16) >> 8) * 2],
"Invalid user in user.offerAssetIndex"
);
require(
// user address == user in user.wantAssetIndex pair
_addresses[(dataA & mask8) * 2] ==
_addresses[((dataA & mask24) >> 16) * 2],
"Invalid user in user.wantAssetIndex"
);
require(
// user address == user in user.feeAssetIndex pair
_addresses[(dataA & mask8) * 2] ==
_addresses[((dataA & mask32) >> 24) * 2],
"Invalid user in user.feeAssetIndex"
);
require(
// offerAssetId != wantAssetId
_addresses[((dataA & mask16) >> 8) * 2 + 1] !=
_addresses[((dataA & mask24) >> 16) * 2 + 1],
"Invalid trade assets"
);
require(
// offerAmount > 0 && wantAmount > 0
(dataB & mask128) > 0 && (dataB >> 128) > 0,
"Invalid trade amounts"
);
require(
_addresses[feeAssetIndex] == _operator,
"Invalid operator address"
);
require(
_addresses[feeAssetIndex + 1] ==
_addresses[((dataA & mask32) >> 24) * 2 + 1],
"Invalid operator fee asset ID"
);
}
}
/// @dev Validates signatures for a set of offers or fills
/// Note that the r value of the offer / fill in _hashes will be
/// overwritten by the hash of that offer / fill
/// @param _values Values from `trade`
/// @param _hashes Hashes from `trade`
/// @param _addresses Addresses from `trade`
/// @param _typehash The typehash used to construct the signed hash
/// @param _i The starting index to verify
/// @param _end The ending index to verify
/// @return An array of hash keys if _i started as 0, because only
/// the hash keys of offers are needed
function _validateTradeSignatures(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses,
bytes32 _typehash,
uint256 _i,
uint256 _end
)
private
pure
{
for (_i; _i < _end; _i++) {
uint256 dataA = _values[_i * 2 + 1];
uint256 dataB = _values[_i * 2 + 2];
bytes32 hashKey = keccak256(abi.encode(
_typehash,
_addresses[(dataA & mask8) * 2], // user
_addresses[((dataA & mask16) >> 8) * 2 + 1], // offerAssetId
dataB & mask128, // offerAmount
_addresses[((dataA & mask24) >> 16) * 2 + 1], // wantAssetId
dataB >> 128, // wantAmount
_addresses[((dataA & mask32) >> 24) * 2 + 1], // feeAssetId
dataA >> 128, // feeAmount
(dataA & mask120) >> 56 // nonce
));
bool prefixedSignature = ((dataA & mask56) >> 48) != 0;
validateSignature(
hashKey,
_addresses[(dataA & mask8) * 2], // user
uint8((dataA & mask48) >> 40), // The `v` component of the user's signature
_hashes[_i * 2], // The `r` component of the user's signature
_hashes[_i * 2 + 1], // The `s` component of the user's signature
prefixedSignature
);
_hashes[_i * 2] = hashKey;
}
}
/// @dev Ensure that the address is a deployed contract
/// @param _contract The address to check
function _validateContractAddress(address _contract) private view {
assembly {
if iszero(extcodesize(_contract)) { revert(0, 0) }
}
}
/// @dev A thin wrapper around the native `call` function, to
/// validate that the contract `call` must be successful.
/// See https://solidity.readthedocs.io/en/v0.5.1/050-breaking-changes.html
/// for details on constructing the `_payload`
/// @param _contract Address of the contract to call
/// @param _payload The data to call the contract with
/// @return The data returned from the contract call
function _callContract(
address _contract,
bytes memory _payload
)
private
returns (bytes memory)
{
bool success;
bytes memory returnData;
(success, returnData) = _contract.call(_payload);
require(success, "Contract call failed");
return returnData;
}
/// @dev Fix for ERC-20 tokens that do not have proper return type
/// See: https://github.com/ethereum/solidity/issues/4116
/// https://medium.com/loopring-protocol/an-incompatibility-in-smart-contract-threatening-dapp-ecosystem-72b8ca5db4da
/// https://github.com/sec-bit/badERC20Fix/blob/master/badERC20Fix.sol
/// @param _data The data returned from a transfer call
function _validateContractCallResult(bytes memory _data) private pure {
require(
_data.length == 0 ||
(_data.length == 32 && _getUint256FromBytes(_data) != 0),
"Invalid contract call result"
);
}
/// @dev Converts data of type `bytes` into its corresponding `uint256` value
/// @param _data The data in bytes
/// @return The corresponding `uint256` value
function _getUint256FromBytes(
bytes memory _data
)
private
pure
returns (uint256)
{
uint256 parsed;
assembly { parsed := mload(add(_data, 32)) }
return parsed;
}
}
// File: contracts/BrokerV2.sol
pragma solidity 0.5.12;
interface IERC1820Registry {
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
}
interface TokenList {
function validateToken(address assetId) external view;
}
interface SpenderList {
function validateSpender(address spender) external view;
function validateSpenderAuthorization(address user, address spender) external view;
}
/// @title The BrokerV2 contract for Switcheo Exchange
/// @author Switcheo Network
/// @notice This contract faciliates Ethereum and Ethereum token trades
/// between users.
/// Users can trade with each other by making and taking offers without
/// giving up custody of their tokens.
/// Users should first deposit tokens, then communicate off-chain
/// with the exchange coordinator, in order to place orders.
/// This allows trades to be confirmed immediately by the coordinator,
/// and settled on-chain through this contract at a later time.
///
/// @dev Bit compacting is used in the contract to reduce gas costs, when
/// it is used, params are documented as bits(n..m).
/// This means that the documented value is represented by bits starting
/// from and including `n`, up to and excluding `m`.
/// For example, bits(8..16), indicates that the value is represented by bits:
/// [8, 9, 10, 11, 12, 13, 14, 15].
///
/// Bit manipulation of the form (data & ~(~uint(0) << m)) >> n is frequently
/// used to recover the value at the specified bits.
/// For example, to recover bits(2..7) from a uint8 value, we can use
/// (data & ~(~uint8(0) << 7)) >> 2.
/// Given a `data` value of `1101,0111`, bits(2..7) should give "10101".
/// ~uint8(0): "1111,1111" (8 ones)
/// (~uint8(0) << 7): "1000,0000" (1 followed by 7 zeros)
/// ~(~uint8(0) << 7): "0111,1111" (0 followed by 7 ones)
/// (data & ~(~uint8(0) << 7)): "0101,0111" (bits after the 7th bit is zeroed)
/// (data & ~(~uint8(0) << 7)) >> 2: "0001,0101" (matching the expected "10101")
///
/// Additionally, bit manipulation of the form data >> n is used to recover
/// bits(n..e), where e is equal to the number of bits in the data.
/// For example, to recover bits(4..8) from a uint8 value, we can use data >> 4.
/// Given a data value of "1111,1111", bits(4..8) should give "1111".
/// data >> 4: "0000,1111" (matching the expected "1111")
///
/// There is frequent reference and usage of asset IDs, this is a unique
/// identifier used within the contract to represent individual assets.
/// For all tokens, the asset ID is identical to the contract address
/// of the token, this is so that additional mappings are not needed to
/// identify tokens during deposits and withdrawals.
/// The only exception is the Ethereum token, which does not have a contract
/// address, for this reason, the zero address is used to represent the
/// Ethereum token's ID.
contract BrokerV2 is Ownable, ReentrancyGuard {
using SafeMath for uint256;
struct WithdrawalAnnouncement {
uint256 amount;
uint256 withdrawableAt;
}
// Exchange states
enum State { Active, Inactive }
// Exchange admin states
enum AdminState { Normal, Escalated }
// The constants for EIP-712 are precompiled to reduce contract size,
// the original values are left here for reference and verification.
//
// bytes32 public constant WITHDRAW_TYPEHASH = keccak256(abi.encodePacked(
// "Withdraw(",
// "address withdrawer,",
// "address receivingAddress,",
// "address assetId,",
// "uint256 amount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant WITHDRAW_TYPEHASH = 0xbe2f4292252fbb88b129dc7717b2f3f74a9afb5b13a2283cac5c056117b002eb;
// bytes32 public constant OFFER_TYPEHASH = keccak256(abi.encodePacked(
// "Offer(",
// "address maker,",
// "address offerAssetId,",
// "uint256 offerAmount,",
// "address wantAssetId,",
// "uint256 wantAmount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant OFFER_TYPEHASH = 0xf845c83a8f7964bc8dd1a092d28b83573b35be97630a5b8a3b8ae2ae79cd9260;
// bytes32 public constant SWAP_TYPEHASH = keccak256(abi.encodePacked(
// "Swap(",
// "address maker,",
// "address taker,",
// "address assetId,",
// "uint256 amount,",
// "bytes32 hashedSecret,",
// "uint256 expiryTime,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant SWAP_TYPEHASH = 0x6ba9001457a287c210b728198a424a4222098d7fac48f8c5fb5ab10ef907d3ef;
// The Ether token address is set as the constant 0x00 for backwards
// compatibility
address private constant ETHER_ADDR = address(0);
// The maximum length of swap secret values
uint256 private constant MAX_SWAP_SECRET_LENGTH = 64;
// Reason codes are used by the off-chain coordinator to track balance changes
uint256 private constant REASON_DEPOSIT = 0x01;
uint256 private constant REASON_WITHDRAW = 0x09;
uint256 private constant REASON_WITHDRAW_FEE_GIVE = 0x14;
uint256 private constant REASON_WITHDRAW_FEE_RECEIVE = 0x15;
uint256 private constant REASON_CANCEL = 0x08;
uint256 private constant REASON_CANCEL_FEE_GIVE = 0x12;
uint256 private constant REASON_CANCEL_FEE_RECEIVE = 0x13;
uint256 private constant REASON_SWAP_GIVE = 0x30;
uint256 private constant REASON_SWAP_FEE_GIVE = 0x32;
uint256 private constant REASON_SWAP_RECEIVE = 0x35;
uint256 private constant REASON_SWAP_FEE_RECEIVE = 0x37;
uint256 private constant REASON_SWAP_CANCEL_RECEIVE = 0x38;
uint256 private constant REASON_SWAP_CANCEL_FEE_RECEIVE = 0x3B;
uint256 private constant REASON_SWAP_CANCEL_FEE_REFUND = 0x3D;
// 7 days * 24 hours * 60 mins * 60 seconds: 604800
uint256 private constant MAX_SLOW_WITHDRAW_DELAY = 604800;
uint256 private constant MAX_SLOW_CANCEL_DELAY = 604800;
uint256 private constant mask8 = ~(~uint256(0) << 8);
uint256 private constant mask16 = ~(~uint256(0) << 16);
uint256 private constant mask24 = ~(~uint256(0) << 24);
uint256 private constant mask32 = ~(~uint256(0) << 32);
uint256 private constant mask40 = ~(~uint256(0) << 40);
uint256 private constant mask120 = ~(~uint256(0) << 120);
uint256 private constant mask128 = ~(~uint256(0) << 128);
uint256 private constant mask136 = ~(~uint256(0) << 136);
uint256 private constant mask144 = ~(~uint256(0) << 144);
State public state;
AdminState public adminState;
// All fees will be transferred to the operator address
address public operator;
TokenList public tokenList;
SpenderList public spenderList;
// The delay in seconds to complete the respective escape hatch (`slowCancel` / `slowWithdraw`).
// This gives the off-chain service time to update the off-chain state
// before the state is separately updated by the user.
uint256 public slowCancelDelay;
uint256 public slowWithdrawDelay;
// A mapping of remaining offer amounts: offerHash => availableAmount
mapping(bytes32 => uint256) public offers;
// A mapping of used nonces: nonceIndex => nonceData
// The storing of nonces is used to ensure that transactions signed by
// the user can only be used once.
// For space and gas cost efficiency, one nonceData is used to store the
// state of 256 nonces.
// This reduces the average cost of storing a new nonce from 20,000 gas
// to 5000 + 20,000 / 256 = 5078.125 gas
// See _markNonce and _nonceTaken for more details.
mapping(uint256 => uint256) public usedNonces;
// A mapping of user balances: userAddress => assetId => balance
mapping(address => mapping(address => uint256)) public balances;
// A mapping of atomic swap states: swapHash => isSwapActive
mapping(bytes32 => bool) public atomicSwaps;
// A record of admin addresses: userAddress => isAdmin
mapping(address => bool) public adminAddresses;
// A record of market DApp addresses
address[] public marketDapps;
// A mapping of cancellation announcements for the cancel escape hatch: offerHash => cancellableAt
mapping(bytes32 => uint256) public cancellationAnnouncements;
// A mapping of withdrawal announcements: userAddress => assetId => { amount, withdrawableAt }
mapping(address => mapping(address => WithdrawalAnnouncement)) public withdrawalAnnouncements;
// Emitted on positive balance state transitions
event BalanceIncrease(
address indexed user,
address indexed assetId,
uint256 amount,
uint256 reason,
uint256 nonce
);
// Emitted on negative balance state transitions
event BalanceDecrease(
address indexed user,
address indexed assetId,
uint256 amount,
uint256 reason,
uint256 nonce
);
// Compacted versions of the `BalanceIncrease` and `BalanceDecrease` events.
// These are used in the `trade` method, they are compacted to save gas costs.
event Increment(uint256 data);
event Decrement(uint256 data);
event TokenFallback(
address indexed user,
address indexed assetId,
uint256 amount
);
event TokensReceived(
address indexed user,
address indexed assetId,
uint256 amount
);
event AnnounceCancel(
bytes32 indexed offerHash,
uint256 cancellableAt
);
event SlowCancel(
bytes32 indexed offerHash,
uint256 amount
);
event AnnounceWithdraw(
address indexed withdrawer,
address indexed assetId,
uint256 amount,
uint256 withdrawableAt
);
event SlowWithdraw(
address indexed withdrawer,
address indexed assetId,
uint256 amount
);
/// @notice Initializes the Broker contract
/// @dev The coordinator, operator and owner (through Ownable) is initialized
/// to be the address of the sender.
/// The Broker is put into an active state, with maximum exit delays set.
/// The Broker is also registered as an implementer of ERC777TokensRecipient
/// through the ERC1820 registry.
constructor(address _tokenListAddress, address _spenderListAddress) public {
adminAddresses[msg.sender] = true;
operator = msg.sender;
tokenList = TokenList(_tokenListAddress);
spenderList = SpenderList(_spenderListAddress);
slowWithdrawDelay = MAX_SLOW_WITHDRAW_DELAY;
slowCancelDelay = MAX_SLOW_CANCEL_DELAY;
state = State.Active;
IERC1820Registry erc1820 = IERC1820Registry(
0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24
);
erc1820.setInterfaceImplementer(
address(this),
keccak256("ERC777TokensRecipient"),
address(this)
);
}
modifier onlyAdmin() {
// Error code 1: onlyAdmin, address is not an admin address
require(adminAddresses[msg.sender], "1");
_;
}
modifier onlyActiveState() {
// Error code 2: onlyActiveState, state is not 'Active'
require(state == State.Active, "2");
_;
}
modifier onlyEscalatedAdminState() {
// Error code 3: onlyEscalatedAdminState, adminState is not 'Escalated'
require(adminState == AdminState.Escalated, "3");
_;
}
/// @notice Checks whether an address is appointed as an admin user
/// @param _user The address to check
/// @return Whether the address is appointed as an admin user
function isAdmin(address _user) external view returns(bool) {
return adminAddresses[_user];
}
/// @notice Sets tbe Broker's state.
/// @dev The two available states are `Active` and `Inactive`.
/// The `Active` state allows for regular exchange activity,
/// while the `Inactive` state prevents the invocation of deposit
/// and trading functions.
/// The `Inactive` state is intended as a means to cease contract operation
/// in the case of an upgrade or in an emergency.
/// @param _state The state to transition the contract into
function setState(State _state) external onlyOwner nonReentrant { state = _state; }
/// @notice Sets the Broker's admin state.
/// @dev The two available states are `Normal` and `Escalated`.
/// In the `Normal` admin state, the admin methods `adminCancel` and `adminWithdraw`
/// are not invocable.
/// The admin state must be set to `Escalated` by the contract owner for these
/// methods to become usable.
/// In an `Escalated` admin state, admin addresses would be able to cancel offers
/// and withdraw balances to the respective user's wallet on behalf of users.
/// The escalated state is intended to be used in the case of a contract upgrade or
/// in an emergency.
/// It is set separately from the `Inactive` state so that it is possible
/// to use admin functions without affecting regular operations.
/// @param _state The admin state to transition the contract into
function setAdminState(AdminState _state) external onlyOwner nonReentrant { adminState = _state; }
/// @notice Sets the operator address.
/// @dev All fees will be transferred to the operator address.
/// @param _operator The address to set as the operator
function setOperator(address _operator) external onlyOwner nonReentrant {
_validateAddress(operator);
operator = _operator;
}
/// @notice Sets the minimum delay between an `announceCancel` call and
/// when the cancellation can actually be executed through `slowCancel`.
/// @dev This gives the off-chain service time to update the off-chain state
/// before the state is separately updated by the user.
/// This differs from the regular `cancel` operation, which does not involve a delay.
/// @param _delay The delay in seconds
function setSlowCancelDelay(uint256 _delay) external onlyOwner nonReentrant {
// Error code 4: setSlowCancelDelay, slow cancel delay exceeds max allowable delay
require(_delay <= MAX_SLOW_CANCEL_DELAY, "4");
slowCancelDelay = _delay;
}
/// @notice Sets the delay between an `announceWithdraw` call and
/// when the withdrawal can actually be executed through `slowWithdraw`.
/// @dev This gives the off-chain service time to update the off-chain state
/// before the state is separately updated by the user.
/// This differs from the regular `withdraw` operation, which does not involve a delay.
/// @param _delay The delay in seconds
function setSlowWithdrawDelay(uint256 _delay) external onlyOwner nonReentrant {
// Error code 5: setSlowWithdrawDelay, slow withdraw delay exceeds max allowable delay
require(_delay <= MAX_SLOW_WITHDRAW_DELAY, "5");
slowWithdrawDelay = _delay;
}
/// @notice Gives admin permissons to the specified address.
/// @dev Admin addresses are intended to coordinate the regular operation
/// of the Broker contract, and to perform special functions such as
/// `adminCancel` and `adminWithdraw`.
/// @param _admin The address to give admin permissions to
function addAdmin(address _admin) external onlyOwner nonReentrant {
_validateAddress(_admin);
// Error code 6: addAdmin, address is already an admin address
require(!adminAddresses[_admin], "6");
adminAddresses[_admin] = true;
}
/// @notice Removes admin permissons for the specified address.
/// @param _admin The admin address to remove admin permissions from
function removeAdmin(address _admin) external onlyOwner nonReentrant {
_validateAddress(_admin);
// Error code 7: removeAdmin, address is not an admin address
require(adminAddresses[_admin], "7");
delete adminAddresses[_admin];
}
/// @notice Adds a market DApp to be used in `networkTrade`
/// @param _dapp Address of the market DApp
function addMarketDapp(address _dapp) external onlyOwner nonReentrant {
_validateAddress(_dapp);
marketDapps.push(_dapp);
}
/// @notice Updates a market DApp to be used in `networkTrade`
/// @param _index Index of the market DApp to update
/// @param _dapp The new address of the market DApp
function updateMarketDapp(uint256 _index, address _dapp) external onlyOwner nonReentrant {
_validateAddress(_dapp);
// Error code 8: updateMarketDapp, _index does not refer to an existing non-zero address
require(marketDapps[_index] != address(0), "8");
marketDapps[_index] = _dapp;
}
/// @notice Removes a market DApp
/// @param _index Index of the market DApp to remove
function removeMarketDapp(uint256 _index) external onlyOwner nonReentrant {
// Error code 9: removeMarketDapp, _index does not refer to a DApp address
require(marketDapps[_index] != address(0), "9");
delete marketDapps[_index];
}
/// @notice Performs a balance transfer from one address to another
/// @dev This method is intended to be invoked by spender contracts.
/// To invoke this method, a spender contract must have been
/// previously whitelisted and also authorized by the address from which
/// funds will be deducted.
/// Balance events are not emitted by this method, they should be separately
/// emitted by the spender contract.
/// @param _from The address to deduct from
/// @param _to The address to credit
/// @param _assetId The asset to transfer
/// @param _amount The amount to transfer
function spendFrom(
address _from,
address _to,
address _assetId,
uint256 _amount
)
external
nonReentrant
{
spenderList.validateSpenderAuthorization(_from, msg.sender);
_validateAddress(_to);
balances[_from][_assetId] = balances[_from][_assetId].sub(_amount);
balances[_to][_assetId] = balances[_to][_assetId].add(_amount);
}
/// @notice Allows a whitelisted contract to mark nonces
/// @dev If the whitelisted contract is malicious or vulnerable then there is
/// a possibility of a DoS attack. However, since this attack requires cooperation
/// of the contract owner, the risk is similar to the contract owner withholding
/// transactions, so there is no violation of the contract's trust model.
/// In the case that nonces are misused, users will still be able to cancel their offers
/// and withdraw all their funds using the escape hatch methods.
/// @param _nonce The nonce to mark
function markNonce(uint256 _nonce) external nonReentrant {
spenderList.validateSpender(msg.sender);
_markNonce(_nonce);
}
/// @notice Returns whether a nonce has been taken
/// @param _nonce The nonce to check
/// @return Whether the nonce has been taken
function nonceTaken(uint256 _nonce) external view returns (bool) {
return _nonceTaken(_nonce);
}
/// @notice Deposits ETH into the sender's contract balance
/// @dev This operation is only usable in an `Active` state
/// to prevent this contract from receiving ETH in the case that its
/// operation has been terminated.
function deposit() external payable onlyActiveState nonReentrant {
// Error code 10: deposit, msg.value is 0
require(msg.value > 0, "10");
_increaseBalance(msg.sender, ETHER_ADDR, msg.value, REASON_DEPOSIT, 0);
}
/// @dev This function is needed as market DApps generally send ETH
/// using the `<address>.transfer` method.
/// It is left empty to avoid issues with the function call running out
/// of gas, as some callers set a small limit on how much gas can be
/// used by the ETH receiver.
function() payable external {}
/// @notice Deposits ERC20 tokens under the `_user`'s balance
/// @dev Transfers token into the Broker contract using the
/// token's `transferFrom` method.
/// The user must have previously authorized the token transfer
/// through the token's `approve` method.
/// This method has separate `_amount` and `_expectedAmount` values
/// to support unconventional token transfers, e.g. tokens which have a
/// proportion burnt on transfer.
/// @param _user The address of the user depositing the tokens
/// @param _assetId The address of the token contract
/// @param _amount The value to invoke the token's `transferFrom` with
/// @param _expectedAmount The final amount expected to be received by this contract
/// @param _nonce A nonce for balance tracking, emitted in the BalanceIncrease event
function depositToken(
address _user,
address _assetId,
uint256 _amount,
uint256 _expectedAmount,
uint256 _nonce
)
external
onlyAdmin
onlyActiveState
nonReentrant
{
_increaseBalance(
_user,
_assetId,
_expectedAmount,
REASON_DEPOSIT,
_nonce
);
Utils.transferTokensIn(
_user,
_assetId,
_amount,
_expectedAmount
);
}
/// @notice Deposits ERC223 tokens under the `_user`'s balance
/// @dev ERC223 tokens should invoke this method when tokens are
/// sent to the Broker contract.
/// The invocation will fail unless the token has been previously
/// whitelisted through the `whitelistToken` method.
/// @param _user The address of the user sending the tokens
/// @param _amount The amount of tokens transferred to the Broker
function tokenFallback(
address _user,
uint _amount,
bytes calldata /* _data */
)
external
onlyActiveState
nonReentrant
{
address assetId = msg.sender;
tokenList.validateToken(assetId);
_increaseBalance(_user, assetId, _amount, REASON_DEPOSIT, 0);
emit TokenFallback(_user, assetId, _amount);
}
/// @notice Deposits ERC777 tokens under the `_user`'s balance
/// @dev ERC777 tokens should invoke this method when tokens are
/// sent to the Broker contract.
/// The invocation will fail unless the token has been previously
/// whitelisted through the `whitelistToken` method.
/// @param _user The address of the user sending the tokens
/// @param _to The address receiving the tokens
/// @param _amount The amount of tokens transferred to the Broker
function tokensReceived(
address /* _operator */,
address _user,
address _to,
uint _amount,
bytes calldata /* _userData */,
bytes calldata /* _operatorData */
)
external
onlyActiveState
nonReentrant
{
if (_to != address(this)) { return; }
address assetId = msg.sender;
tokenList.validateToken(assetId);
_increaseBalance(_user, assetId, _amount, REASON_DEPOSIT, 0);
emit TokensReceived(_user, assetId, _amount);
}
/// @notice Executes an array of offers and fills
/// @dev This method accepts an array of "offers" and "fills" together with
/// an array of "matches" to specify the matching between the "offers" and "fills".
/// The data is bit compacted for ease of index referencing and to reduce gas costs,
/// i.e. data representing different types of information is stored within one 256 bit value.
///
/// For efficient balance updates, the `_addresses` array is meant to contain a
/// unique set of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
/// This allows combining multiple balance updates for a user asset pair
/// into a single update by first calculating the total balance update for
/// a pair at a specified index, then looping through the sums to perform
/// the balance update.
///
/// The added benefit is further gas cost reduction because repeated
/// user asset pairs do not need to be duplicated for the calldata.
///
/// The operator address is enforced to be the contract's current operator
/// address, and the operator fee asset ID is enforced to be identical to
/// the maker's / filler's feeAssetId.
///
/// A tradeoff of compacting the bits is that there is a lower maximum value
/// for offer and fill data, however the limits remain generally practical.
///
/// For `offerAmount`, `wantAmount`, `feeAmount` values, the maximum value
/// is 2^128. For a token with 18 decimals, this allows support for tokens
/// with a maximum supply of 1000 million billion billion (33 zeros).
/// In the case where the maximum value needs to be exceeded, a single
/// offer / fill can be split into multiple offers / fills by the off-chain
/// service.
///
/// For nonces the maximum value is 2^64, or more than a billion billion (19 zeros).
///
/// Offers and fills both encompass information about how much (offerAmount)
/// of a specified token (offerAssetId) the user wants to offer and
/// how much (wantAmount) of another token (wantAssetId) they want
/// in return.
///
/// Each match specifies how much of the match's `offer.offerAmount` should
/// be transferred to the filler, in return, the offer's maker receives:
/// `offer.wantAmount * match.takeAmount / offer.offerAmount` of the
/// `offer.wantAssetId` from the filler.
///
/// A few restirctions are enforced to ensure fairness and security of trades:
/// 1. To prevent unfairness due to rounding issues, it is required that:
/// `offer.wantAmount * match.takeAmount % offer.offerAmount == 0`.
///
/// 2. Fills can be filled by offers which do not individually match
/// the `fill.offerAmount` and `fill.wantAmount` ratio. As such, it is
/// required that:
/// fill.offerAmount == total amount deducted from filler for the fill's
/// associated matches (excluding fees)
/// fill.wantAmount == total amount credited to filler for the fill's
/// associated matches (excluding fees)
///
/// 3. The offer array must not consist of repeated offers. For efficient
/// balance updates, a loop through each offer in the offer array is used
/// to deduct the offer.offerAmount from the respective maker
/// if the offer has not been recorded by a previos `trade` call.
/// If an offer is repeated in the offers array, then there would be
/// duplicate deductions from the maker.
/// To enforce uniqueness, it is required that offers for a trade transaction
/// are sorted such that their nonces are in a strictly ascending order.
///
/// 4. The fill array must not consist of repeated fills, for the same
/// reason why there cannot be repeated offers. Additionally, to prevent
/// replay attacks, all fill nonces are required to be unused.
///
/// @param _values[0] Number of offers, fills, matches
/// bits(0..8): number of offers (numOffers)
/// bits(8..16): number of fills (numFills)
/// bits(16..24): number of matches (numMatches)
/// bits(24..256): must be zero
///
/// @param _values[1 + i * 2] First part of offer data for the i'th offer
/// bits(0..8): Index of the maker's address in _addresses
/// bits(8..16): Index of the maker offerAssetId pair in _addresses
/// bits(16..24): Index of the maker wantAssetId pair in _addresses
/// bits(24..32): Index of the maker feeAssetId pair in _addresses
/// bits(32..40): Index of the operator feeAssetId pair in _addresses
/// bits(40..48): The `v` component of the maker's signature for this offer
/// bits(48..56): Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
/// bits(56..120): The offer nonce to prevent replay attacks
/// bits(120..128): Space to indicate whether the offer nonce has been marked before
/// bits(128..256): The number of tokens to be paid to the operator as fees for this offer
///
/// @param _values[2 + i * 2] Second part of offer data for the i'th offer
/// bits(0..128): offer.offerAmount, i.e. the number of tokens to offer
/// bits(128..256): offer.wantAmount, i.e. the number of tokens to ask for in return
///
/// @param _values[1 + numOffers * 2 + i * 2] First part of fill data for the i'th fill
/// bits(0..8): Index of the filler's address in _addresses
/// bits(8..16): Index of the filler offerAssetId pair in _addresses
/// bits(16..24): Index of the filler wantAssetId pair in _addresses
/// bits(24..32): Index of the filler feeAssetId pair in _addresses
/// bits(32..40): Index of the operator feeAssetId pair in _addresses
/// bits(40..48): The `v` component of the filler's signature for this fill
/// bits(48..56): Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
/// bits(56..120): The fill nonce to prevent replay attacks
/// bits(120..128): Left empty to match the offer values format
/// bits(128..256): The number of tokens to be paid to the operator as fees for this fill
///
/// @param _values[2 + numOffers * 2 + i * 2] Second part of fill data for the i'th fill
/// bits(0..128): fill.offerAmount, i.e. the number of tokens to offer
/// bits(128..256): fill.wantAmount, i.e. the number of tokens to ask for in return
///
/// @param _values[1 + numOffers * 2 + numFills * 2 + i] Data for the i'th match
/// bits(0..8): Index of the offerIndex for this match
/// bits(8..16): Index of the fillIndex for this match
/// bits(128..256): The number of tokens to take from the matched offer's offerAmount
///
/// @param _hashes[i * 2] The `r` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _hashes[i * 2 + 1] The `s` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
function trade(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses
)
public
onlyAdmin
onlyActiveState
nonReentrant
{
// Cache the operator address to reduce gas costs from storage reads
address operatorAddress = operator;
// An array variable to store balance increments / decrements
uint256[] memory statements;
// Cache whether offer nonces are taken in the offer's nonce space
_cacheOfferNonceStates(_values);
// `validateTrades` needs to calculate the hash keys of offers and fills
// to verify the signature of the offer / fill.
// The calculated hash keys are returned to reduce repeated computation.
_hashes = Utils.validateTrades(
_values,
_hashes,
_addresses,
operatorAddress
);
statements = Utils.calculateTradeIncrements(_values, _addresses.length / 2);
_incrementBalances(statements, _addresses, 1);
statements = Utils.calculateTradeDecrements(_values, _addresses.length / 2);
_decrementBalances(statements, _addresses);
// Reduce available offer amounts of offers and store the remaining
// offer amount in the `offers` mapping.
// Offer nonces will also be marked as taken.
_storeOfferData(_values, _hashes);
// Mark all fill nonces as taken in the `usedNonces` mapping.
_storeFillNonces(_values);
}
/// @notice Executes an array of offers against external orders.
/// @dev This method accepts an array of "offers" together with
/// an array of "matches" to specify the matching between the "offers" and
/// external orders.
/// The data is bit compacted and formatted in the same way as the `trade` function.
///
/// @param _values[0] Number of offers, fills, matches
/// bits(0..8): number of offers (numOffers)
/// bits(8..16): number of fills, must be zero
/// bits(16..24): number of matches (numMatches)
/// bits(24..256): must be zero
///
/// @param _values[1 + i * 2] First part of offer data for the i'th offer
/// bits(0..8): Index of the maker's address in _addresses
/// bits(8..16): Index of the maker offerAssetId pair in _addresses
/// bits(16..24): Index of the maker wantAssetId pair in _addresses
/// bits(24..32): Index of the maker feeAssetId pair in _addresses
/// bits(32..40): Index of the operator feeAssetId pair in _addresses
/// bits(40..48): The `v` component of the maker's signature for this offer
/// bits(48..56): Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
/// bits(56..120): The offer nonce to prevent replay attacks
/// bits(120..128): Space to indicate whether the offer nonce has been marked before
/// bits(128..256): The number of tokens to be paid to the operator as fees for this offer
///
/// @param _values[2 + i * 2] Second part of offer data for the i'th offer
/// bits(0..128): offer.offerAmount, i.e. the number of tokens to offer
/// bits(128..256): offer.wantAmount, i.e. the number of tokens to ask for in return
///
/// @param _values[1 + numOffers * 2 + i] Data for the i'th match
/// bits(0..8): Index of the offerIndex for this match
/// bits(8..16): Index of the marketDapp for this match
/// bits(16..24): Index of the surplus receiver and surplus asset ID for this
/// match, for any excess tokens resulting from the trade
/// bits(24..128): Additional DApp specific data
/// bits(128..256): The number of tokens to take from the matched offer's offerAmount
///
/// @param _hashes[i * 2] The `r` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _hashes[i * 2 + 1] The `s` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
function networkTrade(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses
)
public
onlyAdmin
onlyActiveState
nonReentrant
{
// Cache the operator address to reduce gas costs from storage reads
address operatorAddress = operator;
// An array variable to store balance increments / decrements
uint256[] memory statements;
// Cache whether offer nonces are taken in the offer's nonce space
_cacheOfferNonceStates(_values);
// `validateNetworkTrades` needs to calculate the hash keys of offers
// to verify the signature of the offer.
// The calculated hash keys for each offer is return to reduce repeated
// computation.
_hashes = Utils.validateNetworkTrades(
_values,
_hashes,
_addresses,
operatorAddress
);
statements = Utils.calculateNetworkTradeIncrements(_values, _addresses.length / 2);
_incrementBalances(statements, _addresses, 1);
statements = Utils.calculateNetworkTradeDecrements(_values, _addresses.length / 2);
_decrementBalances(statements, _addresses);
// Reduce available offer amounts of offers and store the remaining
// offer amount in the `offers` mapping.
// Offer nonces will also be marked as taken.
_storeOfferData(_values, _hashes);
// There may be excess tokens resulting from a trade
// Any excess tokens are returned and recorded in `increments`
statements = Utils.performNetworkTrades(
_values,
_addresses,
marketDapps
);
_incrementBalances(statements, _addresses, 0);
}
/// @notice Cancels a perviously made offer and refunds the remaining offer
/// amount to the offer maker.
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// The `_expectedavailableamount` is required to help prevent accidental
/// cancellation of an offer ahead of time, for example, if there is
/// a pending fill in the off-chain state.
///
/// @param _values[0] The offerAmount and wantAmount of the offer
/// bits(0..128): offer.offerAmount
/// bits(128..256): offer.wantAmount
///
/// @param _values[1] The fee amounts
/// bits(0..128): offer.feeAmount
/// bits(128..256): cancelFeeAmount
///
/// @param _values[2] Additional offer and cancellation data
/// bits(0..128): expectedAvailableAmount
/// bits(128..136): prefixedSignature
/// bits(136..144): The `v` component of the maker's signature for the cancellation
/// bits(144..256): offer.nonce
///
/// @param _hashes[0] The `r` component of the maker's signature for the cancellation
/// @param _hashes[1] The `s` component of the maker's signature for the cancellation
///
/// @param _addresses[0] offer.maker
/// @param _addresses[1] offer.offerAssetId
/// @param _addresses[2] offer.wantAssetId
/// @param _addresses[3] offer.feeAssetId
/// @param _addresses[4] offer.cancelFeeAssetId
function cancel(
uint256[] calldata _values,
bytes32[] calldata _hashes,
address[] calldata _addresses
)
external
onlyAdmin
nonReentrant
{
Utils.validateCancel(_values, _hashes, _addresses);
bytes32 offerHash = Utils.hashOffer(_values, _addresses);
_cancel(
_addresses[0], // maker
offerHash,
_values[2] & mask128, // expectedAvailableAmount
_addresses[1], // offerAssetId
_values[2] >> 144, // offerNonce
_addresses[4], // cancelFeeAssetId
_values[1] >> 128 // cancelFeeAmount
);
}
/// @notice Cancels an offer without requiring the maker's signature
/// @dev This method is intended to be used in the case of a contract
/// upgrade or in an emergency. It can only be invoked by an admin and only
/// after the admin state has been set to `Escalated` by the contract owner.
///
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// The `_expectedavailableamount` is required to help prevent accidental
/// cancellation of an offer ahead of time, for example, if there is
/// a pending fill in the off-chain state.
/// @param _maker The address of the offer's maker
/// @param _offerAssetId The contract address of the offerred asset
/// @param _offerAmount The number of tokens offerred
/// @param _wantAssetId The contract address of the asset asked in return
/// @param _wantAmount The number of tokens asked for in return
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _offerNonce The nonce of the original offer
/// @param _expectedAvailableAmount The offer amount remaining
function adminCancel(
address _maker,
address _offerAssetId,
uint256 _offerAmount,
address _wantAssetId,
uint256 _wantAmount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _offerNonce,
uint256 _expectedAvailableAmount
)
external
onlyAdmin
onlyEscalatedAdminState
nonReentrant
{
bytes32 offerHash = keccak256(abi.encode(
OFFER_TYPEHASH,
_maker,
_offerAssetId,
_offerAmount,
_wantAssetId,
_wantAmount,
_feeAssetId,
_feeAmount,
_offerNonce
));
_cancel(
_maker,
offerHash,
_expectedAvailableAmount,
_offerAssetId,
_offerNonce,
address(0),
0
);
}
/// @notice Announces a user's intention to cancel their offer
/// @dev This method allows a user to cancel their offer without requiring
/// admin permissions.
/// An announcement followed by a delay is needed so that the off-chain
/// service has time to update the off-chain state.
///
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _maker The address of the offer's maker
/// @param _offerAssetId The contract address of the offerred asset
/// @param _offerAmount The number of tokens offerred
/// @param _wantAssetId The contract address of the asset asked in return
/// @param _wantAmount The number of tokens asked for in return
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _offerNonce The nonce of the original offer
function announceCancel(
address _maker,
address _offerAssetId,
uint256 _offerAmount,
address _wantAssetId,
uint256 _wantAmount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _offerNonce
)
external
nonReentrant
{
// Error code 11: announceCancel, invalid msg.sender
require(_maker == msg.sender, "11");
bytes32 offerHash = keccak256(abi.encode(
OFFER_TYPEHASH,
_maker,
_offerAssetId,
_offerAmount,
_wantAssetId,
_wantAmount,
_feeAssetId,
_feeAmount,
_offerNonce
));
// Error code 12: announceCancel, nothing left to cancel
require(offers[offerHash] > 0, "12");
uint256 cancellableAt = now.add(slowCancelDelay);
cancellationAnnouncements[offerHash] = cancellableAt;
emit AnnounceCancel(offerHash, cancellableAt);
}
/// @notice Executes an offer cancellation previously announced in `announceCancel`
/// @dev This method allows a user to cancel their offer without requiring
/// admin permissions.
/// An announcement followed by a delay is needed so that the off-chain
/// service has time to update the off-chain state.
///
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _maker The address of the offer's maker
/// @param _offerAssetId The contract address of the offerred asset
/// @param _offerAmount The number of tokens offerred
/// @param _wantAssetId The contract address of the asset asked in return
/// @param _wantAmount The number of tokens asked for in return
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _offerNonce The nonce of the original offer
function slowCancel(
address _maker,
address _offerAssetId,
uint256 _offerAmount,
address _wantAssetId,
uint256 _wantAmount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _offerNonce
)
external
nonReentrant
{
bytes32 offerHash = keccak256(abi.encode(
OFFER_TYPEHASH,
_maker,
_offerAssetId,
_offerAmount,
_wantAssetId,
_wantAmount,
_feeAssetId,
_feeAmount,
_offerNonce
));
uint256 cancellableAt = cancellationAnnouncements[offerHash];
// Error code 13: slowCancel, cancellation was not announced
require(cancellableAt != 0, "13");
// Error code 14: slowCancel, cancellation delay not yet reached
require(now >= cancellableAt, "14");
uint256 availableAmount = offers[offerHash];
// Error code 15: slowCancel, nothing left to cancel
require(availableAmount > 0, "15");
delete cancellationAnnouncements[offerHash];
_cancel(
_maker,
offerHash,
availableAmount,
_offerAssetId,
_offerNonce,
address(0),
0
);
emit SlowCancel(offerHash, availableAmount);
}
/// @notice Withdraws tokens from the Broker contract to a user's wallet balance
/// @dev The user's internal balance is decreased, and the tokens are transferred
/// to the `_receivingAddress` signed by the user.
/// @param _withdrawer The user address whose balance will be reduced
/// @param _receivingAddress The address to tranfer the tokens to
/// @param _assetId The contract address of the token to withdraw
/// @param _amount The number of tokens to withdraw
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _nonce An unused nonce to prevent replay attacks
/// @param _v The `v` component of the `_user`'s signature
/// @param _r The `r` component of the `_user`'s signature
/// @param _s The `s` component of the `_user`'s signature
/// @param _prefixedSignature Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
function withdraw(
address _withdrawer,
address payable _receivingAddress,
address _assetId,
uint256 _amount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _nonce,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool _prefixedSignature
)
external
onlyAdmin
nonReentrant
{
_markNonce(_nonce);
_validateSignature(
keccak256(abi.encode(
WITHDRAW_TYPEHASH,
_withdrawer,
_receivingAddress,
_assetId,
_amount,
_feeAssetId,
_feeAmount,
_nonce
)),
_withdrawer,
_v,
_r,
_s,
_prefixedSignature
);
_withdraw(
_withdrawer,
_receivingAddress,
_assetId,
_amount,
_feeAssetId,
_feeAmount,
_nonce
);
}
/// @notice Withdraws tokens without requiring the withdrawer's signature
/// @dev This method is intended to be used in the case of a contract
/// upgrade or in an emergency. It can only be invoked by an admin and only
/// after the admin state has been set to `Escalated` by the contract owner.
/// Unlike `withdraw`, tokens can only be withdrawn to the `_withdrawer`'s
/// address.
/// @param _withdrawer The user address whose balance will be reduced
/// @param _assetId The contract address of the token to withdraw
/// @param _amount The number of tokens to withdraw
/// @param _nonce An unused nonce for balance tracking
function adminWithdraw(
address payable _withdrawer,
address _assetId,
uint256 _amount,
uint256 _nonce
)
external
onlyAdmin
onlyEscalatedAdminState
nonReentrant
{
_markNonce(_nonce);
_withdraw(
_withdrawer,
_withdrawer,
_assetId,
_amount,
address(0),
0,
_nonce
);
}
/// @notice Announces a user's intention to withdraw their funds
/// @dev This method allows a user to withdraw their funds without requiring
/// admin permissions.
/// An announcement followed by a delay before execution is needed so that
/// the off-chain service has time to update the off-chain state.
/// @param _assetId The contract address of the token to withdraw
/// @param _amount The number of tokens to withdraw
function announceWithdraw(
address _assetId,
uint256 _amount
)
external
nonReentrant
{
// Error code 16: announceWithdraw, invalid withdrawal amount
require(_amount > 0 && _amount <= balances[msg.sender][_assetId], "16");
WithdrawalAnnouncement storage announcement = withdrawalAnnouncements[msg.sender][_assetId];
announcement.withdrawableAt = now.add(slowWithdrawDelay);
announcement.amount = _amount;
emit AnnounceWithdraw(msg.sender, _assetId, _amount, announcement.withdrawableAt);
}
/// @notice Executes a withdrawal previously announced in `announceWithdraw`
/// @dev This method allows a user to withdraw their funds without requiring
/// admin permissions.
/// An announcement followed by a delay before execution is needed so that
/// the off-chain service has time to update the off-chain state.
/// @param _withdrawer The user address whose balance will be reduced
/// @param _assetId The contract address of the token to withdraw
function slowWithdraw(
address payable _withdrawer,
address _assetId,
uint256 _amount
)
external
nonReentrant
{
WithdrawalAnnouncement memory announcement = withdrawalAnnouncements[_withdrawer][_assetId];
// Error code 17: slowWithdraw, withdrawal was not announced
require(announcement.withdrawableAt != 0, "17");
// Error code 18: slowWithdraw, withdrawal delay not yet reached
require(now >= announcement.withdrawableAt, "18");
// Error code 19: slowWithdraw, withdrawal amount does not match announced amount
require(announcement.amount == _amount, "19");
delete withdrawalAnnouncements[_withdrawer][_assetId];
_withdraw(
_withdrawer,
_withdrawer,
_assetId,
_amount,
address(0),
0,
0
);
emit SlowWithdraw(_withdrawer, _assetId, _amount);
}
/// @notice Locks a user's balances for the first part of an atomic swap
/// @param _addresses[0] maker: the address of the user to deduct the swap tokens from
/// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens
/// if the swap is completed through `executeSwap`
/// @param _addresses[2] assetId: the contract address of the token to swap
/// @param _addresses[3] feeAssetId: the contract address of the token to use as fees
/// @param _values[0] amount: the number of tokens to lock and to transfer if the swap
/// is completed through `executeSwap`
/// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable
/// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees
/// @param _values[3] nonce: an unused nonce to prevent replay attacks
/// @param _hashes[0] hashedSecret: the hash of the secret decided by the maker
/// @param _hashes[1] The `r` component of the user's signature
/// @param _hashes[2] The `s` component of the user's signature
/// @param _v The `v` component of the user's signature
/// @param _prefixedSignature Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
function createSwap(
address[4] calldata _addresses,
uint256[4] calldata _values,
bytes32[3] calldata _hashes,
uint8 _v,
bool _prefixedSignature
)
external
onlyAdmin
onlyActiveState
nonReentrant
{
// Error code 20: createSwap, invalid swap amount
require(_values[0] > 0, "20");
// Error code 21: createSwap, expiry time has already passed
require(_values[1] > now, "21");
_validateAddress(_addresses[1]);
// Error code 39: createSwap, swap maker cannot be the swap taker
require(_addresses[0] != _addresses[1], "39");
bytes32 swapHash = _hashSwap(_addresses, _values, _hashes[0]);
// Error code 22: createSwap, the swap is already active
require(!atomicSwaps[swapHash], "22");
_markNonce(_values[3]);
_validateSignature(
swapHash,
_addresses[0], // swap.maker
_v,
_hashes[1], // r
_hashes[2], // s
_prefixedSignature
);
if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId
// Error code 23: createSwap, swap.feeAmount exceeds swap.amount
require(_values[2] < _values[0], "23"); // feeAmount < amount
} else {
_decreaseBalance(
_addresses[0], // maker
_addresses[3], // feeAssetId
_values[2], // feeAmount
REASON_SWAP_FEE_GIVE,
_values[3] // nonce
);
}
_decreaseBalance(
_addresses[0], // maker
_addresses[2], // assetId
_values[0], // amount
REASON_SWAP_GIVE,
_values[3] // nonce
);
atomicSwaps[swapHash] = true;
}
/// @notice Executes a swap by transferring the tokens previously locked through
/// a `createSwap` call to the swap taker.
///
/// @dev To reduce gas costs, the original parameters of the swap are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _addresses[0] maker: the address of the user to deduct the swap tokens from
/// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens
/// @param _addresses[2] assetId: the contract address of the token to swap
/// @param _addresses[3] feeAssetId: the contract address of the token to use as fees
/// @param _values[0] amount: the number of tokens previously locked
/// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable
/// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees
/// @param _values[3] nonce: an unused nonce to prevent replay attacks
/// @param _hashedSecret The hash of the secret decided by the maker
/// @param _preimage The preimage of the `_hashedSecret`
function executeSwap(
address[4] calldata _addresses,
uint256[4] calldata _values,
bytes32 _hashedSecret,
bytes calldata _preimage
)
external
nonReentrant
{
// Error code 37: swap secret length exceeded
require(_preimage.length <= MAX_SWAP_SECRET_LENGTH, "37");
bytes32 swapHash = _hashSwap(_addresses, _values, _hashedSecret);
// Error code 24: executeSwap, swap is not active
require(atomicSwaps[swapHash], "24");
// Error code 25: executeSwap, hash of preimage does not match hashedSecret
require(sha256(abi.encodePacked(sha256(_preimage))) == _hashedSecret, "25");
uint256 takeAmount = _values[0];
if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId
takeAmount = takeAmount.sub(_values[2]);
}
delete atomicSwaps[swapHash];
_increaseBalance(
_addresses[1], // taker
_addresses[2], // assetId
takeAmount,
REASON_SWAP_RECEIVE,
_values[3] // nonce
);
_increaseBalance(
operator,
_addresses[3], // feeAssetId
_values[2], // feeAmount
REASON_SWAP_FEE_RECEIVE,
_values[3] // nonce
);
}
/// @notice Cancels a swap and refunds the previously locked tokens to
/// the swap maker.
///
/// @dev To reduce gas costs, the original parameters of the swap are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _addresses[0] maker: the address of the user to deduct the swap tokens from
/// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens
/// @param _addresses[2] assetId: the contract address of the token to swap
/// @param _addresses[3] feeAssetId: the contract address of the token to use as fees
/// @param _values[0] amount: the number of tokens previously locked
/// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable
/// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees
/// @param _values[3] nonce: an unused nonce to prevent replay attacks
/// @param _hashedSecret The hash of the secret decided by the maker
/// @param _cancelFeeAmount The number of tokens to be paid to the operator as the cancellation fee
function cancelSwap(
address[4] calldata _addresses,
uint256[4] calldata _values,
bytes32 _hashedSecret,
uint256 _cancelFeeAmount
)
external
nonReentrant
{
// Error code 26: cancelSwap, expiry time has not been reached
require(_values[1] <= now, "26");
bytes32 swapHash = _hashSwap(_addresses, _values, _hashedSecret);
// Error code 27: cancelSwap, swap is not active
require(atomicSwaps[swapHash], "27");
uint256 cancelFeeAmount = _cancelFeeAmount;
if (!adminAddresses[msg.sender]) { cancelFeeAmount = _values[2]; }
// cancelFeeAmount <= feeAmount
// Error code 28: cancelSwap, cancelFeeAmount exceeds swap.feeAmount
require(cancelFeeAmount <= _values[2], "28");
uint256 refundAmount = _values[0];
if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId
refundAmount = refundAmount.sub(cancelFeeAmount);
}
delete atomicSwaps[swapHash];
_increaseBalance(
_addresses[0], // maker
_addresses[2], // assetId
refundAmount,
REASON_SWAP_CANCEL_RECEIVE,
_values[3] // nonce
);
_increaseBalance(
operator,
_addresses[3], // feeAssetId
cancelFeeAmount,
REASON_SWAP_CANCEL_FEE_RECEIVE,
_values[3] // nonce
);
if (_addresses[3] != _addresses[2]) { // feeAssetId != assetId
uint256 refundFeeAmount = _values[2].sub(cancelFeeAmount);
_increaseBalance(
_addresses[0], // maker
_addresses[3], // feeAssetId
refundFeeAmount,
REASON_SWAP_CANCEL_FEE_REFUND,
_values[3] // nonce
);
}
}
/// @dev Cache whether offer nonces are taken in the offer's nonce space
/// @param _values The _values param from the trade / networkTrade method
function _cacheOfferNonceStates(uint256[] memory _values) private view {
uint256 i = 1;
// i + numOffers * 2
uint256 end = i + (_values[0] & mask8) * 2;
// loop offers
for(i; i < end; i += 2) {
// Error code 38: Invalid nonce space
require(((_values[i] & mask128) >> 120) == 0, "38");
uint256 nonce = (_values[i] & mask120) >> 56;
if (_nonceTaken(nonce)) {
_values[i] = _values[i] | (uint256(1) << 120);
}
}
}
/// @dev Reduce available offer amounts of offers and store the remaining
/// offer amount in the `offers` mapping.
/// Offer nonces will also be marked as taken.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
/// @param _hashes An array of offer hash keys
function _storeOfferData(
uint256[] memory _values,
bytes32[] memory _hashes
)
private
{
// takenAmounts with same size as numOffers
uint256[] memory takenAmounts = new uint256[](_values[0] & mask8);
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 takeAmount = _values[i] >> 128;
takenAmounts[offerIndex] = takenAmounts[offerIndex].add(takeAmount);
}
i = 0;
end = _values[0] & mask8; // numOffers
// loop offers
for (i; i < end; i++) {
// we can use the cached nonce taken value here because offers have been
// validated to be unique
bool existingOffer = ((_values[i * 2 + 1] & mask128) >> 120) == 1;
bytes32 hashKey = _hashes[i * 2];
uint256 availableAmount = existingOffer ? offers[hashKey] : (_values[i * 2 + 2] & mask128);
// Error code 31: _storeOfferData, offer's available amount is zero
require(availableAmount > 0, "31");
uint256 remainingAmount = availableAmount.sub(takenAmounts[i]);
if (remainingAmount > 0) { offers[hashKey] = remainingAmount; }
if (existingOffer && remainingAmount == 0) { delete offers[hashKey]; }
if (!existingOffer) {
uint256 nonce = (_values[i * 2 + 1] & mask120) >> 56;
_markNonce(nonce);
}
}
}
/// @dev Mark all fill nonces as taken in the `usedNonces` mapping.
/// This also validates fill uniquness within the set of fills in `_values`,
/// since fill nonces are marked one at a time with validation that the
/// nonce to be marked has not been marked before.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _storeFillNonces(uint256[] memory _values) private {
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
// i + numFills * 2
uint256 end = i + ((_values[0] & mask16) >> 8) * 2;
// loop fills
for(i; i < end; i += 2) {
uint256 nonce = (_values[i] & mask120) >> 56;
_markNonce(nonce);
}
}
/// @dev The actual cancellation logic shared by `cancel`, `adminCancel`,
/// `slowCancel`.
/// The remaining offer amount is refunded back to the offer's maker, and
/// the specified cancellation fee will be deducted from the maker's balances.
function _cancel(
address _maker,
bytes32 _offerHash,
uint256 _expectedAvailableAmount,
address _offerAssetId,
uint256 _offerNonce,
address _cancelFeeAssetId,
uint256 _cancelFeeAmount
)
private
{
uint256 refundAmount = offers[_offerHash];
// Error code 32: _cancel, there is no offer amount left to cancel
require(refundAmount > 0, "32");
// Error code 33: _cancel, the remaining offer amount does not match
// the expectedAvailableAmount
require(refundAmount == _expectedAvailableAmount, "33");
delete offers[_offerHash];
if (_cancelFeeAssetId == _offerAssetId) {
refundAmount = refundAmount.sub(_cancelFeeAmount);
} else {
_decreaseBalance(
_maker,
_cancelFeeAssetId,
_cancelFeeAmount,
REASON_CANCEL_FEE_GIVE,
_offerNonce
);
}
_increaseBalance(
_maker,
_offerAssetId,
refundAmount,
REASON_CANCEL,
_offerNonce
);
_increaseBalance(
operator,
_cancelFeeAssetId,
_cancelFeeAmount,
REASON_CANCEL_FEE_RECEIVE,
_offerNonce // offer nonce
);
}
/// @dev The actual withdrawal logic shared by `withdraw`, `adminWithdraw`,
/// `slowWithdraw`. The specified amount is deducted from the `_withdrawer`'s
/// contract balance and transferred to the external `_receivingAddress`,
/// and the specified withdrawal fee will be deducted from the `_withdrawer`'s
/// balance.
function _withdraw(
address _withdrawer,
address payable _receivingAddress,
address _assetId,
uint256 _amount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _nonce
)
private
{
// Error code 34: _withdraw, invalid withdrawal amount
require(_amount > 0, "34");
_validateAddress(_receivingAddress);
_decreaseBalance(
_withdrawer,
_assetId,
_amount,
REASON_WITHDRAW,
_nonce
);
_increaseBalance(
operator,
_feeAssetId,
_feeAmount,
REASON_WITHDRAW_FEE_RECEIVE,
_nonce
);
uint256 withdrawAmount;
if (_feeAssetId == _assetId) {
withdrawAmount = _amount.sub(_feeAmount);
} else {
_decreaseBalance(
_withdrawer,
_feeAssetId,
_feeAmount,
REASON_WITHDRAW_FEE_GIVE,
_nonce
);
withdrawAmount = _amount;
}
if (_assetId == ETHER_ADDR) {
_receivingAddress.transfer(withdrawAmount);
return;
}
Utils.transferTokensOut(
_receivingAddress,
_assetId,
withdrawAmount
);
}
/// @dev Creates a hash key for a swap using the swap's parameters
/// @param _addresses[0] Address of the user making the swap
/// @param _addresses[1] Address of the user taking the swap
/// @param _addresses[2] Contract address of the asset to swap
/// @param _addresses[3] Contract address of the fee asset
/// @param _values[0] The number of tokens to be transferred
/// @param _values[1] The time in epoch seconds after which the swap will become cancellable
/// @param _values[2] The number of tokens to pay as fees to the operator
/// @param _values[3] The swap nonce to prevent replay attacks
/// @param _hashedSecret The hash of the secret decided by the maker
/// @return The hash key of the swap
function _hashSwap(
address[4] memory _addresses,
uint256[4] memory _values,
bytes32 _hashedSecret
)
private
pure
returns (bytes32)
{
return keccak256(abi.encode(
SWAP_TYPEHASH,
_addresses[0], // maker
_addresses[1], // taker
_addresses[2], // assetId
_values[0], // amount
_hashedSecret, // hashedSecret
_values[1], // expiryTime
_addresses[3], // feeAssetId
_values[2], // feeAmount
_values[3] // nonce
));
}
/// @dev Checks if the `_nonce` had been previously taken.
/// To reduce gas costs, a single `usedNonces` value is used to
/// store the state of 256 nonces, using the formula:
/// nonceTaken = "usedNonces[_nonce / 256] bit (_nonce % 256)" != 0
/// For example:
/// nonce 0 taken: "usedNonces[0] bit 0" != 0 (0 / 256 = 0, 0 % 256 = 0)
/// nonce 1 taken: "usedNonces[0] bit 1" != 0 (1 / 256 = 0, 1 % 256 = 1)
/// nonce 2 taken: "usedNonces[0] bit 2" != 0 (2 / 256 = 0, 2 % 256 = 2)
/// nonce 255 taken: "usedNonces[0] bit 255" != 0 (255 / 256 = 0, 255 % 256 = 255)
/// nonce 256 taken: "usedNonces[1] bit 0" != 0 (256 / 256 = 1, 256 % 256 = 0)
/// nonce 257 taken: "usedNonces[1] bit 1" != 0 (257 / 256 = 1, 257 % 256 = 1)
/// @param _nonce The nonce to check
/// @return Whether the nonce has been taken
function _nonceTaken(uint256 _nonce) private view returns (bool) {
uint256 slotData = _nonce.div(256);
uint256 shiftedBit = uint256(1) << _nonce.mod(256);
uint256 bits = usedNonces[slotData];
// The check is for "!= 0" instead of "== 1" because the shiftedBit is
// not at the zero'th position, so it would require an additional
// shift to compare it with "== 1"
return bits & shiftedBit != 0;
}
/// @dev Sets the corresponding `_nonce` bit to 1.
/// An error will be raised if the corresponding `_nonce` bit was
/// previously set to 1.
/// See `_nonceTaken` for details on calculating the corresponding `_nonce` bit.
/// @param _nonce The nonce to mark
function _markNonce(uint256 _nonce) private {
// Error code 35: _markNonce, nonce cannot be zero
require(_nonce != 0, "35");
uint256 slotData = _nonce.div(256);
uint256 shiftedBit = 1 << _nonce.mod(256);
uint256 bits = usedNonces[slotData];
// Error code 36: _markNonce, nonce has already been marked
require(bits & shiftedBit == 0, "36");
usedNonces[slotData] = bits | shiftedBit;
}
/// @dev Validates that the specified `_hash` was signed by the specified `_user`.
/// This method supports the EIP712 specification, the older Ethereum
/// signed message specification is also supported for backwards compatibility.
/// @param _hash The original hash that was signed by the user
/// @param _user The user who signed the hash
/// @param _v The `v` component of the `_user`'s signature
/// @param _r The `r` component of the `_user`'s signature
/// @param _s The `s` component of the `_user`'s signature
/// @param _prefixed If true, the signature will be verified
/// against the Ethereum signed message specification instead of the
/// EIP712 specification
function _validateSignature(
bytes32 _hash,
address _user,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool _prefixed
)
private
pure
{
Utils.validateSignature(
_hash,
_user,
_v,
_r,
_s,
_prefixed
);
}
/// @dev A utility method to increase the balance of a user.
/// A corressponding `BalanceIncrease` event will also be emitted.
/// @param _user The address to increase balance for
/// @param _assetId The asset's contract address
/// @param _amount The number of tokens to increase the balance by
/// @param _reasonCode The reason code for the `BalanceIncrease` event
/// @param _nonce The nonce for the `BalanceIncrease` event
function _increaseBalance(
address _user,
address _assetId,
uint256 _amount,
uint256 _reasonCode,
uint256 _nonce
)
private
{
if (_amount == 0) { return; }
balances[_user][_assetId] = balances[_user][_assetId].add(_amount);
emit BalanceIncrease(
_user,
_assetId,
_amount,
_reasonCode,
_nonce
);
}
/// @dev A utility method to decrease the balance of a user.
/// A corressponding `BalanceDecrease` event will also be emitted.
/// @param _user The address to decrease balance for
/// @param _assetId The asset's contract address
/// @param _amount The number of tokens to decrease the balance by
/// @param _reasonCode The reason code for the `BalanceDecrease` event
/// @param _nonce The nonce for the `BalanceDecrease` event
function _decreaseBalance(
address _user,
address _assetId,
uint256 _amount,
uint256 _reasonCode,
uint256 _nonce
)
private
{
if (_amount == 0) { return; }
balances[_user][_assetId] = balances[_user][_assetId].sub(_amount);
emit BalanceDecrease(
_user,
_assetId,
_amount,
_reasonCode,
_nonce
);
}
/// @dev Ensures that `_address` is not the zero address
/// @param _address The address to check
function _validateAddress(address _address) private pure {
Utils.validateAddress(_address);
}
/// @dev A utility method to increase balances of multiple addresses.
/// A corressponding `Increment` event will also be emitted.
/// @param _increments An array of amounts to increase a user's balance by,
/// the corresponding user and assetId is referenced by
/// _addresses[index * 2] and _addresses[index * 2 + 1] respectively
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
/// @param _static Indicates if the amount was pre-calculated or only known
/// at the time the transaction was executed
function _incrementBalances(
uint256[] memory _increments,
address[] memory _addresses,
uint256 _static
)
private
{
uint256 end = _increments.length;
for(uint256 i = 0; i < end; i++) {
uint256 increment = _increments[i];
if (increment == 0) { continue; }
balances[_addresses[i * 2]][_addresses[i * 2 + 1]] =
balances[_addresses[i * 2]][_addresses[i * 2 + 1]].add(increment);
emit Increment((i << 248) | (_static << 240) | increment);
}
}
/// @dev A utility method to decrease balances of multiple addresses.
/// A corressponding `Decrement` event will also be emitted.
/// @param _decrements An array of amounts to decrease a user's balance by,
/// the corresponding user and assetId is referenced by
/// _addresses[index * 2] and _addresses[index * 2 + 1] respectively
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
function _decrementBalances(
uint256[] memory _decrements,
address[] memory _addresses
)
private
{
uint256 end = _decrements.length;
for(uint256 i = 0; i < end; i++) {
uint256 decrement = _decrements[i];
if (decrement == 0) { continue; }
balances[_addresses[i * 2]][_addresses[i * 2 + 1]] =
balances[_addresses[i * 2]][_addresses[i * 2 + 1]].sub(decrement);
emit Decrement(i << 248 | decrement);
}
}
} | Deposits ERC223 tokens under the `_user`'s balance ERC223 tokens should invoke this method when tokens are sent to the Broker contract. The invocation will fail unless the token has been previously whitelisted through the `whitelistToken` method. _user The address of the user sending the tokens _amount The amount of tokens transferred to the Broker | function tokenFallback(
address _user,
uint _amount,
bytes calldata /* _data */
)
external
onlyActiveState
nonReentrant
{
address assetId = msg.sender;
tokenList.validateToken(assetId);
_increaseBalance(_user, assetId, _amount, REASON_DEPOSIT, 0);
emit TokenFallback(_user, assetId, _amount);
}
| 13,110,315 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10;
// solhint-disable no-inline-assembly
/// @title Unstructured Storage
/// @author Pavle Batuta <[email protected]>
/// @notice Read and write raw data to/from contract storage.
/// @dev Warning; this may override existing state variables!
library UnstructuredStorage {
/// @notice Read a bool value from a given position in storage
/// @param position The position to read from
/// @return data The value read
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly {
data := sload(position)
}
}
/// @notice Read an address value from a given position in storage
/// @param position The position to read from
/// @return data The value read
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly {
data := sload(position)
}
}
/// @notice Read a bytes32 value from a given position in storage
/// @param position The position to read from
/// @return data The value read
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly {
data := sload(position)
}
}
/// @notice Read an uint256 value from a given position in storage
/// @param position The position to read from
/// @return data The value read
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly {
data := sload(position)
}
}
/// @notice Write a bool value to a given position in storage
/// @dev Warning: may overrite existing state vaiables!
/// @param position The position to write to
/// @param data The data to write
function setStorageBool(bytes32 position, bool data) internal {
assembly {
sstore(position, data)
}
}
/// @notice Write an address value to a given position in storage
/// @dev Warning: may overrite existing state vaiables!
/// @param position The position to write to
/// @param data The data to write
function setStorageAddress(bytes32 position, address data) internal {
assembly {
sstore(position, data)
}
}
/// @notice Write a bytes32 value to a given position in storage
/// @dev Warning: may overrite existing state vaiables!
/// @param position The position to write to
/// @param data The data to write
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly {
sstore(position, data)
}
}
/// @notice Write a uin value to a given position in storage
/// @dev Warning: may overrite existing state vaiables!
/// @param position The position to write to
/// @param data The data to write
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly {
sstore(position, data)
}
}
}
| Write a bool value to a given position in storage Warning: may overrite existing state vaiables! position The position to write to data The data to write | function setStorageBool(bytes32 position, bool data) internal {
assembly {
sstore(position, data)
}
}
| 12,906,906 |
pragma solidity ^0.5.13;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "solidity-bytes-utils/contracts/BytesLib.sol";
import "./interfaces/ICeloVersionedContract.sol";
import "./interfaces/IMetaTransactionWalletDeployer.sol";
import "./proxies/MetaTransactionWalletProxy.sol";
import "./ExternalCall.sol";
import "./Initializable.sol";
import "./MetaTransactionWallet.sol";
contract MetaTransactionWalletDeployer is
IMetaTransactionWalletDeployer,
ICeloVersionedContract,
Initializable,
Ownable
{
using SafeMath for uint256;
using BytesLib for bytes;
mapping(address => address) public wallets;
mapping(address => bool) public canDeploy;
event WalletDeployed(address indexed owner, address indexed wallet, address implementation);
event DeployerStatusGranted(address indexed addr);
event DeployerStatusRevoked(address indexed addr);
/**
* @dev Verifies that the sender is allowed to deploy a wallet
*/
modifier onlyCanDeploy() {
require(msg.sender == owner() || canDeploy[msg.sender], "sender not allowed to deploy wallet");
_;
}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return The storage, major, minor, and patch version of the contract.
*/
function getVersionNumber() public pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 0, 0);
}
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param initialDeployers a list of addresses that are allowed to deploy wallets
*/
function initialize(address[] calldata initialDeployers) external initializer {
_transferOwnership(msg.sender);
for (uint256 i = 0; i < initialDeployers.length; i++) {
_changeDeployerPermission(initialDeployers[i], true);
}
}
/**
* @notice Change the permission of an address to deploy
* @param target The address to be allowed as a deployer
* @param allowedToDeploy toggle whether the address is allowed or not
*/
function changeDeployerPermission(address target, bool allowedToDeploy) external onlyOwner {
_changeDeployerPermission(target, allowedToDeploy);
}
/**
* @notice Implementation of permission change
* @param target The address to be allowed as a deployer
* @param allowedToDeploy toggle whether the address is allowed or not
*/
function _changeDeployerPermission(address target, bool allowedToDeploy) internal {
canDeploy[target] = allowedToDeploy;
if (allowedToDeploy) {
emit DeployerStatusGranted(target);
} else {
emit DeployerStatusRevoked(target);
}
}
/**
* @notice Used to deploy a MetaTransactionWalletProxy, set the implementation,
* initialize, transfer ownership and emit an event.
* @param owner The external account which will act as signer and owner of the proxy
* @param implementation The address of the implementation which the proxy will point to
* @param initCallData calldata pointing to a method on implementation used to initialize
*/
function deploy(address owner, address implementation, bytes calldata initCallData)
external
onlyCanDeploy
{
require(wallets[owner] == address(0), "wallet already deployed");
MetaTransactionWalletProxy proxy = new MetaTransactionWalletProxy();
proxy._setAndInitializeImplementation(implementation, initCallData);
proxy._transferOwnership(owner);
wallets[owner] = address(proxy);
emit WalletDeployed(owner, address(proxy), implementation);
}
}
| Used to deploy a MetaTransactionWalletProxy, set the implementation, initialize, transfer ownership and emit an event. owner The external account which will act as signer and owner of the proxy implementation The address of the implementation which the proxy will point to initCallData calldata pointing to a method on implementation used to initialize/ | function deploy(address owner, address implementation, bytes calldata initCallData)
external
onlyCanDeploy
{
require(wallets[owner] == address(0), "wallet already deployed");
MetaTransactionWalletProxy proxy = new MetaTransactionWalletProxy();
proxy._setAndInitializeImplementation(implementation, initCallData);
proxy._transferOwnership(owner);
wallets[owner] = address(proxy);
emit WalletDeployed(owner, address(proxy), implementation);
}
| 908,671 |
./full_match/80001/0x03bf32e3Dc308FE7554E5dD801387f282eC5BE45/sources/contracts/CyberMarketplace2.sol | idToMarketItem[itemId].seller.transfer(msg.value); payable(idToMarketItem[itemId].owner).transfer(price); | function createMarketSale(
address nftContract,
uint256 itemId
) public payable nonReentrant {
uint price = idToMarketItem[itemId].price;
uint tokenId = idToMarketItem[itemId].tokenId;
require(
msg.value == price,
"Please submit the asking price in order to complete the purchase"
);
require(
erc20.balanceOf(msg.sender) >= msg.value,
"Not enough ERC-20 tokens"
);
erc20.transferFrom(msg.sender, idToMarketItem[itemId].owner, price);
IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);
idToMarketItem[itemId].owner = payable(msg.sender);
_itemsSold.increment();
}
| 5,605,810 |
// SPDX-License-Identifier: MIT
/*
* JuiceBox.sol
*
* Created: October 27, 2021
*
* Price: FREE
* Rinkeby: 0x09494437a042494eAdA9801A85eE494cFB27D75b
* Mainnet:
*
* Description: An ERC-721 token that will be claimable by anyone who owns 'the Plug'
*
* - There will be 4 variations, each with a different rarity (based on how likely it is
* to receive, i.e. v1:60%, v2:20%, v3:15%, v4:5%)
* - Owners with multiple Plugs will benefit through a distribution scheme that shifts
* the probability of minting each variation towards 25%
*/
pragma solidity >=0.5.16 <0.9.0;
import "./Kasbeer721.sol";
//@title Juice Box
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract JuiceBox is Kasbeer721 {
// -------------
// EVENTS & VARS
// -------------
event JuiceBoxMinted(uint256 indexed a);
event JuiceBoxBurned(uint256 indexed a);
//@dev This is how we'll keep track of who has already minted a JuiceBox
mapping (address => bool) internal _boxHolders;
//@dev Keep track of which token ID is associated with which hash
mapping (uint256 => string) internal _tokenToHash;
//@dev Initial production hashes
string [NUM_ASSETS] boxHashes = ["QmbZH1NZLvUTqeaHXH37fVnb7QHcCFDsn4QKvicM1bmn5j",
"QmVXiZFCwxBiJQJCpiSCKz8TkaWmnEBpT6stmxYqRK4FeY",
"Qmds7Ag48sfeodwmtWmTokFGZoHiGZXYN2YbojtjTR7GhR",
"QmeUPdEvAU5sSEv1Nwixbu1oxkSFCY194m8Drm9u3rtVWg"];
//cherry, berry, kiwi, lemon
//@dev Associated weights of probability for hashes
uint16 [NUM_ASSETS] boxWeights = [60, 23, 15, 2];//cherry, berry, kiwi, lemon
//@dev Secret word to prevent etherscan claims
string private _secret;
constructor(string memory secret) Kasbeer721("Juice Box", "") {
_whitelistActive = true;
_secret = secret;
_contractUri = "ipfs://QmdafigFsnSjondbSFKWhV2zbCf8qF5xEkgNoCYcnanhD6";
payoutAddress = 0x6b8C6E15818C74895c31A1C91390b3d42B336799;//logik
}
// -----------
// RESTRICTORS
// -----------
modifier boxAvailable()
{
require(getCurrentId() < MAX_NUM_TOKENS, "JuiceBox: no JuiceBox's left to mint");
_;
}
modifier tokenExists(uint256 tokenId)
{
require(_exists(tokenId), "JuiceBox: nonexistent token");
_;
}
// ---------------
// JUICE BOX MAGIC
// ---------------
//@dev Override 'tokenURI' to account for asset/hash cycling
function tokenURI(uint256 tokenId)
public view virtual override tokenExists(tokenId)
returns (string memory)
{
return string(abi.encodePacked(_baseURI(), _tokenToHash[tokenId]));
}
//@dev Get the secret word
function _getSecret() private view returns (string memory)
{
return _secret;
}
//// ----------------------
//// IPFS HASH MANIPULATION
//// ----------------------
//@dev Get the hash stored at `idx`
function getHashByIndex(uint8 idx) public view hashIndexInRange(idx)
returns (string memory)
{
return boxHashes[idx];
}
//@dev Allows us to update the IPFS hash values (one at a time)
// 0:cherry, 1:berry, 2:kiwi, 3:lemon
function updateHashForIndex(uint8 idx, string memory str)
public isSquad hashIndexInRange(idx)
{
boxHashes[idx] = str;
}
// ------------------
// MINTING & CLAIMING
// ------------------
//@dev Allows owners to mint for free
function mint(address to) public virtual override isSquad boxAvailable
returns (uint256 tid)
{
tid = _mintInternal(to);
_assignHash(tid, 1);
}
//@dev Mint a specific juice box (owners only)
function mintWithHash(address to, string memory hash) public isSquad returns (uint256 tid)
{
tid = _mintInternal(to);
_tokenToHash[tid] = hash;
}
//@dev Claim a JuiceBox if you're a Plug holder
function claim(address to, uint8 numPlugs, string memory secret) public
boxAvailable whitelistEnabled onlyWhitelist(to) saleActive
returns (uint256 tid, string memory hash)
{
require(!_boxHolders[to], "JuiceBox: cannot claim more than 1");
require(!_isContract(to), "JuiceBox: silly rabbit :P");
require(_stringsEqual(secret, _getSecret()), "JuiceBox: silly rabbit :P");
tid = _mintInternal(to);
hash = _assignHash(tid, numPlugs);
}
//@dev Mints a single Juice Box & updates `_boxHolders` accordingly
function _mintInternal(address to) internal virtual returns (uint256 newId)
{
_incrementTokenId();
newId = getCurrentId();
_safeMint(to, newId);
_markAsClaimed(to);
emit JuiceBoxMinted(newId);
}
//@dev Based on the number of Plugs owned by the sender, randomly select
// a JuiceBox hash that will be associated with their token id
function _assignHash(uint256 tid, uint8 numPlugs) private tokenExists(tid)
returns (string memory hash)
{
uint8[] memory weights = new uint8[](NUM_ASSETS);
//calculate new weights based on `numPlugs`
if (numPlugs > 15) numPlugs = 15;
weights[0] = uint8(boxWeights[0] - 35*((numPlugs-1)/10));//cherry: 60% -> 25%
weights[1] = uint8(boxWeights[1] + 2*((numPlugs-1)/10));//berry: 23% -> 25%
weights[2] = uint8(boxWeights[2] + 10*((numPlugs-1)/10));//kiwi: 15% -> 25%
weights[3] = uint8(boxWeights[3] + 23*((numPlugs-1)/10));//lemon: 2% -> 25%
uint16 rnd = random() % 100;//should be b/n 0 & 100
//randomly select a juice box hash
uint8 i;
for (i = 0; i < NUM_ASSETS; i++) {
if (rnd < weights[i]) {
hash = boxHashes[i];
break;
}
rnd -= weights[i];
}
//assign the selected hash to this token id
_tokenToHash[tid] = hash;
}
//@dev Update `_boxHolders` so that `a` cannot claim another juice box
function _markAsClaimed(address a) private
{
_boxHolders[a] = true;
}
function getHashForTid(uint256 tid) public view tokenExists(tid)
returns (string memory)
{
return _tokenToHash[tid];
}
//@dev Pseudo-random number generator
function random() public view returns (uint16 rnd)
{
return uint16(uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, boxWeights))));
}
}
// SPDX-License-Identifier: MIT
/*
* Kasbeer721.sol
*
* Created: October 27, 2021
*
* Tuned-up ERC721 that covers a multitude of features that are generally useful
* so that it can be easily extended for quick customization .
*/
pragma solidity >=0.5.16 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./access/Whitelistable.sol";
import "./access/Pausable.sol";
import "./utils/LibPart.sol";
//@title Kasbeer721 - Beefed up ERC721
//@author Jack Kasbeer (git:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract Kasbeer721 is ERC721, Whitelistable, Pausable {
using SafeMath for uint256;
using Counters for Counters.Counter;
// -------------
// EVENTS & VARS
// -------------
event Kasbeer721Minted(uint256 indexed tokenId);
event Kasbeer721Burned(uint256 indexed tokenId);
//@dev Token incrementing
Counters.Counter internal _tokenIds;
//@dev Important numbers
uint constant NUM_ASSETS = 4;//4 juice box variations
uint constant MAX_NUM_TOKENS = 111;
//@dev Properties
string internal _contractUri;
address public payoutAddress;
//@dev These are needed for contract compatability
uint256 constant public royaltyFeeBps = 1000; // 10%
bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 internal constant _INTERFACE_ID_EIP2981 = 0x2a55205a;
bytes4 internal constant _INTERFACE_ID_ROYALTIES = 0xcad96cca;
constructor(string memory temp_name, string memory temp_symbol)
ERC721(temp_name, temp_symbol) {}
// ---------
// MODIFIERS
// ---------
modifier hashIndexInRange(uint8 idx)
{
require(0 <= idx && idx < NUM_ASSETS, "Kasbeer721: index OOB");
_;
}
modifier onlyValidTokenId(uint256 tokenId)
{
require(1 <= tokenId && tokenId <= MAX_NUM_TOKENS, "Kasbeer721: tokenId OOB");
_;
}
// ----------
// MAIN LOGIC
// ----------
//@dev All of the asset's will be pinned to IPFS
function _baseURI()
internal view virtual override returns (string memory)
{
return "ipfs://";
}
//@dev This is here as a reminder to override for custom transfer functionality
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal virtual override
{
super._beforeTokenTransfer(from, to, tokenId);
}
//@dev Allows owners to mint for free
function mint(address to) public virtual isSquad returns (uint256)
{
_tokenIds.increment();
uint256 newId = _tokenIds.current();
_safeMint(to, newId);
emit Kasbeer721Minted(newId);
return newId;
}
//@dev Custom burn function - nothing special
function burn(uint256 tokenId) public virtual
{
require(
isInSquad(_msgSender()) ||
_msgSender() == ownerOf(tokenId),
"Kasbeer721: not owner or in squad."
);
_burn(tokenId);
emit Kasbeer721Burned(tokenId);
}
//// --------
//// CONTRACT
//// --------
//@dev Controls the contract-level metadata to include things like royalties
function contractURI() public view returns(string memory)
{
return _contractUri;
}
//@dev Ability to change the contract URI
function updateContractUri(string memory updatedContractUri) public isSquad
{
_contractUri = updatedContractUri;
}
//@dev Allows us to withdraw funds collected
function withdraw(address payable wallet, uint256 amount) public isSquad
{
require(amount <= address(this).balance,
"Kasbeer721: Insufficient funds to withdraw");
wallet.transfer(amount);
}
//@dev Destroy contract and reclaim leftover funds
function kill() public onlyOwner
{
selfdestruct(payable(_msgSender()));
}
// -------
// HELPERS
// -------
//@dev Returns the current token id (number minted so far)
function getCurrentId() public view returns (uint256)
{
return _tokenIds.current();
}
//@dev Increments `_tokenIds` by 1
function _incrementTokenId() internal
{
_tokenIds.increment();
}
//@dev Determine if two strings are equal using the length + hash method
function _stringsEqual(string memory a, string memory b)
internal pure returns (bool)
{
bytes memory A = bytes(a);
bytes memory B = bytes(b);
if (A.length != B.length) {
return false;
} else {
return keccak256(A) == keccak256(B);
}
}
//@dev Determine if an address is a smart contract
function _isContract(address a) internal view returns (bool)
{
uint32 size;
assembly {
size := extcodesize(a)
}
return size > 0;
}
// -----------------
// SECONDARY MARKETS
// -----------------
//@dev Rarible Royalties V2
function getRaribleV2Royalties(uint256 id)
onlyValidTokenId(id) external view returns (LibPart.Part[] memory)
{
LibPart.Part[] memory royalties = new LibPart.Part[](1);
royalties[0] = LibPart.Part({
account: payable(payoutAddress),
value: uint96(royaltyFeeBps)
});
return royalties;
}
//@dev EIP-2981
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view onlyValidTokenId(tokenId) returns (address receiver, uint256 amount) {
uint256 ourCut = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000);
return (payoutAddress, ourCut);
}
// -----------------
// INTERFACE SUPPORT
// -----------------
//@dev Confirm that this contract is compatible w/ these interfaces
function supportsInterface(bytes4 interfaceId)
public view virtual override returns (bool)
{
return interfaceId == _INTERFACE_ID_ERC165
|| interfaceId == _INTERFACE_ID_ROYALTIES
|| interfaceId == _INTERFACE_ID_ERC721
|| interfaceId == _INTERFACE_ID_ERC721_METADATA
|| interfaceId == _INTERFACE_ID_ERC721_ENUMERABLE
|| interfaceId == _INTERFACE_ID_EIP2981
|| super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
/*
* Whitelistable.sol
*
* Created: December 21, 2021
*
* Provides functionality for a "whitelist"/"guestlist" for inheriting contracts.
*/
pragma solidity >=0.5.16 <0.9.0;
import "./SquadOwnable.sol";
//@title Whitelistable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract Whitelistable is SquadOwnable {
// -------------
// EVENTS & VARS
// -------------
event WhitelistActivated(address indexed a);
event WhitelistDeactivated(address indexed a);
//@dev Whitelist mapping for client addresses
mapping (address => bool) internal _whitelist;
//@dev Whitelist flag for active/inactive states
bool internal _whitelistActive;
constructor() {
_whitelistActive = false;
//add myself and then logik (client)
_whitelist[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true;
_whitelist[0x6b8C6E15818C74895c31A1C91390b3d42B336799] = true;
}
// ---------
// MODIFIERS
// ---------
//@dev Determine if someone is in the whitelsit
modifier onlyWhitelist(address a)
{
require(isWhitelisted(a), "Whitelistable: must be on whitelist");
_;
}
//@dev Prevent non-whitelist minting functions from being used
modifier whitelistDisabled()
{
require(_whitelistActive == false, "Whitelistable: whitelist still active");
_;
}
//@dev Require that the whitelist is currently enabled
modifier whitelistEnabled()
{
require(_whitelistActive == true, "Whitelistable: whitelist not active");
_;
}
// ----------
// MAIN LOGIC
// ----------
//@dev Toggle the state of the whitelist (on/off)
function toggleWhitelist() public isSquad
{
_whitelistActive = !_whitelistActive;
if (_whitelistActive) {
emit WhitelistActivated(_msgSender());
} else {
emit WhitelistDeactivated(_msgSender());
}
}
//@dev Determine if `a` is in the `_whitelist
function isWhitelisted(address a) public view returns (bool)
{
return _whitelist[a];
}
//// ----------
//// ADD/REMOVE
//// ----------
//@dev Add a single address to whitelist
function addToWhitelist(address a) public isSquad
{
require(!isWhitelisted(a), "Whitelistable: already whitelisted");
_whitelist[a] = true;
}
//@dev Remove a single address from the whitelist
function removeFromWhitelist(address a) public isSquad
{
require(isWhitelisted(a), "Whitelistable: not in whitelist");
_whitelist[a] = false;
}
//@dev Add a list of addresses to the whitelist
function bulkAddToWhitelist(address[] memory addresses) public isSquad
{
uint addrLen = addresses.length;
require(addrLen > 1, "Whitelistable: use `addToWhitelist` instead");
require(addrLen < 65536, "Whitelistable: cannot add more than 65535 at once");
uint16 i;
for (i = 0; i < addrLen; i++) {
if (!isWhitelisted(addresses[i])) {
_whitelist[addresses[i]] = true;
}
}
}
}
// SPDX-License-Identifier: MIT
/*
* Pausable.sol
*
* Created: December 21, 2021
*
* Provides functionality for pausing and unpausing the sale (or other functionality)
*/
pragma solidity >=0.5.16 <0.9.0;
import "./SquadOwnable.sol";
//@title Pausable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract Pausable is SquadOwnable {
// -------------
// EVENTS & VARS
// -------------
event Paused(address indexed a);
event Unpaused(address indexed a);
bool private _paused;
constructor() {
_paused = false;
}
// ---------
// MODIFIERS
// ---------
//@dev This will require the sale to be unpaused
modifier saleActive()
{
require(!_paused, "Pausable: sale paused.");
_;
}
// ----------
// MAIN LOGIC
// ----------
//@dev Pause or unpause minting
function toggleSaleActive() public isSquad
{
_paused = !_paused;
if (_paused) {
emit Paused(_msgSender());
} else {
emit Unpaused(_msgSender());
}
}
//@dev Determine if the sale is currently paused
function paused() public view virtual returns (bool)
{
return _paused;
}
}
// SPDX-License-Identifier: MIT
/*
* LibPart.sol
*
* Author: Jack Kasbeer (taken from 'dot')
* Created: October 20, 2021
*/
pragma solidity >=0.5.16 <0.9.0;
//@dev We need this libary for Rarible
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
/*
* SquadOwnable.sol
*
* Created: December 21, 2021
*
* An extension of `Ownable.sol` to accomodate for a potential list of owners.
* NOTE: this will need to be the last inherited contract to give all parents
* access to the modifiers it provides
*/
pragma solidity >=0.5.16 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
//@title SquadOwnable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract SquadOwnable is Ownable {
//@dev Ownership - list of squad members (owners)
mapping (address => bool) internal _squad;
constructor() {
//add myself and then logik (client)
_squad[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true;
_squad[0x6b8C6E15818C74895c31A1C91390b3d42B336799] = true;
}
//@dev Custom modifier for multiple owners
modifier isSquad()
{
require(isInSquad(_msgSender()), "SquadOwnable: Caller not part of squad.");
_;
}
//@dev Determine if address `a` is an approved owner
function isInSquad(address a) public view returns (bool)
{
return _squad[a];
}
//@dev Add `a` to the squad
function addToSquad(address a) public onlyOwner
{
require(!isInSquad(a), "SquadOwnable: Address already in squad.");
_squad[a] = true;
}
//@dev Remove `a` from the squad
function removeFromSquad(address a) public onlyOwner
{
require(isInSquad(a), "SquadOwnable: Address already not in squad.");
_squad[a] = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | Claim a JuiceBox if you're a Plug holder | function claim(address to, uint8 numPlugs, string memory secret) public
boxAvailable whitelistEnabled onlyWhitelist(to) saleActive
returns (uint256 tid, string memory hash)
{
require(!_boxHolders[to], "JuiceBox: cannot claim more than 1");
require(!_isContract(to), "JuiceBox: silly rabbit :P");
require(_stringsEqual(secret, _getSecret()), "JuiceBox: silly rabbit :P");
tid = _mintInternal(to);
hash = _assignHash(tid, numPlugs);
}
| 6,132,902 |
/**
*Submitted for verification at BscScan.com on 2022-01-28
*/
/**
*Submitted for verification at snowtrace.io on 2022-01-28
*/
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.2;
interface ISushiswapV2Pair {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathSushiswap {
function add(uint x, uint y) internal pure returns (uint z) {
unchecked {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
}
function sub(uint x, uint y) internal pure returns (uint z) {
unchecked {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
}
function mul(uint x, uint y) internal pure returns (uint z) {
unchecked {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
}
library SushiswapV2Library {
using SafeMathSushiswap for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'SushiswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'SushiswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint160(uint256(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
)))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = ISushiswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'SushiswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'SushiswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'SushiswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SushiswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SushiswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// helper methods for interacting with ERC20 tokens and sending NATIVE that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferNative(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: NATIVE_TRANSFER_FAILED');
}
}
interface IwNATIVE {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
interface AnyswapV1ERC20 {
function mint(address to, uint256 amount) external returns (bool);
function burn(address from, uint256 amount) external returns (bool);
function setMinter(address _auth) external;
function applyMinter() external;
function revokeMinter(address _auth) external;
function changeVault(address newVault) external returns (bool);
function depositVault(uint amount, address to) external returns (uint);
function withdrawVault(address from, uint amount, address to) external returns (uint);
function underlying() external view returns (address);
function deposit(uint amount, address to) external returns (uint);
function withdraw(uint amount, address to) external returns (uint);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
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 AnyswapV6Router {
using SafeERC20 for IERC20;
using SafeMathSushiswap for uint;
address public immutable factory;
address public immutable wNATIVE;
bool public enableSwapTrade;
modifier swapTradeEnabled() {
require(enableSwapTrade, 'AnyswapV6Router: SwapTrade disabled');
_;
}
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'AnyswapV3Router: EXPIRED');
_;
}
constructor(address _factory, address _wNATIVE, address _mpc) {
_newMPC = _mpc;
_newMPCEffectiveTime = block.timestamp;
factory = _factory;
wNATIVE = _wNATIVE;
}
receive() external payable {
assert(msg.sender == wNATIVE); // only accept Native via fallback from the wNative contract
}
address private _oldMPC;
address private _newMPC;
uint256 private _newMPCEffectiveTime;
event LogChangeMPC(address indexed oldMPC, address indexed newMPC, uint indexed effectiveTime, uint chainID);
event LogChangeRouter(address indexed oldRouter, address indexed newRouter, uint chainID);
event LogAnySwapIn(bytes32 indexed txhash, address indexed token, address indexed to, uint amount, uint fromChainID, uint toChainID);
event LogAnySwapOut(address indexed token, address indexed from, address indexed to, uint amount, uint fromChainID, uint toChainID);
event LogAnySwapOut(address indexed token, address indexed from, string to, uint amount, uint fromChainID, uint toChainID);
event LogAnySwapTradeTokensForTokens(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID);
event LogAnySwapTradeTokensForNative(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID);
modifier onlyMPC() {
require(msg.sender == mpc(), "AnyswapV3Router: FORBIDDEN");
_;
}
function mpc() public view returns (address) {
if (block.timestamp >= _newMPCEffectiveTime) {
return _newMPC;
}
return _oldMPC;
}
function cID() public view returns (uint id) {
assembly {id := chainid()}
}
function setEnableSwapTrade(bool enable) external onlyMPC {
enableSwapTrade = enable;
}
function changeMPC(address newMPC) public onlyMPC returns (bool) {
require(newMPC != address(0), "AnyswapV3Router: address(0x0)");
_oldMPC = mpc();
_newMPC = newMPC;
_newMPCEffectiveTime = block.timestamp + 2*24*3600;
emit LogChangeMPC(_oldMPC, _newMPC, _newMPCEffectiveTime, cID());
return true;
}
function changeVault(address token, address newVault) public onlyMPC returns (bool) {
require(newVault != address(0), "AnyswapV3Router: address(0x0)");
return AnyswapV1ERC20(token).changeVault(newVault);
}
function setMinter(address token, address _auth) external onlyMPC {
return AnyswapV1ERC20(token).setMinter(_auth);
}
function applyMinter(address token) external onlyMPC {
return AnyswapV1ERC20(token).applyMinter();
}
function revokeMinter(address token, address _auth) external onlyMPC {
return AnyswapV1ERC20(token).revokeMinter(_auth);
}
function _anySwapOut(address from, address token, address to, uint amount, uint toChainID) internal {
AnyswapV1ERC20(token).burn(from, amount);
emit LogAnySwapOut(token, from, to, amount, cID(), toChainID);
}
// Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to`
function anySwapOut(address token, address to, uint amount, uint toChainID) external {
_anySwapOut(msg.sender, token, to, amount, toChainID);
}
// Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to` by minting with `underlying`
function anySwapOutUnderlying(address token, address to, uint amount, uint toChainID) external {
IERC20(AnyswapV1ERC20(token).underlying()).safeTransferFrom(msg.sender, token, amount);
emit LogAnySwapOut(token, msg.sender, to, amount, cID(), toChainID);
}
function anySwapOutNative(address token, address to, uint toChainID) external payable {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
IwNATIVE(wNATIVE).deposit{value: msg.value}();
assert(IwNATIVE(wNATIVE).transfer(token, msg.value));
emit LogAnySwapOut(token, msg.sender, to, msg.value, cID(), toChainID);
}
function anySwapOut(address[] calldata tokens, address[] calldata to, uint[] calldata amounts, uint[] calldata toChainIDs) external {
for (uint i = 0; i < tokens.length; i++) {
_anySwapOut(msg.sender, tokens[i], to[i], amounts[i], toChainIDs[i]);
}
}
function anySwapOut(address token, string memory to, uint amount, uint toChainID) external {
AnyswapV1ERC20(token).burn(msg.sender, amount);
emit LogAnySwapOut(token, msg.sender, to, amount, cID(), toChainID);
}
function anySwapOutUnderlying(address token, string memory to, uint amount, uint toChainID) external {
IERC20(AnyswapV1ERC20(token).underlying()).safeTransferFrom(msg.sender, token, amount);
emit LogAnySwapOut(token, msg.sender, to, amount, cID(), toChainID);
}
function anySwapOutNative(address token, string memory to, uint toChainID) external payable {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
IwNATIVE(wNATIVE).deposit{value: msg.value}();
assert(IwNATIVE(wNATIVE).transfer(token, msg.value));
emit LogAnySwapOut(token, msg.sender, to, msg.value, cID(), toChainID);
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID
function _anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) internal {
AnyswapV1ERC20(token).mint(to, amount);
emit LogAnySwapIn(txs, token, to, amount, fromChainID, cID());
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID
// triggered by `anySwapOut`
function anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC {
_anySwapIn(txs, token, to, amount, fromChainID);
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying`
function anySwapInUnderlying(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC {
_anySwapIn(txs, token, to, amount, fromChainID);
AnyswapV1ERC20(token).withdrawVault(to, amount, to);
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying` if possible
function anySwapInAuto(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC {
_anySwapIn(txs, token, to, amount, fromChainID);
AnyswapV1ERC20 _anyToken = AnyswapV1ERC20(token);
address _underlying = _anyToken.underlying();
if (_underlying != address(0) && IERC20(_underlying).balanceOf(token) >= amount) {
if (_underlying == wNATIVE) {
_anyToken.withdrawVault(to, amount, address(this));
IwNATIVE(wNATIVE).withdraw(amount);
TransferHelper.safeTransferNative(to, amount);
} else {
_anyToken.withdrawVault(to, amount, to);
}
}
}
function depositNative(address token, address to) external payable returns (uint) {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
IwNATIVE(wNATIVE).deposit{value: msg.value}();
assert(IwNATIVE(wNATIVE).transfer(token, msg.value));
AnyswapV1ERC20(token).depositVault(msg.value, to);
return msg.value;
}
function withdrawNative(address token, uint amount, address to) external returns (uint) {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
AnyswapV1ERC20(token).withdrawVault(msg.sender, amount, address(this));
IwNATIVE(wNATIVE).withdraw(amount);
TransferHelper.safeTransferNative(to, amount);
return amount;
}
// extracts mpc fee from bridge fees
function anySwapFeeTo(address token, uint amount) external onlyMPC {
address _mpc = mpc();
AnyswapV1ERC20(token).mint(_mpc, amount);
AnyswapV1ERC20(token).withdrawVault(_mpc, amount, _mpc);
}
function anySwapIn(bytes32[] calldata txs, address[] calldata tokens, address[] calldata to, uint256[] calldata amounts, uint[] calldata fromChainIDs) external onlyMPC {
for (uint i = 0; i < tokens.length; i++) {
_anySwapIn(txs[i], tokens[i], to[i], amounts[i], fromChainIDs[i]);
}
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = SushiswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? SushiswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
ISushiswapV2Pair(SushiswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual swapTradeEnabled ensure(deadline) {
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokensUnderlying(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual swapTradeEnabled ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).safeTransferFrom(msg.sender, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender);
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain
// Triggered by `anySwapOutExactTokensForTokens`
function anySwapInExactTokensForTokens(
bytes32 txs,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint fromChainID
) external onlyMPC virtual swapTradeEnabled ensure(deadline) returns (uint[] memory amounts) {
amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'SushiswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
_anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID);
_swap(amounts, path, to);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNative(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual swapTradeEnabled ensure(deadline) {
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNativeUnderlying(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual swapTradeEnabled ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).safeTransferFrom(msg.sender, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender);
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain
// Triggered by `anySwapOutExactTokensForNative`
function anySwapInExactTokensForNative(
bytes32 txs,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint fromChainID
) external onlyMPC virtual swapTradeEnabled ensure(deadline) returns (uint[] memory amounts) {
require(path[path.length - 1] == wNATIVE, 'AnyswapV3Router: INVALID_PATH');
amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'AnyswapV3Router: INSUFFICIENT_OUTPUT_AMOUNT');
_anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID);
_swap(amounts, path, address(this));
IwNATIVE(wNATIVE).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferNative(to, amounts[amounts.length - 1]);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual returns (uint amountB) {
return SushiswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
returns (uint amountOut)
{
return SushiswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
returns (uint amountIn)
{
return SushiswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
returns (uint[] memory amounts)
{
return SushiswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
returns (uint[] memory amounts)
{
return SushiswapV2Library.getAmountsIn(factory, amountOut, path);
}
} | sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` | function anySwapOutExactTokensForNative(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual swapTradeEnabled ensure(deadline) {
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
| 5,721,188 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/GSN/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;
}
}
/**
* @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/IERC721.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;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.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);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
string constant private ERR = "Address";
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, ERR);
(bool success, ) = recipient.call{ value: amount }('');
require(success, ERR);
}
/**
* @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, ERR);
}
/**
* @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,
ERR
);
}
/**
* @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 && isContract(target),
ERR
);
(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, ERR);
}
/**
* @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), ERR);
(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), ERR);
(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);
}
}
}
}
/**
* @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/Strings.sol
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = '0123456789abcdef';
string private constant ERR = "Strings";
/**
* @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, ERR);
return string(buffer);
}
}
/**
* @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;
string private constant ERR = "Ownable";
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(), ERR);
_;
}
/**
* @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), ERR);
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.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, Ownable, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private constant ERR = "ERC721";
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Mint pause control
uint256 public mintPaused = 1;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function _initialize(string memory name_, string memory symbol_) internal {
_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), ERR);
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), ERR);
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), ERR);
bytes memory bytesURI = bytes(_baseURI);
if (bytesURI.length == 0 || bytesURI[bytesURI.length - 1] == '/')
return string(abi.encodePacked(_baseURI, tokenId.toString(), ".json"));
else return _baseURI;
}
function setBaseURI(string memory newBaseURI) external onlyOwner {
_baseURI = newBaseURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, ERR);
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
ERR
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(_exists(tokenId), ERR);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
ERR
);
_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),
ERR
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Admin pause / unpause minting
*/
function setMintPaused(uint256 paused) external onlyOwner {
mintPaused = paused;
}
/**
* @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),
ERR
);
}
/**
* @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), ERR);
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),
ERR
);
}
/**
* @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) && !_exists(tokenId), ERR);
_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);
// 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(
to != address(0) && ERC721.ownerOf(tokenId) == from,
ERR
);
// 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 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, ERR);
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
}
/**
* @dev OpenSea proxy registry to prevent gas spend for approvals
*/
contract ProxyRegistry {
mapping(address => address) public proxies;
}
/**
* @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;
string private constant ERR = "Reentrancy";
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, ERR);
// 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;
}
}
/**
* @dev Implementation of Base ERC721 contract
*/
contract ERC721Base is ERC721, ReentrancyGuard {
// OpenSea proxy registry
address private immutable _osProxyRegistryAddress;
// Address allowed to initialize contract
address private immutable _initializer;
// Max mints per transaction
uint256 private _maxTxMint;
// The CAP of mintable tokenIds
uint256 private _cap;
// ETH price of one tokenIds
uint256 private _tokenPrice;
// TokenId counter, 1 minted in ctor
uint256 private _currentTokenId;
string private constant ERR = "ERC721Base";
// Fired when funds are distributed
event Distributed(address indexed receiver, uint256 amount);
/**
* @dev Initialization.
*/
constructor(address initializer_, address osProxyRegistry_) {
_osProxyRegistryAddress = osProxyRegistry_;
_initializer = initializer_;
}
/**
* @dev Clone Initialization.
*/
function initialize(
address owner_,
string memory name_,
string memory symbol_,
uint256 cap_,
uint256 maxPerTx_,
uint256 price_) external
{
require(msg.sender == _initializer, ERR);
_transferOwnership(owner_);
ERC721._initialize(name_, symbol_);
_cap = cap_;
_maxTxMint = maxPerTx_;
_tokenPrice = price_;
// Mint our first token
_mint(owner_, 0);
_currentTokenId = 1;
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(_osProxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* @dev Distribute mint
*/
function mint(address to, uint256 numMint) external payable nonReentrant {
require(mintPaused == 0 &&
numMint > 0 &&
numMint <= _maxTxMint &&
_currentTokenId + numMint <= _cap &&
msg.value >= numMint * _tokenPrice, ERR);
for (uint256 i = 0; i < numMint; ++i)
_mint(to, _currentTokenId + i);
_currentTokenId += numMint;
uint256 dust = msg.value - (numMint * _tokenPrice);
if (dust > 0) payable(msg.sender).transfer(dust);
}
/**
* @dev Distribute rewards
*/
function distribute(
address[] calldata accounts,
uint256[] calldata refunds,
uint256[] calldata percents
) external onlyOwner {
require(
(refunds.length == 0 || refunds.length == accounts.length) &&
(percents.length == 0 || percents.length == accounts.length),
ERR
);
uint256 availableAmount = address(this).balance;
uint256[] memory amounts = new uint256[](accounts.length);
for (uint256 i = 0; i < refunds.length; ++i) {
require(refunds[i] <= availableAmount, ERR);
amounts[i] = refunds[i];
availableAmount -= refunds[i];
}
uint256 amountToShare = availableAmount;
for (uint256 i = 0; i < percents.length; ++i) {
uint256 amount = (amountToShare * percents[i]) / 100;
amounts[i] += (amount <= availableAmount) ? amount : availableAmount;
availableAmount -= amount;
}
for (uint256 i = 0; i < accounts.length; ++i) {
if (amounts[i] > 0) {
payable(accounts[i]).transfer(amounts[i]);
emit Distributed(accounts[i], amounts[i]);
}
}
}
/**
* @dev return number of minted token
*/
function totalSupply() external view returns (uint256) {
return _currentTokenId;
}
/**
* @dev we don't allow ether receive()
*/
receive() external payable {
revert('Not allowed');
}
} | 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, ERR);
return string(buffer);
}
| 613,846 |
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity ^0.4.0;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
library oraclizeLib {
uint constant internal day = 60*60*24;
uint constant internal week = 60*60*24*7;
uint constant internal month = 60*60*24*30;
byte constant internal proofType_NONE = 0x00;
byte constant internal proofType_TLSNotary = 0x10;
byte constant internal proofStorage_IPFS = 0x01;
// *******TRUFFLE + BRIDGE*********
//OraclizeAddrResolverI constant public OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
// *****REALNET DEPLOYMENT******
OraclizeAddrResolverI constant public OAR = oraclize_setNetwork(); // constant means dont store and re-eval on each call
OraclizeI constant public oraclize = OraclizeI(OAR.getAddress());
/*function oraclize()
private
returns (OraclizeI oraclize) {
oraclize = OraclizeI(OAR.getAddress());
}*/
// should work but isnt w truffle + testrpc
function oraclize_setNetwork()
public
returns(OraclizeAddrResolverI){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
return OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
return OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
return OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
return OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
return OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
return OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
return OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
}
}
function useCoupon(string code)
public {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource)
public
returns (uint){
return oraclize.getPrice(datasource);
}
function getOAR()
public constant
returns (address) {
return address(OAR);
}
function getCON()
public constant
returns (OraclizeI) {
return OraclizeI(OAR.getAddress());
}
function oraclize_getPrice(string datasource, uint gaslimit)
public
returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg)
public returns (bytes32 id){
return oraclize_query(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg)
public returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(string datasource, string arg, uint gaslimit)
public returns (bytes32 id){
return oraclize_query(0, datasource, arg, gaslimit);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit)
public returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2)
public returns (bytes32 id){
return oraclize_query(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2)
public returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit)
public returns (bytes32 id){
return oraclize_query(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit)
public returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN)
internal returns (bytes32 id){
return oraclize_query(0, datasource, argN);
}
function oraclize_query(uint timestamp, string datasource, string[] argN)
internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit)
internal returns (bytes32 id){
return oraclize_query(0, datasource, argN, gaslimit);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit)
internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_cbAddress()
public
constant
returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP)
public {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice)
public {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config)
public {
return oraclize.setConfig(config);
}
function getCodeSize(address _addr)
public
returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a)
public
returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b)
public
returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle)
public
returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e)
internal
returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d)
internal
returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c)
internal
returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b)
internal
returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a)
public constant
returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b)
public constant
returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i)
internal
returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr)
internal
returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function b2s(bytes _b)
internal
returns (string) {
bytes memory output = new bytes(_b.length * 2);
uint len = output.length;
assembly {
let i := 0
let mem := 0
loop:
// isolate octet
0x1000000000000000000000000000000000000000000000000000000000000000
exp(0x10, mod(i, 0x40))
// change offset only if needed
jumpi(skip, gt(mod(i, 0x40), 0))
// save offset mem for reuse
mem := mload(add(_b, add(mul(0x20, div(i, 0x40)), 0x20)))
skip:
mem
mul
div
dup1
// check if alpha or numerical, jump if numerical
0x0a
swap1
lt
num
jumpi
// offset alpha char correctly
0x0a
swap1
sub
alp:
0x61
add
jump(end)
num:
0x30
add
end:
add(output, add(0x20, i))
mstore8
i := add(i, 1)
jumpi(loop, gt(len, i))
}
return string(output);
}
}
// </ORACLIZE_API>
| should work but isnt w truffle + testrpc | function oraclize_setNetwork()
public
returns(OraclizeAddrResolverI){
return OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
}
return OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
| 2,547,972 |
./partial_match/1/0x9E25121dd5df2f26EAE8125c48AF835E4aeFb1e3/sources/FeeProvider.sol | calculates the origination fee for every loan executed on the platform. _user can be used in the future to apply discount to the origination fee based on the _user account (eg. stake Populous tokens in the lending pool, or deposit > 1M USD etc.) _amount the amount of the loan/ | function calculateLoanOriginationFee(address _user, uint256 _amount) external view returns (uint256) {
return _amount.wadMul(originationFeePercentage);
}
| 3,953,867 |
./full_match/5/0xC766Ff6854008270D768195Cb93b7D7452B01f63/sources/project_/contracts/FeralfileArtworkV3.sol | createArtworks use for create list of artworks in a transaction artworks_ - the array of artwork | function createArtworks(Artwork[] memory artworks_)
external
onlyAuthorized
{
for (uint256 i = 0; i < artworks_.length; i++) {
_createArtwork(
artworks_[i].fingerprint,
artworks_[i].title,
artworks_[i].artistName,
artworks_[i].editionSize,
artworks_[i].AEAmount,
artworks_[i].PPAmount
);
}
}
| 7,047,831 |
./full_match/1/0x4BE3AD153F4C6b10F098e4270E77a434234C5493/sources/src/contracts-nft/consortium-key.sol | Returns the current amount of NFTs minted in total. | function totalMinted() public view returns (uint256) {
return totalMintedCounter.current();
}
| 16,461,253 |
// SPDX-License-Identifier: MIT
/**
* @authors: [@jaybuidl, @shalzz, @hrishibhat, @shotaronowhere]
* @reviewers: []
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity ^0.8.0;
import "./SafeBridgeReceiverOnEthereum.sol";
import "./interfaces/IFastBridgeReceiver.sol";
/**
* Fast Bridge Receiver on Ethereum from Arbitrum
* Counterpart of `FastBridgeSenderToEthereum`
*/
contract FastBridgeReceiverOnEthereum is SafeBridgeReceiverOnEthereum, IFastBridgeReceiver {
// ************************************* //
// * Enums / Structs * //
// ************************************* //
struct Claim {
bytes32 messageHash;
address bridger;
uint256 claimedAt;
uint256 claimDeposit;
bool verified;
}
struct Challenge {
address challenger;
uint256 challengedAt;
uint256 challengeDeposit;
}
struct Ticket {
Claim claim;
Challenge challenge;
bool relayed;
}
// ************************************* //
// * Storage * //
// ************************************* //
uint256 public constant ONE_BASIS_POINT = 1e4; // One basis point, for scaling.
uint256 public override claimDeposit; // The deposit required to submit a claim.
uint256 public override challengeDeposit; // The deposit required to submit a challenge.
uint256 public override challengeDuration; // The duration of the period allowing to challenge a claim.
uint256 public override alpha; // Basis point of claim or challenge deposit that are lost when dishonest.
mapping(uint256 => Ticket) public tickets; // The tickets by ticketID.
/**
* @dev Constructor.
* @param _governor The governor's address.
* @param _safeBridgeSender The address of the Safe Bridge sender on Arbitrum.
* @param _inbox The address of the Arbitrum Inbox contract.
* @param _claimDeposit The deposit amount to submit a claim in wei.
* @param _challengeDeposit The deposit amount to submit a challenge in wei.
* @param _challengeDuration The duration of the period allowing to challenge a claim.
* @param _alpha Basis point of claim or challenge deposit that are lost when dishonest.
*/
constructor(
address _governor,
address _safeBridgeSender,
address _inbox,
uint256 _claimDeposit,
uint256 _challengeDeposit,
uint256 _challengeDuration,
uint256 _alpha
) SafeBridgeReceiverOnEthereum(_governor, _safeBridgeSender, _inbox) {
claimDeposit = _claimDeposit;
challengeDeposit = _challengeDeposit;
challengeDuration = _challengeDuration;
alpha = _alpha;
}
// ************************************* //
// * State Modifiers * //
// ************************************* //
/**
* @dev Submit a claim about the `messageHash` for a particular Fast Bridge `ticketID` and submit a deposit. The `messageHash` should match the one on the sending side otherwise the sender will lose his deposit.
* @param _ticketID The ticket identifier referring to a message going through the bridge.
* @param _messageHash The hash claimed for the ticket.
*/
function claim(uint256 _ticketID, bytes32 _messageHash) external payable override {
Ticket storage ticket = tickets[_ticketID];
require(ticket.claim.bridger == address(0), "Claim already made");
require(ticket.relayed == false, "Claim already relayed"); // already relayed via verifyAndRelaySafe() without claim.
require(msg.value >= claimDeposit, "Not enough claim deposit");
ticket.claim = Claim({
messageHash: _messageHash,
bridger: msg.sender,
claimedAt: block.timestamp,
claimDeposit: msg.value,
verified: false
});
emit ClaimReceived(_ticketID, _messageHash, block.timestamp);
}
/**
* @dev Submit a challenge for a particular Fast Bridge `ticketID` and submit a deposit. The `messageHash` in the claim already made for this `ticketID` should be different from the one on the sending side, otherwise the sender will lose his deposit.
* @param _ticketID The ticket identifier referring to a message going through the bridge.
*/
function challenge(uint256 _ticketID) external payable override {
Ticket storage ticket = tickets[_ticketID];
require(ticket.claim.bridger != address(0), "Claim does not exist");
require(block.timestamp - ticket.claim.claimedAt < challengeDuration, "Challenge period over");
require(ticket.challenge.challenger == address(0), "Claim already challenged");
require(msg.value >= challengeDeposit, "Not enough challenge deposit");
ticket.challenge = Challenge({
challenger: msg.sender,
challengedAt: block.timestamp,
challengeDeposit: msg.value
});
emit ClaimChallenged(_ticketID, block.timestamp);
}
/**
* @dev Relay the message for this `ticketID` if the challenge period has passed and the claim is unchallenged. The hash computed over `messageData` and the other parameters must match the hash provided by the claim.
* @param _ticketID The ticket identifier referring to a message going through the bridge.
* @param _blockNumber The block number on the cross-domain chain when the message with this ticketID has been sent.
* @param _messageData The data on the cross-domain chain for the message sent with this ticketID.
*/
function verifyAndRelay(
uint256 _ticketID,
uint256 _blockNumber,
bytes calldata _messageData
) external override {
Ticket storage ticket = tickets[_ticketID];
require(ticket.claim.bridger != address(0), "Claim does not exist");
require(
ticket.claim.messageHash == keccak256(abi.encode(_ticketID, _blockNumber, _messageData)),
"Invalid hash"
);
require(ticket.claim.claimedAt + challengeDuration < block.timestamp, "Challenge period not over");
require(ticket.challenge.challenger == address(0), "Claim is challenged");
require(ticket.relayed == false, "Message already relayed");
ticket.claim.verified = true;
ticket.relayed = true;
require(_relay(_messageData), "Failed to call contract"); // Checks-Effects-Interaction
}
/**
* Note: Access restricted to the Safe Bridge.
* @dev Relay the message for this `ticketID` as provided by the Safe Bridge. Resolve a challenged claim for this `ticketID` if any.
* @param _ticketID The ticket identifier referring to a message going through the bridge.
* @param _blockNumber The block number on the cross-domain chain when the message with this ticketID has been sent.
* @param _messageData The data on the cross-domain chain for the message sent with this ticketID.
*/
function verifyAndRelaySafe(
uint256 _ticketID,
uint256 _blockNumber,
bytes calldata _messageData
) external override {
require(isSentBySafeBridge(), "Access not allowed: SafeBridgeSender only.");
Ticket storage ticket = tickets[_ticketID];
require(ticket.relayed == false, "Message already relayed");
// Claim assessment if any
bytes32 messageHash = keccak256(abi.encode(_ticketID, _blockNumber, _messageData));
if (ticket.claim.bridger != address(0) && ticket.claim.messageHash == messageHash) {
ticket.claim.verified = true;
}
ticket.relayed = true;
require(_relay(_messageData), "Failed to call contract"); // Checks-Effects-Interaction
}
/**
* @dev Sends the deposit back to the Bridger if his claim is not successfully challenged. Includes a portion of the Challenger's deposit if unsuccessfully challenged.
* @param _ticketID The ticket identifier referring to a message going through the bridge.
*/
function withdrawClaimDeposit(uint256 _ticketID) external override {
Ticket storage ticket = tickets[_ticketID];
require(ticket.relayed == true, "Message not relayed yet");
require(ticket.claim.bridger != address(0), "Claim does not exist");
require(ticket.claim.verified == true, "Claim not verified: deposit forfeited");
uint256 amount = ticket.claim.claimDeposit + (ticket.challenge.challengeDeposit * alpha) / ONE_BASIS_POINT;
ticket.claim.claimDeposit = 0;
ticket.challenge.challengeDeposit = 0;
payable(ticket.claim.bridger).send(amount); // Use of send to prevent reverting fallback. User is responsibility for accepting ETH.
// Checks-Effects-Interaction
}
/**
* @dev Sends the deposit back to the Challenger if his challenge is successful. Includes a portion of the Bridger's deposit.
* @param _ticketID The ticket identifier referring to a message going through the bridge.
*/
function withdrawChallengeDeposit(uint256 _ticketID) external override {
Ticket storage ticket = tickets[_ticketID];
require(ticket.relayed == true, "Message not relayed");
require(ticket.challenge.challenger != address(0), "Challenge does not exist");
require(ticket.claim.verified == false, "Claim verified: deposit forfeited");
uint256 amount = ticket.challenge.challengeDeposit + (ticket.claim.claimDeposit * alpha) / ONE_BASIS_POINT;
ticket.claim.claimDeposit = 0;
ticket.challenge.challengeDeposit = 0;
payable(ticket.challenge.challenger).send(amount); // Use of send to prevent reverting fallback. User is responsibility for accepting ETH.
// Checks-Effects-Interaction
}
// ************************************* //
// * Public Views * //
// ************************************* //
/**
* @dev Returns the `start` and `end` time of challenge period for this `ticketID`.
* @return start The start time of the challenge period.
* @return end The end time of the challenge period.
*/
function challengePeriod(uint256 _ticketID) external view override returns (uint256 start, uint256 end) {
Ticket storage ticket = tickets[_ticketID];
require(ticket.claim.bridger != address(0), "Claim does not exist");
start = ticket.claim.claimedAt;
end = start + challengeDuration;
return (start, end);
}
// ************************ //
// * Governance * //
// ************************ //
function changeClaimDeposit(uint256 _claimDeposit) external onlyByGovernor {
claimDeposit = _claimDeposit;
}
function changeChallengeDeposit(uint256 _challengeDeposit) external onlyByGovernor {
challengeDeposit = _challengeDeposit;
}
function changeChallengePeriodDuration(uint256 _challengeDuration) external onlyByGovernor {
challengeDuration = _challengeDuration;
}
function changeAlpha(uint256 _alpha) external onlyByGovernor {
alpha = _alpha;
}
// ************************ //
// * Internal * //
// ************************ //
function _relay(bytes calldata _messageData) internal returns (bool success) {
// Decode the receiver address from the data encoded by the IFastBridgeSender
(address receiver, bytes memory data) = abi.decode(_messageData, (address, bytes));
(success, ) = address(receiver).call(data);
}
}
| Relay the message for this `ticketID` if the challenge period has passed and the claim is unchallenged. The hash computed over `messageData` and the other parameters must match the hash provided by the claim. _ticketID The ticket identifier referring to a message going through the bridge. _blockNumber The block number on the cross-domain chain when the message with this ticketID has been sent. _messageData The data on the cross-domain chain for the message sent with this ticketID./ | function verifyAndRelay(
uint256 _ticketID,
uint256 _blockNumber,
bytes calldata _messageData
) external override {
Ticket storage ticket = tickets[_ticketID];
require(ticket.claim.bridger != address(0), "Claim does not exist");
require(
ticket.claim.messageHash == keccak256(abi.encode(_ticketID, _blockNumber, _messageData)),
"Invalid hash"
);
require(ticket.claim.claimedAt + challengeDuration < block.timestamp, "Challenge period not over");
require(ticket.challenge.challenger == address(0), "Claim is challenged");
require(ticket.relayed == false, "Message already relayed");
ticket.claim.verified = true;
ticket.relayed = true;
}
| 14,107,406 |
pragma solidity 0.4.24;
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 AltcoinToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract ERC20Basic {
uint256 public totalSupply;
function totalSupply() public constant returns (uint);
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract NafCoin is ERC20, Owned {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "NafCoin";
string public constant symbol = "NFC";
uint public constant decimals = 18;
uint256 public totalSupply = 1200000000000000000000000000;
uint256 public totalDistributed = 0;
uint256 public totalIcoDistributed = 0;
uint256 public constant minContribution = 1 ether / 100; // 0.01 Eth
uint256 public tokensPerEth = 0;
// ------------------------------
// Token Distribution and Address
// ------------------------------
// saleable 90%
uint256 public constant totalIco = 1080000000000000000000000000;
uint256 public totalIcoDist = 0;
address storageIco = owner;
// airdrop 5%
uint256 public constant totalAirdrop = 60000000000000000000000000;
address private storageAirdrop = 0x57D2EE2E359c08DfFeD715A0bd305FE513657822;
// developer 5%
uint256 public constant totalDeveloper = 60000000000000000000000000;
address private storageDeveloper = 0xdcc89F6793285C2cAcFb558B5bE840ec8149F47D;
// ---------------------
// sale start price and bonus
// ---------------------
// presale
uint public presaleStartTime = 1544979600; // Monday, 17 December 2018 00:00:00 GMT+07:00
uint256 public presalePerEth = 1366000000000000000000;
// ico
uint public icoStartTime = 1546189200; // Tuesday, 15 January 2019 00:00:00 GMT+07:00
uint256 public icoPerEth = 1366000000000000000000;
// ico1
uint public ico1StartTime = 1547398800; // Wednesday, 30 January 2019 00:00:00 GMT+07:00
uint256 public ico1PerEth = 1366000000000000000000;
// ico2
uint public ico2StartTime = 1548608400; // Wednesday, 13 February 2019 00:00:00 GMT+07:00
uint256 public ico2PerEth = 1366000000000000000000;
//ico start and end
uint public icoOpenTime = presaleStartTime;
uint public icoEndTime = 1549818000; // Thursday, 28 February 2019 00:00:00 GMT+07:00
// -----------------------
// events
// -----------------------
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
event Sent(address from, address to, uint amount);
// -------------------
// STATE
// ---------------------
bool public icoOpen = false;
bool public icoFinished = false;
bool public distributionFinished = false;
// -----
// temp
// -----
uint256 public tTokenPerEth = 0;
uint256 public tAmount = 0;
uint i = 0;
bool private tIcoOpen = false;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
balances[owner] = totalIco;
balances[storageAirdrop] = totalAirdrop;
balances[storageDeveloper] = totalDeveloper;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return totalSupply - balances[address(0)];
}
modifier canDistr() {
require(!distributionFinished);
_;
}
function startDistribution() onlyOwner canDistr public returns (bool) {
icoOpen = true;
presaleStartTime = now;
icoOpenTime = now;
return true;
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
icoFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
balances[owner] = balances[owner].sub(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function send(address receiver, uint amount) public {
if (balances[msg.sender] < amount) return;
balances[msg.sender] -= amount;
balances[receiver] += amount;
emit Sent(msg.sender, receiver, amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
//owner withdraw
if (msg.sender == owner && msg.value == 0){
withdraw();
}
if(msg.sender != owner){
if ( now < icoOpenTime ){
revert('ICO does not open yet');
}
//is Open
if ( ( now >= icoOpenTime ) && ( now <= icoEndTime ) ){
icoOpen = true;
}
if ( now > icoEndTime ){
icoOpen = false;
icoFinished = true;
distributionFinished = true;
}
if ( icoFinished == true ){
revert('ICO has finished');
}
if ( distributionFinished == true ){
revert('Token distribution has finished');
}
if ( icoOpen == true ){
if ( now >= presaleStartTime && now < icoStartTime){ tTokenPerEth = presalePerEth; }
if ( now >= icoStartTime && now < ico1StartTime){ tTokenPerEth = icoPerEth; }
if ( now >= ico1StartTime && now < ico2StartTime){ tTokenPerEth = ico1PerEth; }
if ( now >= ico2StartTime && now < icoEndTime){ tTokenPerEth = ico2PerEth; }
tokensPerEth = tTokenPerEth;
getTokens();
}
}
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
require( msg.value >= minContribution );
require( msg.value > 0 );
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if ( icoFinished == true ){
revert('ICO Has Finished');
}
if( balances[owner] < tokens ){
revert('Insufficient Token Balance or Sold Out.');
}
if (tokens < 0){
revert();
}
totalIcoDistributed += tokens;
if (tokens > 0) {
distr(investor, tokens);
}
if (totalIcoDistributed >= totalIco) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
// mitigates the ERC20 short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
// mitigates the ERC20 spend/approval race condition
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
AltcoinToken t = AltcoinToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function burn(uint256 _amount) onlyOwner public {
balances[owner] = balances[owner].sub(_amount);
totalSupply = totalSupply.sub(_amount);
totalDistributed = totalDistributed.sub(_amount);
emit Burn(owner, _amount);
}
function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) {
AltcoinToken token = AltcoinToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
function dist_privateSale(address _to, uint256 _amount) onlyOwner public {
require(_amount <= balances[owner]);
require(_amount > 0);
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
balances[owner] = balances[owner].sub(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
tAmount = 0;
}
function dist_airdrop(address _to, uint256 _amount) onlyOwner public {
require(_amount <= balances[storageAirdrop]);
require(_amount > 0);
balances[_to] = balances[_to].add(_amount);
balances[storageAirdrop] = balances[storageAirdrop].sub(_amount);
emit Airdrop(_to, _amount, balances[_to]);
emit Transfer(address(0), _to, _amount);
}
function dist_multiple_airdrop(address[] _participants, uint256 _amount) onlyOwner public {
tAmount = 0;
for ( i = 0; i < _participants.length; i++){
tAmount = tAmount.add(_amount);
}
require(tAmount <= balances[storageAirdrop]);
for ( i = 0; i < _participants.length; i++){
dist_airdrop(_participants[i], _amount);
}
tAmount = 0;
}
function dist_developer(address _to, uint256 _amount) onlyOwner public {
require(_amount <= balances[storageDeveloper]);
require(_amount > 0);
balances[_to] = balances[_to].add(_amount);
balances[storageDeveloper] = balances[storageDeveloper].sub(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
tAmount = 0;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | owner withdrawis Open | function () external payable {
if (msg.sender == owner && msg.value == 0){
withdraw();
}
if(msg.sender != owner){
if ( now < icoOpenTime ){
revert('ICO does not open yet');
}
if ( ( now >= icoOpenTime ) && ( now <= icoEndTime ) ){
icoOpen = true;
}
if ( now > icoEndTime ){
icoOpen = false;
icoFinished = true;
distributionFinished = true;
}
if ( icoFinished == true ){
revert('ICO has finished');
}
if ( distributionFinished == true ){
revert('Token distribution has finished');
}
if ( icoOpen == true ){
tokensPerEth = tTokenPerEth;
getTokens();
}
}
}
| 6,957,320 |
./full_match/4/0x6BE60E29FBb7559A5aF18D1e8F840767dd315359/sources/tellorcore/contracts/TellorGetters.sol | Checks for uint variables in the disputeUintVars mapping based on the disuputeId _disputeId is the dispute id; _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is the variables/strings used to save the data in the mapping. The variables names are commented out under the disputeUintVars under the Dispute struct return uint value for the bytes32 data submitted/ | function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256) {
return tellor.getDisputeUintVars(_disputeId, _data);
}
| 817,633 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: lifetimeapp.io && manifold.xyz
/**
* Simple EIP2981 reference override implementation
*/
interface IERC1155WithRoyalty {
function setTokenRoyalty(
uint256 tokenId,
address recipient,
uint16 bps
) external;
function setDefaultRoyalty(address recipient, uint16 bps) external;
}
| Simple EIP2981 reference override implementation/ | interface IERC1155WithRoyalty {
function setTokenRoyalty(
uint256 tokenId,
address recipient,
uint16 bps
) external;
function setDefaultRoyalty(address recipient, uint16 bps) external;
}
| 15,871,670 |
/**
* An example contract using the Sikorka API
*
* A shop owner wants to give some discount credit tokens to any users
* who go on location and interact with the contracts he/she has deployed.
*
* @author Lefteris Karapetsas
* @license BSD3
*/
pragma solidity ^0.4.1;
import "./sikorka_basic_interface.sol";
contract DiscountTokens is SikorkaBasicInterface {
mapping (address => uint256) public balances;
address[] participants;
uint tokens_to_reward;
uint public token_round_end;
/**
* Constructor
*
* @param _tokens_to_reward The number of tokens to reward to each
* user who succesfully interacts with
* the contract
* @param _round_duration The number of seconds this token round
* will last
*/
function DiscountTokens(
string _name,
uint _latitude,
uint _longtitude,
string _question,
bytes32 _answer_hash,
uint _tokens_to_reward,
uint _round_duration
) SikorkaBasicInterface(
_name,
_latitude,
_longtitude,
_question,
_answer_hash) {
tokens_to_reward = _tokens_to_reward;
token_round_end = now + _round_duration;
}
/**
* Claim discount tokens for the shop!
*
* @param _answer The answer to the challenge question.
*/
function claimToken(string _answer) need_pop(_answer) {
// User already got their discount tokens for this round
if (balances[msg.sender] != 0) {
return;
}
balances[msg.sender] += tokens_to_reward;
}
/**
* Clear out the tokens to allow for a new round of discounts
*
* @param _new_duration The new duration in seconds
*/
function clearTokens(uint _new_duration) only_owner {
for (uint i = 0; i < participants.length; i ++) {
balances[participants[i]] = 0;
}
delete participants;
}
}
| Clear out the tokens to allow for a new round of discounts _new_duration The new duration in seconds/ | function clearTokens(uint _new_duration) only_owner {
for (uint i = 0; i < participants.length; i ++) {
balances[participants[i]] = 0;
}
delete participants;
}
| 6,430,380 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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 Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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 () public {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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 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;
}
}
/*
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);
}
}
/// @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
);
}
/// @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);
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
/**
* @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_) public {
_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];
}
/**
* @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(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 Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
/// @title 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;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {
}
/// @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(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: 3000}("");
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);
}
}
}
contract Peacock is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private swapping;
address payable public devWallet;
PCOCKDividendTracker public dividendTracker;
uint256 public swapTokensAtAmount = 5 * 10**7 * (10**9); // 0.005%
uint256 public maxBuyAmount = 10**10 * (10**9); // 1%
uint256 public buyDelay = 45 seconds;
uint256 public constant ETHRewardsFee = 5;
uint256 public constant walletDevFee = 3;
uint256 public totalFees;
// use by default 300,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 400000;
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) private _isBlacklisted;
mapping (address => uint256) private _holderLastBuyTimestamp;
event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event BlacklistAccount(address indexed account, bool isBlacklisted);
event devWalletUpdated(address indexed newDevWallet, address indexed oldDevWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event SendDividends(
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor() public ERC20("Peacock", "PCOCK") {
totalFees = ETHRewardsFee.add(walletDevFee);
devWallet = payable(0xF48CDb934ca1b17046EBF0c008ef2363823205Bf);
dividendTracker = new PCOCKDividendTracker();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // uniswap router
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
// exclude from paying fees
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 10**12 * (10**9));
}
receive() external payable {}
function updateDividendTracker(address newAddress) external onlyOwner() {
require(newAddress != address(dividendTracker), "Peacock: The dividend tracker already has that address");
PCOCKDividendTracker newDividendTracker = PCOCKDividendTracker(payable(newAddress));
require(newDividendTracker.owner() == address(this), "Peacock: The new dividend tracker must be owned by the Peacock contract");
newDividendTracker.excludeFromDividends(address(newDividendTracker));
newDividendTracker.excludeFromDividends(address(this));
newDividendTracker.excludeFromDividends(owner());
newDividendTracker.excludeFromDividends(address(uniswapV2Router));
emit UpdateDividendTracker(newAddress, address(dividendTracker));
dividendTracker = newDividendTracker;
}
function updateUniswapV2Router(address newAddress) external onlyOwner() {
require(newAddress != address(uniswapV2Router), "Peacock: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function Batchtransfer(address[] calldata recipients, uint256 amount) public returns (bool) {
for (uint256 i = 0; i < recipients.length; i++) {
require(transfer(recipients[i], amount));
}
return true;
}
function blacklistAddress(address account) external onlyOwner(){
require(!_isBlacklisted[account], "Account is already blacklisted");
require(account != owner(), "Owner cannot be blacklisted");
_isBlacklisted[account] = true;
}
function removeBlacklist(address account) external onlyOwner() {
require(_isBlacklisted[account], "Account is not blacklisted");
_isBlacklisted[account] = false;
}
function excludeFromFees(address account, bool excluded) public onlyOwner() {
require(_isExcludedFromFees[account] != excluded, "Peacock: Account is already the value of 'excluded'");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setSwapTokensAtAmount(uint256 amountBeforeSwap) external onlyOwner() {
swapTokensAtAmount = amountBeforeSwap * (10**9);
}
function updateDevWallet(address payable newDevWallet) external onlyOwner() {
require(newDevWallet != devWallet, "Peacock: The liquidity wallet is already this address");
excludeFromFees(newDevWallet, true);
emit devWalletUpdated(newDevWallet, devWallet);
devWallet = newDevWallet;
}
function updateMaxBuyPercent(uint256 _maxBuyPercent) external onlyOwner() {
require(_maxBuyPercent <= 100, "Peacock: MaxBuyPercent cannot be more than 100");
maxBuyAmount = totalSupply().mul(_maxBuyPercent).div(100);
}
function updateBuyDelay(uint256 _buyDelayInSeconds) external onlyOwner() {
buyDelay = _buyDelayInSeconds;
}
function updateGasForProcessing(uint256 newValue) external onlyOwner() {
require(newValue >= 200000 && newValue <= 500000, "Peacock: gasForProcessing must be between 200,000 and 500,000");
require(newValue != gasForProcessing, "Peacock: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner() {
dividendTracker.updateClaimWait(claimWait);
}
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(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(!_isBlacklisted[from], "Peacock: Sender address is blacklisted");
require(from != address(0), "Peacock: transfer from the zero address");
require(to != address(0), "Peacock: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(from == uniswapV2Pair && !_isExcludedFromFees[to]) {
require(amount <= maxBuyAmount, "Cannot buy such a large amount of tokens");
require(_holderLastBuyTimestamp[to].add(buyDelay) <= block.timestamp, "Peacock: Must wait before buying");
_holderLastBuyTimestamp[to] = block.timestamp;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
!swapping &&
from != uniswapV2Pair &&
from != devWallet &&
to != devWallet
) {
swapping = true;
swapTokensForETH(swapTokensAtAmount);
uint256 contractETHBalance = address(this).balance;
uint256 WalletBB = contractETHBalance.mul(walletDevFee).div(totalFees);
uint256 ETHRewards = contractETHBalance.sub(WalletBB);
sendDividends(ETHRewards);
sendToDevWallet(WalletBB);
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
uint256 fees = amount.mul(totalFees).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(!swapping) {
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 sendToDevWallet(uint256 WalletBB) private {
devWallet.transfer(WalletBB);
}
function getBalace() external view returns(uint256) {
return balanceOf(address(this));
}
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 sendDividends(uint256 dividends) private {
(bool success,) = address(dividendTracker).call{value: dividends}("");
if(success) {
emit SendDividends(dividends);
}
}
// withdraw any ERC20 tokens sent here my mistake
function withdrawTokens(address _token) external onlyOwner() {
require(_token != address(this), "Cannot withdraw PCOCK");
uint256 amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).transfer(owner(), amount);
}
}
contract PCOCKDividendTracker 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 immutable minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() public DividendPayingToken("PCOCK_tracker", "PCOCK_tracker") {
claimWait = 1200;
minimumTokenBalanceForDividends = 10000 * (10**9); //must hold 10000+ tokens
}
function _transfer(address, address, uint256) internal override {
require(false, "PCOCK DividendTracker: No transfers allowed");
}
function withdrawDividend() public override {
require(false, "PCOCK DividendTracker: withdrawDividend disabled. Use the 'claim' function on the main PCOCK contract.");
}
function excludeFromDividends(address account) external onlyOwner() {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromDividends(account);
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner() {
require(newClaimWait >= 1200 && newClaimWait <= 7200, "claimWait must be updated to between 20 minutes and 2 hours");
require(newClaimWait != claimWait, "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 >= minimumTokenBalanceForDividends) {
_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;
}
} | generate the uniswap pair path of token -> weth make the swap | function swapTokensForETH(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
| 14,759,017 |
./partial_match/42/0xACa3ec7fC7c899095BAaFa78967df7988a629053/sources/PoolStake.sol | check whether the input locking term is one of the supported terms. ---------------------------------------------------------------------- _term --> the locking term. ------------------------------- returns whether true or not./ | function _isValidTerm(uint _term) internal view returns(bool) {
if (_term == period1
|| _term == period2
|| _term == period3
|| _term == period4
) return true;
else return false;
}
| 3,361,611 |
pragma solidity ^0.4.13;
//solc --bin --abi --optimize --optimize-runs 20000 -o . Testpool.sol
import "./Ethash.sol";
/**
* @title RLPReader
*
* RLPReader is used to read and parse RLP encoded data in memory.
*
* @author Andreas Olofsson ([email protected])
*
* code was taken from https://github.com/androlo/standard-contracts/blob/master/contracts/src/codec/RLP.sol
*
*/
library RLP {
uint constant DATA_SHORT_START = 0x80;
uint constant DATA_LONG_START = 0xB8;
uint constant LIST_SHORT_START = 0xC0;
uint constant LIST_LONG_START = 0xF8;
uint constant DATA_LONG_OFFSET = 0xB7;
uint constant LIST_LONG_OFFSET = 0xF7;
struct RLPItem {
uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes.
uint _unsafe_length; // Number of bytes. This is the full length of the string.
}
struct Iterator {
RLPItem _unsafe_item; // Item that's being iterated over.
uint _unsafe_nextPtr; // Position of the next item in the list.
}
/* Iterator */
function next(Iterator memory self) internal constant returns (RLPItem memory subItem) {
if(hasNext(self)) {
var ptr = self._unsafe_nextPtr;
var itemLength = _itemLength(ptr);
subItem._unsafe_memPtr = ptr;
subItem._unsafe_length = itemLength;
self._unsafe_nextPtr = ptr + itemLength;
}
else
revert();
}
function next(Iterator memory self, bool strict) internal constant returns (RLPItem memory subItem) {
subItem = next(self);
if(strict && !_validate(subItem))
revert();
return;
}
function hasNext(Iterator memory self) internal constant returns (bool) {
var item = self._unsafe_item;
return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length;
}
/* RLPItem */
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @return An RLPItem
function toRLPItem(bytes memory self) internal constant returns (RLPItem memory) {
uint len = self.length;
if (len == 0) {
return RLPItem(0, 0);
}
uint memPtr;
assembly {
memPtr := add(self, 0x20)
}
return RLPItem(memPtr, len);
}
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @param strict Will throw if the data is not RLP encoded.
/// @return An RLPItem
function toRLPItem(bytes memory self, bool strict) internal constant returns (RLPItem memory) {
var item = toRLPItem(self);
if(strict) {
uint len = self.length;
if(_payloadOffset(item) > len)
revert();
if(_itemLength(item._unsafe_memPtr) != len)
revert();
if(!_validate(item))
revert();
}
return item;
}
/// @dev Check if the RLP item is null.
/// @param self The RLP item.
/// @return 'true' if the item is null.
function isNull(RLPItem memory self) internal constant returns (bool ret) {
return self._unsafe_length == 0;
}
/// @dev Check if the RLP item is a list.
/// @param self The RLP item.
/// @return 'true' if the item is a list.
function isList(RLPItem memory self) internal constant returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := iszero(lt(byte(0, mload(memPtr)), 0xC0))
}
}
/// @dev Check if the RLP item is data.
/// @param self The RLP item.
/// @return 'true' if the item is data.
function isData(RLPItem memory self) internal constant returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := lt(byte(0, mload(memPtr)), 0xC0)
}
}
/// @dev Check if the RLP item is empty (string or list).
/// @param self The RLP item.
/// @return 'true' if the item is null.
function isEmpty(RLPItem memory self) internal constant returns (bool ret) {
if(isNull(self))
return false;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START);
}
/// @dev Get the number of items in an RLP encoded list.
/// @param self The RLP item.
/// @return The number of items.
function items(RLPItem memory self) internal constant returns (uint) {
if (!isList(self))
return 0;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
uint pos = memPtr + _payloadOffset(self);
uint last = memPtr + self._unsafe_length - 1;
uint itms;
while(pos <= last) {
pos += _itemLength(pos);
itms++;
}
return itms;
}
/// @dev Create an iterator.
/// @param self The RLP item.
/// @return An 'Iterator' over the item.
function iterator(RLPItem memory self) internal constant returns (Iterator memory it) {
if (!isList(self))
revert();
uint ptr = self._unsafe_memPtr + _payloadOffset(self);
it._unsafe_item = self;
it._unsafe_nextPtr = ptr;
}
/// @dev Return the RLP encoded bytes.
/// @param self The RLPItem.
/// @return The bytes.
/*
function toBytes(RLPItem memory self) internal constant returns (bytes memory bts) {
var len = self._unsafe_length;
if (len == 0)
return;
bts = new bytes(len);
_copyToBytes(self._unsafe_memPtr, bts, len);
}*/
/// @dev Decode an RLPItem into bytes. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
/*
function toData(RLPItem memory self) internal constant returns (bytes memory bts) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
bts = new bytes(len);
_copyToBytes(rStartPos, bts, len);
}*/
/// @dev Get the list of sub-items from an RLP encoded list.
/// Warning: This is inefficient, as it requires that the list is read twice.
/// @param self The RLP item.
/// @return Array of RLPItems.
function toList(RLPItem memory self) internal constant returns (RLPItem[] memory list) {
if(!isList(self))
revert();
var numItems = items(self);
list = new RLPItem[](numItems);
var it = iterator(self);
uint idx;
while(hasNext(it)) {
list[idx] = next(it);
idx++;
}
}
/// @dev Decode an RLPItem into an ascii string. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
/*
function toAscii(RLPItem memory self) internal constant returns (string memory str) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
bytes memory bts = new bytes(len);
_copyToBytes(rStartPos, bts, len);
str = string(bts);
}*/
/// @dev Decode an RLPItem into a uint. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toUint(RLPItem memory self) internal constant returns (uint data) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
if (len > 32 || len == 0)
revert();
assembly {
data := div(mload(rStartPos), exp(256, sub(32, len)))
}
}
/// @dev Decode an RLPItem into a boolean. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toBool(RLPItem memory self) internal constant returns (bool data) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
if (len != 1)
revert();
uint temp;
assembly {
temp := byte(0, mload(rStartPos))
}
if (temp > 1)
revert();
return temp == 1 ? true : false;
}
/// @dev Decode an RLPItem into a byte. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toByte(RLPItem memory self) internal constant returns (byte data) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
if (len != 1)
revert();
uint temp;
assembly {
temp := byte(0, mload(rStartPos))
}
return byte(temp);
}
/// @dev Decode an RLPItem into an int. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toInt(RLPItem memory self) internal constant returns (int data) {
return int(toUint(self));
}
/// @dev Decode an RLPItem into a bytes32. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toBytes32(RLPItem memory self) internal constant returns (bytes32 data) {
return bytes32(toUint(self));
}
/// @dev Decode an RLPItem into an address. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toAddress(RLPItem memory self) internal constant returns (address data) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
if (len != 20)
revert();
assembly {
data := div(mload(rStartPos), exp(256, 12))
}
}
// Get the payload offset.
function _payloadOffset(RLPItem memory self) private constant returns (uint) {
if(self._unsafe_length == 0)
return 0;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
if(b0 < DATA_SHORT_START)
return 0;
if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START))
return 1;
if(b0 < LIST_SHORT_START)
return b0 - DATA_LONG_OFFSET + 1;
return b0 - LIST_LONG_OFFSET + 1;
}
// Get the full length of an RLP item.
function _itemLength(uint memPtr) private constant returns (uint len) {
uint b0;
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START)
len = 1;
else if (b0 < DATA_LONG_START)
len = b0 - DATA_SHORT_START + 1;
else if (b0 < LIST_SHORT_START) {
assembly {
let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
else if (b0 < LIST_LONG_START)
len = b0 - LIST_SHORT_START + 1;
else {
assembly {
let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
}
// Get start position and length of the data.
function _decode(RLPItem memory self) private constant returns (uint memPtr, uint len) {
if(!isData(self))
revert();
uint b0;
uint start = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(start))
}
if (b0 < DATA_SHORT_START) {
memPtr = start;
len = 1;
return;
}
if (b0 < DATA_LONG_START) {
len = self._unsafe_length - 1;
memPtr = start + 1;
} else {
uint bLen;
assembly {
bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET
}
len = self._unsafe_length - 1 - bLen;
memPtr = start + bLen + 1;
}
return;
}
// Assumes that enough memory has been allocated to store in target.
/* this code is commented because I am too lazy to fix it to prevent jumpi warning, and since I don't use it anyway, I might as well just remove it.
function _copyToBytes(uint btsPtr, bytes memory tgt, uint btsLen) private constant {
// Exploiting the fact that 'tgt' was the last thing to be allocated,
// we can write entire words, and just overwrite any excess.
assembly {
{
let i := 0 // Start at arr + 0x20
let words := div(add(btsLen, 31), 32)
let rOffset := btsPtr
let wOffset := add(tgt, 0x20)
tag_loop:
jumpi(end, eq(i, words))
{
let offset := mul(i, 0x20)
mstore(add(wOffset, offset), mload(add(rOffset, offset)))
i := add(i, 1)
}
jump(tag_loop)
end:
mstore(add(tgt, add(0x20, mload(tgt))), 0)
}
}
}*/
// Check that an RLP item is valid.
function _validate(RLPItem memory self) private constant returns (bool ret) {
// Check that RLP is well-formed.
uint b0;
uint b1;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
b1 := byte(1, mload(memPtr))
}
if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START)
return false;
return true;
}
}
contract Agt {
using RLP for RLP.RLPItem;
using RLP for RLP.Iterator;
using RLP for bytes;
struct BlockHeader {
uint prevBlockHash; // 0
uint coinbase; // 1
uint blockNumber; // 8
//uint gasUsed; // 10
uint timestamp; // 11
bytes32 extraData; // 12
}
function Agt() {}
function parseBlockHeader( bytes rlpHeader ) constant internal returns(BlockHeader) {
BlockHeader memory header;
var it = rlpHeader.toRLPItem().iterator();
uint idx;
while(it.hasNext()) {
if( idx == 0 ) header.prevBlockHash = it.next().toUint();
else if ( idx == 2 ) header.coinbase = it.next().toUint();
else if ( idx == 8 ) header.blockNumber = it.next().toUint();
else if ( idx == 11 ) header.timestamp = it.next().toUint();
else if ( idx == 12 ) header.extraData = bytes32(it.next().toUint());
else it.next();
idx++;
}
return header;
}
//event VerifyAgt( string msg, uint index );
event VerifyAgt( uint error, uint index );
struct VerifyAgtData {
uint rootHash;
uint rootMin;
uint rootMax;
uint leafHash;
uint leafCounter;
}
function verifyAgt( VerifyAgtData data,
uint branchIndex,
uint[] countersBranch,
uint[] hashesBranch ) constant internal returns(bool) {
uint currentHash = data.leafHash & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint leftCounterMin;
uint leftCounterMax;
uint leftHash;
uint rightCounterMin;
uint rightCounterMax;
uint rightHash;
uint min = data.leafCounter;
uint max = data.leafCounter;
for( uint i = 0 ; i < countersBranch.length ; i++ ) {
if( branchIndex & 0x1 > 0 ) {
leftCounterMin = countersBranch[i] & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
leftCounterMax = countersBranch[i] >> 128;
leftHash = hashesBranch[i];
rightCounterMin = min;
rightCounterMax = max;
rightHash = currentHash;
}
else {
leftCounterMin = min;
leftCounterMax = max;
leftHash = currentHash;
rightCounterMin = countersBranch[i] & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
rightCounterMax = countersBranch[i] >> 128;
rightHash = hashesBranch[i];
}
currentHash = uint(sha3(leftCounterMin + (leftCounterMax << 128),
leftHash,
rightCounterMin + (rightCounterMax << 128),
rightHash)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if( (leftCounterMin >= leftCounterMax) || (rightCounterMin >= rightCounterMax) ) {
if( i > 0 ) {
//VerifyAgt( "counters mismatch",i);
VerifyAgt( 0x80000000, i );
return false;
}
if( leftCounterMin > leftCounterMax ) {
//VerifyAgt( "counters mismatch",i);
VerifyAgt( 0x80000001, i );
return false;
}
if( rightCounterMin > rightCounterMax ) {
//VerifyAgt( "counters mismatch",i);
VerifyAgt( 0x80000002, i );
return false;
}
}
if( leftCounterMax >= rightCounterMin ) {
VerifyAgt( 0x80000009, i );
return false;
}
min = leftCounterMin;
max = rightCounterMax;
branchIndex = branchIndex / 2;
}
if( min != data.rootMin ) {
//VerifyAgt( "min does not match root min",min);
VerifyAgt( 0x80000003, min );
return false;
}
if( max != data.rootMax ) {
//VerifyAgt( "max does not match root max",max);
VerifyAgt( 0x80000004, max );
return false;
}
if( currentHash != data.rootHash ) {
//VerifyAgt( "hash does not match root hash",currentHash);
VerifyAgt( 0x80000005, currentHash );
return false;
}
return true;
}
function verifyAgtDebugForTesting( uint rootHash,
uint rootMin,
uint rootMax,
uint leafHash,
uint leafCounter,
uint branchIndex,
uint[] countersBranch,
uint[] hashesBranch ) returns(bool) {
VerifyAgtData memory data;
data.rootHash = rootHash;
data.rootMin = rootMin;
data.rootMax = rootMax;
data.leafHash = leafHash;
data.leafCounter = leafCounter;
return verifyAgt( data, branchIndex, countersBranch, hashesBranch );
}
}
contract WeightedSubmission {
function WeightedSubmission(){}
struct SingleSubmissionData {
uint128 numShares;
uint128 submissionValue;
uint128 totalPreviousSubmissionValue;
uint128 min;
uint128 max;
uint128 augRoot;
}
struct SubmissionMetaData {
uint64 numPendingSubmissions;
uint32 readyForVerification; // suppose to be bool
uint32 lastSubmissionBlockNumber;
uint128 totalSubmissionValue;
uint128 difficulty;
uint128 lastCounter;
uint submissionSeed;
}
mapping(address=>SubmissionMetaData) submissionsMetaData;
// (user, submission number)=>data
mapping(address=>mapping(uint=>SingleSubmissionData)) submissionsData;
event SubmitClaim( address indexed sender, uint error, uint errorInfo );
function submitClaim( uint numShares, uint difficulty, uint min, uint max, uint augRoot, bool lastClaimBeforeVerification ) {
SubmissionMetaData memory metaData = submissionsMetaData[msg.sender];
if( metaData.lastCounter >= min ) {
// miner cheated. min counter is too low
SubmitClaim( msg.sender, 0x81000001, metaData.lastCounter );
return;
}
if( metaData.readyForVerification > 0 ) {
// miner cheated - should go verification first
SubmitClaim( msg.sender, 0x81000002, 0 );
return;
}
if( metaData.numPendingSubmissions > 0 ) {
if( metaData.difficulty != difficulty ) {
// could not change difficulty before verification
SubmitClaim( msg.sender, 0x81000003, metaData.difficulty );
return;
}
}
SingleSubmissionData memory submissionData;
submissionData.numShares = uint64(numShares);
uint blockDifficulty;
if( block.difficulty == 0 ) {
// testrpc - fake increasing difficulty
blockDifficulty = (900000000 * (metaData.numPendingSubmissions+1));
}
else {
blockDifficulty = block.difficulty;
}
submissionData.submissionValue = uint128((uint(numShares * difficulty) * (5 ether)) / blockDifficulty);
submissionData.totalPreviousSubmissionValue = metaData.totalSubmissionValue;
submissionData.min = uint128(min);
submissionData.max = uint128(max);
submissionData.augRoot = uint128(augRoot);
(submissionsData[msg.sender])[metaData.numPendingSubmissions] = submissionData;
// update meta data
metaData.numPendingSubmissions++;
metaData.lastSubmissionBlockNumber = uint32(block.number);
metaData.difficulty = uint128(difficulty);
metaData.lastCounter = uint128(max);
metaData.readyForVerification = lastClaimBeforeVerification ? uint32(1) : uint32(0);
uint128 temp128;
temp128 = metaData.totalSubmissionValue;
metaData.totalSubmissionValue += submissionData.submissionValue;
if( temp128 > metaData.totalSubmissionValue ) {
// overflow in calculation
// note that this code is reachable if user is dishonest and give false
// report on his submission. but even without
// this validation, user cannot benifit from the overflow
SubmitClaim( msg.sender, 0x81000005, 0 );
return;
}
submissionsMetaData[msg.sender] = metaData;
// everything is ok
SubmitClaim( msg.sender, 0, numShares * difficulty );
}
function getClaimSeed(address sender) constant returns(uint){
SubmissionMetaData memory metaData = submissionsMetaData[sender];
if( metaData.readyForVerification == 0 ) return 0;
if( metaData.submissionSeed != 0 ) return metaData.submissionSeed;
uint lastBlockNumber = uint(metaData.lastSubmissionBlockNumber);
if( block.number > lastBlockNumber + 200 ) return 0;
if( block.number <= lastBlockNumber + 15 ) return 0;
return uint(block.blockhash(lastBlockNumber + 10));
}
event StoreClaimSeed( address indexed sender, uint error, uint errorInfo );
function storeClaimSeed( address miner ) {
// anyone who is willing to pay gas fees can call this function
uint seed = getClaimSeed( miner );
if( seed != 0 ) {
submissionsMetaData[miner].submissionSeed = seed;
StoreClaimSeed( msg.sender, 0, uint(miner) );
return;
}
// else
SubmissionMetaData memory metaData = submissionsMetaData[miner];
uint lastBlockNumber = uint(metaData.lastSubmissionBlockNumber);
if( metaData.readyForVerification == 0 ) {
// submission is not ready for verification
StoreClaimSeed( msg.sender, 0x8000000, uint(miner) );
}
else if( block.number > lastBlockNumber + 200 ) {
// submission is not ready for verification
StoreClaimSeed( msg.sender, 0x8000001, uint(miner) );
}
else if( block.number <= lastBlockNumber + 15 ) {
// it is too late to call store function
StoreClaimSeed( msg.sender, 0x8000002, uint(miner) );
}
else {
// unknown error
StoreClaimSeed( msg.sender, 0x8000003, uint(miner) );
}
}
function verifySubmissionIndex( address sender, uint seed, uint submissionNumber, uint shareIndex ) constant returns(bool) {
if( seed == 0 ) return false;
uint totalValue = uint(submissionsMetaData[sender].totalSubmissionValue);
uint numPendingSubmissions = uint(submissionsMetaData[sender].numPendingSubmissions);
SingleSubmissionData memory submissionData = (submissionsData[sender])[submissionNumber];
if( submissionNumber >= numPendingSubmissions ) return false;
uint seed1 = seed & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint seed2 = seed / (2**128);
uint selectedValue = seed1 % totalValue;
if( uint(submissionData.totalPreviousSubmissionValue) >= selectedValue ) return false;
if( uint(submissionData.totalPreviousSubmissionValue + submissionData.submissionValue) < selectedValue ) return false;
uint expectedShareshareIndex = (seed2 % uint(submissionData.numShares));
if( expectedShareshareIndex != shareIndex ) return false;
return true;
}
function calculateSubmissionIndex( address sender, uint seed ) constant returns(uint[2]) {
// this function should be executed off chain - hene, it is not optimized
uint seed1 = seed & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint seed2 = seed / (2**128);
uint totalValue = uint(submissionsMetaData[sender].totalSubmissionValue);
uint numPendingSubmissions = uint(submissionsMetaData[sender].numPendingSubmissions);
uint selectedValue = seed1 % totalValue;
SingleSubmissionData memory submissionData;
for( uint submissionInd = 0 ; submissionInd < numPendingSubmissions ; submissionInd++ ) {
submissionData = (submissionsData[sender])[submissionInd];
if( uint(submissionData.totalPreviousSubmissionValue + submissionData.submissionValue) >= selectedValue ) break;
}
// unexpected error
if( submissionInd == numPendingSubmissions ) return [uint(0xFFFFFFFFFFFFFFFF),0xFFFFFFFFFFFFFFFF];
uint shareIndex = seed2 % uint(submissionData.numShares);
return [submissionInd, shareIndex];
}
// should be called only from verify claim
function closeSubmission( address sender ) internal {
SubmissionMetaData memory metaData = submissionsMetaData[sender];
metaData.numPendingSubmissions = 0;
metaData.totalSubmissionValue = 0;
metaData.readyForVerification = 0;
metaData.submissionSeed = 0;
// last counter must not be reset
// last submission block number and difficulty are also kept, but it is not a must
// only to save some gas
submissionsMetaData[sender] = metaData;
}
struct SubmissionDataForClaimVerification {
uint lastCounter;
uint shareDifficulty;
uint totalSubmissionValue;
uint min;
uint max;
uint augMerkle;
bool indicesAreValid;
bool readyForVerification;
}
function getClaimData( address sender, uint submissionIndex, uint shareIndex, uint seed )
constant internal returns(SubmissionDataForClaimVerification){
SubmissionDataForClaimVerification memory output;
SubmissionMetaData memory metaData = submissionsMetaData[sender];
output.lastCounter = uint(metaData.lastCounter);
output.shareDifficulty = uint(metaData.difficulty);
output.totalSubmissionValue = metaData.totalSubmissionValue;
SingleSubmissionData memory submissionData = (submissionsData[sender])[submissionIndex];
output.min = uint(submissionData.min);
output.max = uint(submissionData.max);
output.augMerkle = uint(submissionData.augRoot);
output.indicesAreValid = verifySubmissionIndex( sender, seed, submissionIndex, shareIndex );
output.readyForVerification = (metaData.readyForVerification > 0);
return output;
}
function debugGetNumPendingSubmissions( address sender ) constant returns(uint) {
return uint(submissionsMetaData[sender].numPendingSubmissions);
}
event DebugResetSubmissions( address indexed sender, uint error, uint errorInfo );
function debugResetSubmissions( ) {
// should be called only in emergency
// msg.sender will loose all its pending shares
closeSubmission(msg.sender);
DebugResetSubmissions( msg.sender, 0, 0 );
}
}
contract SmartPool is Agt, WeightedSubmission {
string public version = "0.1.1";
Ethash public ethashContract;
address public withdrawalAddress;
mapping(address=>bool) public owners;
bool public newVersionReleased = false;
struct MinerData {
bytes32 minerId;
address paymentAddress;
}
mapping(address=>MinerData) minersData;
mapping(bytes32=>bool) public existingIds;
bool public whiteListEnabled;
bool public blackListEnabled;
mapping(address=>bool) whiteList;
mapping(address=>bool) blackList;
function SmartPool( address[] _owners,
Ethash _ethashContract,
address _withdrawalAddress,
bool _whiteListEnabled,
bool _blackListEnabled ) payable {
for( uint i = 0 ; i < _owners.length ; i++ ) {
owners[_owners[i]] = true;
}
ethashContract = _ethashContract;
withdrawalAddress = _withdrawalAddress;
whiteListEnabled = _whiteListEnabled;
blackListEnabled = _blackListEnabled;
}
function replaceOwner(address _newOwner) {
require( owners[msg.sender] );
owners[msg.sender] = false;
owners[_newOwner] = true;
}
function declareNewerVersion() {
require( owners[msg.sender] );
newVersionReleased = true;
//if( ! msg.sender.send(this.balance) ) throw;
}
event Withdraw( address indexed sender, uint error, uint errorInfo );
function withdraw( uint amount ) {
if( ! owners[msg.sender] ) {
// only ownder can withdraw
Withdraw( msg.sender, 0x80000000, amount );
return;
}
withdrawalAddress.transfer( amount );
Withdraw( msg.sender, 0, amount );
}
function to62Encoding( uint id, uint numChars ) constant returns(bytes32) {
require( id < (26+26+10)**numChars );
uint result = 0;
for( uint i = 0 ; i < numChars ; i++ ) {
uint b = id % (26+26+10);
uint8 char;
if( b < 10 ) {
char = uint8(b + 0x30); // 0x30 = '0'
}
else if( b < 26 + 10 ) {
char = uint8(b + 0x61 - 10); //0x61 = 'a'
}
else {
char = uint8(b + 0x41 - 26 - 10); // 0x41 = 'A'
}
result = (result * 256) + char;
id /= (26+26+10);
}
return bytes32(result);
}
event Register( address indexed sender, uint error, uint errorInfo );
function register( address paymentAddress ) {
address minerAddress = msg.sender;
// build id
uint id = uint(minerAddress) % (26+26+10)**11;
bytes32 minerId = to62Encoding(id,11);
if( existingIds[minersData[minerAddress].minerId] ) {
// miner id is already in use
Register( msg.sender, 0x80000000, uint(minerId) );
return;
}
if( paymentAddress == address(0) ) {
// payment address is 0
Register( msg.sender, 0x80000001, uint(paymentAddress) );
return;
}
if( whiteListEnabled ) {
if( ! whiteList[ msg.sender ] ) {
// miner not in white list
Register( msg.sender, 0x80000002, uint(minerId) );
return;
}
}
if( blackListEnabled ) {
if( blackList[ msg.sender ] ) {
// miner on black list
Register( msg.sender, 0x80000003, uint(minerId) );
return;
}
}
// last counter is set to 0.
// It might be safer to change it to now.
//minersData[minerAddress].lastCounter = now * (2**64);
minersData[minerAddress].paymentAddress = paymentAddress;
minersData[minerAddress].minerId = minerId;
existingIds[minersData[minerAddress].minerId] = true;
// succesful registration
Register( msg.sender, 0, 0 );
}
function canRegister(address sender) constant returns(bool) {
uint id = uint(sender) % (26+26+10)**11;
bytes32 expectedId = to62Encoding(id,11);
if( whiteListEnabled ) {
if( ! whiteList[ sender ] ) return false;
}
if( blackListEnabled ) {
if( blackList[ sender ] ) return false;
}
return ! existingIds[expectedId];
}
function isRegistered(address sender) constant returns(bool) {
return minersData[sender].paymentAddress != address(0);
}
function getMinerId(address sender) constant returns(bytes32) {
return minersData[sender].minerId;
}
event UpdateWhiteList( address indexed miner, uint error, uint errorInfo, bool add );
event UpdateBlackList( address indexed miner, uint error, uint errorInfo, bool add );
function unRegister( address miner ) internal {
minersData[miner].paymentAddress = address(0);
existingIds[minersData[miner].minerId] = false;
}
function updateWhiteList( address miner, bool add ) {
if( ! owners[ msg.sender ] ) {
// only owner can update list
UpdateWhiteList( msg.sender, 0x80000000, 0, add );
return;
}
if( ! whiteListEnabled ) {
// white list is not enabeled
UpdateWhiteList( msg.sender, 0x80000001, 0, add );
return;
}
whiteList[ miner ] = add;
if( ! add && isRegistered( miner ) ) {
// unregister
unRegister( miner );
}
UpdateWhiteList( msg.sender, 0, uint(miner), add );
}
function updateBlackList( address miner, bool add ) {
if( ! owners[ msg.sender ] ) {
// only owner can update list
UpdateBlackList( msg.sender, 0x80000000, 0, add );
return;
}
if( ! blackListEnabled ) {
// white list is not enabeled
UpdateBlackList( msg.sender, 0x80000001, 0, add );
return;
}
blackList[ miner ] = add;
if( add && isRegistered( miner ) ) {
// unregister
unRegister( miner );
}
UpdateBlackList( msg.sender, 0, uint(miner), add );
}
event DisableBlackListForever( address indexed sender, uint error, uint errorInfo );
function disableBlackListForever() {
if( ! owners[ msg.sender ] ) {
// only owner can update list
DisableBlackListForever( msg.sender, 0x80000000, 0 );
return;
}
blackListEnabled = false;
DisableBlackListForever( msg.sender, 0, 0 );
}
event DisableWhiteListForever( address indexed sender, uint error, uint errorInfo );
function disableWhiteListForever() {
if( ! owners[ msg.sender ] ) {
// only owner can update list
DisableWhiteListForever( msg.sender, 0x80000000, 0 );
return;
}
whiteListEnabled = false;
DisableWhiteListForever( msg.sender, 0, 0 );
}
event VerifyExtraData( address indexed sender, uint error, uint errorInfo );
function verifyExtraData( bytes32 extraData, bytes32 minerId, uint difficulty ) constant internal returns(bool) {
uint i;
// compare id
for( i = 0 ; i < 11 ; i++ ) {
if( extraData[10+i] != minerId[21+i] ) {
//ErrorLog( "verifyExtraData: miner id not as expected", 0 );
VerifyExtraData( msg.sender, 0x83000000, uint(minerId) );
return false;
}
}
// compare difficulty
bytes32 encodedDiff = to62Encoding(difficulty,11);
for( i = 0 ; i < 11 ; i++ ) {
if(extraData[i+21] != encodedDiff[21+i]) {
//ErrorLog( "verifyExtraData: difficulty is not as expected", uint(encodedDiff) );
VerifyExtraData( msg.sender, 0x83000001, uint(encodedDiff) );
return false;
}
}
return true;
}
event VerifyClaim( address indexed sender, uint error, uint errorInfo );
function verifyClaim( bytes rlpHeader,
uint nonce,
uint submissionIndex,
uint shareIndex,
uint[] dataSetLookup,
uint[] witnessForLookup,
uint[] augCountersBranch,
uint[] augHashesBranch ) {
if( ! isRegistered(msg.sender) ) {
// miner is not registered
VerifyClaim( msg.sender, 0x8400000c, 0 );
return;
}
SubmissionDataForClaimVerification memory submissionData = getClaimData( msg.sender,
submissionIndex, shareIndex, getClaimSeed( msg.sender ) );
if( ! submissionData.readyForVerification ) {
//ErrorLog( "there are no pending claims", 0 );
VerifyClaim( msg.sender, 0x84000003, 0 );
return;
}
BlockHeader memory header = parseBlockHeader(rlpHeader);
// check extra data
if( ! verifyExtraData( header.extraData,
minersData[ msg.sender ].minerId,
submissionData.shareDifficulty ) ) {
//ErrorLog( "extra data not as expected", uint(header.extraData) );
VerifyClaim( msg.sender, 0x84000004, uint(header.extraData) );
return;
}
// check coinbase data
if( header.coinbase != uint(this) ) {
//ErrorLog( "coinbase not as expected", uint(header.coinbase) );
VerifyClaim( msg.sender, 0x84000005, uint(header.coinbase) );
return;
}
// check counter
uint counter = header.timestamp * (2 ** 64) + nonce;
if( counter < submissionData.min ) {
//ErrorLog( "counter is smaller than min",counter);
VerifyClaim( msg.sender, 0x84000007, counter );
return;
}
if( counter > submissionData.max ) {
//ErrorLog( "counter is smaller than max",counter);
VerifyClaim( msg.sender, 0x84000008, counter );
return;
}
// verify agt
uint leafHash = uint(sha3(rlpHeader));
VerifyAgtData memory agtData;
agtData.rootHash = submissionData.augMerkle;
agtData.rootMin = submissionData.min;
agtData.rootMax = submissionData.max;
agtData.leafHash = leafHash;
agtData.leafCounter = counter;
if( ! verifyAgt( agtData,
shareIndex,
augCountersBranch,
augHashesBranch ) ) {
//ErrorLog( "verifyAgt failed",0);
VerifyClaim( msg.sender, 0x84000009, 0 );
return;
}
/*
// check epoch data - done inside hashimoto
if( ! ethashContract.isEpochDataSet( header.blockNumber / 30000 ) ) {
//ErrorLog( "epoch data was not set",header.blockNumber / 30000);
VerifyClaim( msg.sender, 0x8400000a, header.blockNumber / 30000 );
return;
}*/
// verify ethash
uint ethash = ethashContract.hashimoto( bytes32(leafHash),
bytes8(nonce),
dataSetLookup,
witnessForLookup,
header.blockNumber / 30000 );
if( ethash > ((2**256-1)/submissionData.shareDifficulty )) {
if( ethash == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE ) {
//ErrorLog( "epoch data was not set",header.blockNumber / 30000);
VerifyClaim( msg.sender, 0x8400000a, header.blockNumber / 30000 );
}
else {
//ErrorLog( "ethash difficulty too low",ethash);
VerifyClaim( msg.sender, 0x8400000b, ethash );
}
return;
}
if( getClaimSeed(msg.sender) == 0 ) {
//ErrorLog( "claim seed is 0", 0 );
VerifyClaim( msg.sender, 0x84000001, 0 );
return;
}
if( ! submissionData.indicesAreValid ) {
//ErrorLog( "share index or submission are not as expected. should be:", getShareIndex() );
VerifyClaim( msg.sender, 0x84000002, 0 );
return;
}
// recrusive attack is not possible as doPayment is using send and not call.
if( ! doPayment(submissionData.totalSubmissionValue,
minersData[ msg.sender ].paymentAddress) ) {
// error msg is given in doPayment function
return;
}
closeSubmission( msg.sender );
//minersData[ msg.sender ].pendingClaim = false;
VerifyClaim( msg.sender, 0, 0 );
return;
}
// 10000 = 100%
uint public uncleRate = 500; // 5%
// 10000 = 100%
uint public poolFees = 0;
event IncomingFunds( address sender, uint amountInWei );
function() payable {
require(msg.value > 0 ); // prevent, e.g., receiving ERC223 tokens.
IncomingFunds( msg.sender, msg.value );
}
event SetUnlceRateAndFees( address indexed sender, uint error, uint errorInfo );
function setUnlceRateAndFees( uint _uncleRate, uint _poolFees ) {
if( ! owners[msg.sender] ) {
// only owner should change rates
SetUnlceRateAndFees( msg.sender, 0x80000000, 0 );
return;
}
uncleRate = _uncleRate;
poolFees = _poolFees;
SetUnlceRateAndFees( msg.sender, 0, 0 );
}
event DoPayment( address indexed sender, address paymentAddress, uint valueInWei );
function doPayment( uint submissionValue,
address paymentAddress ) internal returns(bool) {
uint payment = submissionValue;
// take uncle rate into account
// payment = payment * (1-0.25*uncleRate)
// uncleRate in [0,10000]
payment = (payment * (4*10000 - uncleRate)) / (4*10000);
// fees
payment = (payment * (10000 - poolFees)) / 10000;
if( payment > this.balance ){
//ErrorLog( "cannot afford to pay", calcPayment( submissionData.numShares, submissionData.difficulty ) );
VerifyClaim( msg.sender, 0x84000000, payment );
return false;
}
paymentAddress.transfer( payment );
DoPayment( msg.sender, paymentAddress, payment );
return true;
}
function getPoolBalance( ) constant returns(uint) {
// debug function for testrpc
return this.balance;
}
event GetShareIndexDebugForTestRPCSubmissionIndex( uint index );
event GetShareIndexDebugForTestRPCShareIndex( uint index );
function getShareIndexDebugForTestRPC( address sender ) {
uint seed = getClaimSeed( sender );
uint[2] memory result = calculateSubmissionIndex( sender, seed );
GetShareIndexDebugForTestRPCSubmissionIndex( result[0] );
GetShareIndexDebugForTestRPCShareIndex( result[1] );
}
}
| should be called only in emergency msg.sender will loose all its pending shares | function debugResetSubmissions( ) {
closeSubmission(msg.sender);
DebugResetSubmissions( msg.sender, 0, 0 );
}
| 13,006,315 |
pragma solidity 0.5.15;
contract IAugur {
function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING
function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING
function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING
function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING
function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING
function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING
function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING
function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING
function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING
function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IOwnable {
function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING
function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING
}
contract ITyped {
function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING
}
library SafeMathUint256 {
function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV647(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 c;
}
function SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
return a - b;
}
function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a <= b) {
return a;
} else {
return b;
}
}
function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a >= b) {
return a;
} else {
return b;
}
}
function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING
if (y > 3) {
uint256 x = (y + 1) / 2;
z = y;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING
return 0;
}
function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 2 ** 256 - 1
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING
return a % b == 0;
}
// Float [fixed point] Operations
function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, b), base);
}
function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, base), b);
}
}
interface IERC1155 {
event TRANSFERSINGLE49( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TRANSFERBATCH882( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event APPROVALFORALL731( //inject NONSTANDARD NAMING
address indexed owner,
address indexed operator,
bool approved
);
event URI998( //inject NONSTANDARD NAMING
string value,
uint256 indexed id
);
function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFBATCH918( //inject NONSTANDARD NAMING
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
contract IERC20 {
function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING
// solhint-disable-next-line no-simple-event-func-name
event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract ICash is IERC20 {
}
contract ERC20 is IERC20 {
using SafeMathUint256 for uint256;
uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING
uint256 public totalSupply;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowances;
function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING
return balances[_account];
}
function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(msg.sender, _recipient, _amount);
return true;
}
function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return allowances[_owner][_spender];
}
function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, _amount);
return true;
}
function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(_sender, _recipient, _amount);
_APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount));
return true;
}
function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue));
return true;
}
function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue));
return true;
}
function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_sender != address(0), "ERC20: transfer from the zero address");
require(_recipient != address(0), "ERC20: transfer to the zero address");
balances[_sender] = balances[_sender].SUB692(_amount);
balances[_recipient] = balances[_recipient].ADD571(_amount);
emit TRANSFER723(_sender, _recipient, _amount);
ONTOKENTRANSFER292(_sender, _recipient, _amount);
}
function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: mint to the zero address");
totalSupply = totalSupply.ADD571(_amount);
balances[_account] = balances[_account].ADD571(_amount);
emit TRANSFER723(address(0), _account, _amount);
}
function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: burn from the zero address");
balances[_account] = balances[_account].SUB692(_amount);
totalSupply = totalSupply.SUB692(_amount);
emit TRANSFER723(_account, address(0), _amount);
}
function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = _amount;
emit APPROVAL665(_owner, _spender, _amount);
}
function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
_BURN356(_account, _amount);
_APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount));
}
// Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING
}
contract VariableSupplyToken is ERC20 {
using SafeMathUint256 for uint256;
function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_MINT880(_target, _amount);
ONMINT315(_target, _amount);
return true;
}
function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_BURN356(_target, _amount);
ONBURN653(_target, _amount);
return true;
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING
}
}
contract IAffiliateValidator {
function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING
}
contract IDisputeWindow is ITyped, IERC20 {
function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING
function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING
function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING
function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING
function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING
function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING
function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING
function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING
function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING
}
contract IMarket is IOwnable {
enum MarketType {
YES_NO,
CATEGORICAL,
SCALAR
}
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING
function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING
function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING
function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING
function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING
function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING
function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IReportingParticipant {
function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING
function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING
function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING
function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 {
function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING
function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING
function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING
function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING
function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING
function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IInitialReporter is IReportingParticipant, IOwnable {
function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING
function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING
function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING
function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING
function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING
function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING
}
contract IReputationToken is IERC20 {
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING
}
contract IShareToken is ITyped, IERC1155 {
function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING
function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING
function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING
function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING
function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING
function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING
function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING
function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING
function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING
function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING
function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IUniverse {
function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING
function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING
function FORK341() public returns (bool); //inject NONSTANDARD NAMING
function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING
function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING
function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING
function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING
function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING
function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING
function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING
function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING
function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING
}
contract IV2ReputationToken is IReputationToken {
function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING
}
library Reporting {
uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING
uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING
uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING
uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING
uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING
uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING
uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING
uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING
uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING
uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING
uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING
uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING
uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING
uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING
uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING
uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING
uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING
uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING
function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING
function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING
function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING
function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING
function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING
function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING
function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING
function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING
function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING
function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING
function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING
function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING
function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING
function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING
function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING
function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING
function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING
function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING
}
contract IAugurTrading {
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING
}
contract IOrders {
function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING
function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING
function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING
function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING
function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING
function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING
function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING
function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING
function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING
function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING
function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING
function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING
}
library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IMarket market;
IAugur augur;
IAugurTrading augurTrading;
IShareToken shareToken;
ICash cash;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING
require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range");
require(_price != 0, "Order.create: Price may not be 0");
require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range");
require(_attoshares > 0, "Order.create: Cannot use amount of 0");
require(_creator != address(0), "Order.create: Creator is 0x0");
IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken"));
return Data({
market: _market,
augur: _augur,
augurTrading: _augurTrading,
shareToken: _shareToken,
cash: ICash(_augur.LOOKUP594("Cash")),
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible");
_orderData.id = _orderId;
}
return _orderData.id;
}
function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed));
}
function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING
GETORDERID157(_orderData, _orders);
uint256[] memory _uints = new uint256[](5);
_uints[0] = _orderData.amount;
_uints[1] = _orderData.price;
_uints[2] = _orderData.outcome;
_uints[3] = _orderData.moneyEscrowed;
_uints[4] = _orderData.sharesEscrowed;
bytes32[] memory _bytes32s = new bytes32[](4);
_bytes32s[0] = _orderData.betterOrderId;
_bytes32s[1] = _orderData.worseOrderId;
_bytes32s[2] = _tradeGroupId;
_bytes32s[3] = _orderData.id;
return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator);
}
}
interface IUniswapV2Pair {
event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP992( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING
function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM81(address to) external; //inject NONSTANDARD NAMING
function SYNC86() external; //inject NONSTANDARD NAMING
function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING
}
contract IRepSymbol {
function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract ReputationToken is VariableSupplyToken, IV2ReputationToken {
using SafeMathUint256 for uint256;
string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING
IUniverse internal universe;
IUniverse public parentUniverse;
uint256 internal totalMigrated;
IERC20 public legacyRepToken;
IAugur public augur;
address public warpSync;
constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public {
augur = _augur;
universe = _universe;
parentUniverse = _parentUniverse;
warpSync = _augur.LOOKUP594("WarpSync");
legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken"));
require(warpSync != address(0));
require(legacyRepToken != IERC20(0));
}
function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING
return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe));
}
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(_attotokens > 0);
IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators);
IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35();
BURN234(msg.sender, _attotokens);
_destination.MIGRATEIN692(msg.sender, _attotokens);
return true;
}
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
IUniverse _parentUniverse = parentUniverse;
require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35());
require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510());
MINT146(_reporter, _attotokens);
totalMigrated += _attotokens;
// Update the fork tentative winner and finalize if we can
if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) {
_parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230());
}
return true;
}
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING
IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender);
require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant));
// simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute
uint256 _bonus = _amountMigrated.MUL760(2) / 5;
MINT146(address(_reportingParticipant), _bonus);
return true;
}
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING
require(warpSync == msg.sender);
MINT146(_target, _amountToMint);
universe.UPDATEFORKVALUES73();
return true;
}
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
BURN234(msg.sender, _amountToBurn);
return true;
}
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(IUniverse(msg.sender) == universe);
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING
IUniverse _universe = _shadyReputationToken.GETUNIVERSE719();
require(universe.ISPARENTOF319(_universe));
require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken);
}
function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING
return universe;
}
function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING
return totalMigrated;
}
function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING
return legacyRepToken;
}
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _totalSupply = totalSupply;
if (parentUniverse == IUniverse(0)) {
return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0)));
} else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) {
return _totalSupply;
} else {
return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552();
}
}
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]);
}
function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]);
}
function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]);
}
function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING
require(parentUniverse == IUniverse(0));
uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender);
require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance));
MINT146(msg.sender, _legacyBalance);
return true;
}
} | inject NONSTANDARD NAMING | function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); | 2,553,957 |
/*
Copyright 2019 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
pragma experimental "ABIEncoderV2";
import { ERC20 } from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import { Math } from "openzeppelin-solidity/contracts/math/Math.sol";
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { RebalancingLibrary } from "../../lib/RebalancingLibrary.sol";
import { RebalancingSetState } from "./RebalancingSetState.sol";
/**
* @title RebalancingStart
* @author Set Protocol
*
* Implementation of Rebalancing Set Token V2 start rebalance functionality
*/
contract RebalancingStart is
ERC20,
RebalancingSetState
{
using SafeMath for uint256;
/* ============ Internal Functions ============ */
/**
* Validate that start rebalance can be called:
* - Current state is Default
* - rebalanceInterval has elapsed
* - Proposed set is valid in Core
* - Components in set are all valid
* - NaturalUnits are multiples of each other
*
* @param _nextSet The Set to rebalance into
*/
function validateStartRebalance(
ISetToken _nextSet
)
internal
view
{
validateRebalanceStateIs(RebalancingLibrary.State.Default);
// Enough time must have passed from last rebalance to start a new proposal
require(
block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval),
"Interval not elapsed"
);
// Must be a positive supply of the Set
require(
totalSupply() > 0,
"Invalid supply"
);
// New proposed Set must be a valid Set created by Core
require(
core.validSets(address(_nextSet)),
"Invalid Set"
);
// Check proposed components on whitelist. This is to ensure managers are unable to add contract addresses
// to a propose that prohibit the set from carrying out an auction i.e. a token that only the manager possesses
require(
componentWhiteList.areValidAddresses(_nextSet.getComponents()),
"Invalid component"
);
// Check that the proposed set natural unit is a multiple of current set natural unit, or vice versa.
// Done to make sure that when calculating token units there will are be rounding errors.
require(
naturalUnitsAreValid(currentSet, _nextSet),
"Invalid natural unit"
);
}
/**
* Calculates the maximum quantity of the currentSet that can be redeemed. This is defined
* by how many naturalUnits worth of the Set there are.
*
* @return Maximum quantity of the current Set that can be redeemed
*/
function calculateStartingSetQuantity()
internal
view
returns (uint256)
{
uint256 currentSetBalance = vault.getOwnerBalance(address(currentSet), address(this));
uint256 currentSetNaturalUnit = currentSet.naturalUnit();
// Rounds the redemption quantity to a multiple of the current Set natural unit
return currentSetBalance.sub(currentSetBalance.mod(currentSetNaturalUnit));
}
/**
* Signals to the Liquidator to initiate the rebalance.
*
* @param _nextSet Next set instance
* @param _startingCurrentSetQuantity Amount of currentSets the rebalance is initiated with
* @param _liquidatorData Bytecode formatted data with liquidator-specific arguments
*/
function liquidatorRebalancingStart(
ISetToken _nextSet,
uint256 _startingCurrentSetQuantity,
bytes memory _liquidatorData
)
internal
{
liquidator.startRebalance(
currentSet,
_nextSet,
_startingCurrentSetQuantity,
_liquidatorData
);
}
/**
* Updates rebalance-related state parameters.
*
* @param _nextSet The Set to rebalance into
*/
function transitionToRebalance(ISetToken _nextSet) internal {
nextSet = _nextSet;
rebalanceState = RebalancingLibrary.State.Rebalance;
rebalanceStartTime = block.timestamp;
}
/* ============ Private Functions ============ */
/**
* Check that the proposed set natural unit is a multiple of current set natural unit, or vice versa.
* Done to make sure that when calculating token units there will be no rounding errors.
*
* @param _currentSet The current base SetToken
* @param _nextSet The proposed SetToken
*/
function naturalUnitsAreValid(
ISetToken _currentSet,
ISetToken _nextSet
)
private
view
returns (bool)
{
uint256 currentNaturalUnit = _currentSet.naturalUnit();
uint256 nextSetNaturalUnit = _nextSet.naturalUnit();
return Math.max(currentNaturalUnit, nextSetNaturalUnit).mod(
Math.min(currentNaturalUnit, nextSetNaturalUnit)
) == 0;
}
}
| Check that the proposed set natural unit is a multiple of current set natural unit, or vice versa. Done to make sure that when calculating token units there will be no rounding errors. _currentSet The current base SetToken _nextSet The proposed SetToken/ | function naturalUnitsAreValid(
ISetToken _currentSet,
ISetToken _nextSet
)
private
view
returns (bool)
{
uint256 currentNaturalUnit = _currentSet.naturalUnit();
uint256 nextSetNaturalUnit = _nextSet.naturalUnit();
return Math.max(currentNaturalUnit, nextSetNaturalUnit).mod(
Math.min(currentNaturalUnit, nextSetNaturalUnit)
) == 0;
}
| 1,078,437 |
pragma experimental ABIEncoderV2;
// File: 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) {
// 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);
}
}
}
}
// File: 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 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: 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: 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: IERC721Receiver.sol
/**
* @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: Math.sol
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
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: ERC20.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 is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: IERC721.sol
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transfered 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: 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: BaseStrategy.sol
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
/**
* This interface is here for the keeper bot to use.
*/
interface StrategyAPI {
function name() external view returns (string memory);
function vault() external view returns (address);
function want() external view returns (address);
function apiVersion() external pure returns (string memory);
function keeper() external view returns (address);
function isActive() external view returns (bool);
function delegatedAssets() external view returns (uint256);
function estimatedTotalAssets() external view returns (uint256);
function tendTrigger(uint256 callCost) external view returns (bool);
function tend() external;
function harvestTrigger(uint256 callCost) external view returns (bool);
function harvest() external;
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
}
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
abstract contract BaseStrategyInitializable is BaseStrategy {
bool public isOriginal = true;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function clone(address _vault) external returns (address) {
require(isOriginal, "!clone");
return this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
}
// File: Mph.sol
interface IVesting {
struct Vest {
address pool;
uint64 depositID;
uint64 lastUpdateTimestamp;
uint256 accumulatedAmount;
uint256 withdrawnAmount;
uint256 vestAmountPerStablecoinPerSecond;
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) external;
function depositIDToVestID(address _owner, uint64 _depositId)
external
view
returns (uint64 _vestId);
function getVestWithdrawableAmount(uint64 vestID)
external
view
returns (uint256);
function getVest(uint64 vestID) external view returns (Vest memory);
function withdraw(uint64 vestID) external returns (uint256 withdrawnAmount);
function token() external view returns (address);
function ownerOf(uint256 vestId) external view returns (address);
}
interface IMphMinter {
function vesting02() external view returns (address);
}
interface IDInterest {
struct Deposit {
uint256 virtualTokenTotalSupply; // depositAmount + interestAmount, behaves like a zero coupon bond
uint256 interestRate; // interestAmount = interestRate * depositAmount
uint256 feeRate; // feeAmount = feeRate * depositAmount
uint256 averageRecordedIncomeIndex; // Average income index at time of deposit, used for computing deposit surplus
uint64 maturationTimestamp; // Unix timestamp after which the deposit may be withdrawn, in seconds
uint64 fundingID; // The ID of the associated Funding struct. 0 if not funded.
}
function feeModel() external view returns (address);
function mphMinter() external view returns (address);
function stablecoin() external view returns (address);
function depositNFT() external view returns (address);
/**
@notice Create a deposit using `depositAmount` stablecoin that matures at timestamp `maturationTimestamp`.
@dev The ERC-721 NFT representing deposit ownership is given to msg.sender
@param depositAmount The amount of deposit, in stablecoin
@param maturationTimestamp The Unix timestamp of maturation, in seconds
@return depositID The ID of the created deposit
@return interestAmount The amount of fixed-rate interest
*/
function deposit(uint256 depositAmount, uint64 maturationTimestamp)
external
returns (uint64 depositID, uint256 interestAmount);
/**
@notice Create a deposit using `depositAmount` stablecoin that matures at timestamp `maturationTimestamp`.
@dev The ERC-721 NFT representing deposit ownership is given to msg.sender
@param depositAmount The amount of deposit, in stablecoin
@param maturationTimestamp The Unix timestamp of maturation, in seconds
@param minimumInterestAmount If the interest amount is less than this, revert
@param uri The metadata URI for the minted NFT
@return depositID The ID of the created deposit
@return interestAmount The amount of fixed-rate interest
*/
function deposit(
uint256 depositAmount,
uint64 maturationTimestamp,
uint256 minimumInterestAmount,
string calldata uri
) external returns (uint64 depositID, uint256 interestAmount);
/**
@notice Add `depositAmount` stablecoin to the existing deposit with ID `depositID`.
@dev The interest rate for the topped up funds will be the current oracle rate.
@param depositID The deposit to top up
@param depositAmount The amount to top up, in stablecoin
@return interestAmount The amount of interest that will be earned by the topped up funds at maturation
*/
function topupDeposit(uint64 depositID, uint256 depositAmount)
external
returns (uint256 interestAmount);
/**
@notice Add `depositAmount` stablecoin to the existing deposit with ID `depositID`.
@dev The interest rate for the topped up funds will be the current oracle rate.
@param depositID The deposit to top up
@param depositAmount The amount to top up, in stablecoin
@param minimumInterestAmount If the interest amount is less than this, revert
@return interestAmount The amount of interest that will be earned by the topped up funds at maturation
*/
function topupDeposit(
uint64 depositID,
uint256 depositAmount,
uint256 minimumInterestAmount
) external returns (uint256 interestAmount);
/**
@notice Withdraw all funds from deposit with ID `depositID` and use them
to create a new deposit that matures at time `maturationTimestamp`
@param depositID The deposit to roll over
@param maturationTimestamp The Unix timestamp of the new deposit, in seconds
@return newDepositID The ID of the new deposit
*/
function rolloverDeposit(uint64 depositID, uint64 maturationTimestamp)
external
returns (uint256 newDepositID, uint256 interestAmount);
/**
@notice Withdraw all funds from deposit with ID `depositID` and use them
to create a new deposit that matures at time `maturationTimestamp`
@param depositID The deposit to roll over
@param maturationTimestamp The Unix timestamp of the new deposit, in seconds
@param minimumInterestAmount If the interest amount is less than this, revert
@param uri The metadata URI of the NFT
@return newDepositID The ID of the new deposit
*/
function rolloverDeposit(
uint64 depositID,
uint64 maturationTimestamp,
uint256 minimumInterestAmount,
string calldata uri
) external returns (uint256 newDepositID, uint256 interestAmount);
/**
@notice Withdraws funds from the deposit with ID `depositID`.
@dev Virtual tokens behave like zero coupon bonds, after maturation withdrawing 1 virtual token
yields 1 stablecoin. The total supply is given by deposit.virtualTokenTotalSupply
@param depositID the deposit to withdraw from
@param virtualTokenAmount the amount of virtual tokens to withdraw
@param early True if intend to withdraw before maturation, false otherwise
@return withdrawnStablecoinAmount the amount of stablecoins withdrawn
NOTE: @param virtualTokenAmount when premature amount takes into account the interest already. If you want to withdraw 10k amount,
you must input 10,000 * interest amount. When mature, request exact amount 10k.
*/
function withdraw(
uint64 depositID,
uint256 virtualTokenAmount,
bool early
) external returns (uint256 withdrawnStablecoinAmount);
/**
@notice Returns the Deposit struct associated with the deposit with ID
`depositID`.
@param depositID The ID of the deposit
@return The deposit struct
*/
function getDeposit(uint64 depositID)
external
view
returns (Deposit memory);
/**
@notice Computes the amount of fixed-rate interest (before fees) that
will be given to a deposit of `depositAmount` stablecoins that
matures in `depositPeriodInSeconds` seconds.
@param depositAmount The deposit amount, in stablecoins
@param depositPeriodInSeconds The deposit period, in seconds
@return interestAmount The amount of fixed-rate interest (before fees)
*/
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds
) external returns (uint256 interestAmount);
}
// xMPH.sol
interface IStake is IERC20 {
/**
@notice Deposit MPH to get xMPH
@dev The amount can't be 0
@param _mphAmount The amount of MPH to deposit
@return shareAmount The amount of xMPH minted
*/
function deposit(uint256 _mphAmount) external returns (uint256 shareAmount);
/**
@notice Withdraw MPH using xMPH
@dev The amount can't be 0
@param _shareAmount The amount of xMPH to burn
@return mphAmount The amount of MPH withdrawn
*/
function withdraw(uint256 _shareAmount)
external
returns (uint256 mphAmount);
function getPricePerFullShare() external view returns (uint256);
}
interface INft {
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) external;
function contractURI() external view returns (string memory);
function setTokenURI(uint256 tokenId, string calldata newURI) external;
}
interface INftDescriptor {
struct URIParams {
uint256 tokenId;
address owner;
string name;
string symbol;
}
function constructTokenURI(URIParams memory params)
external
pure
returns (string memory);
}
// File: Strategy.sol
// Feel free to change the license, but this is what we use
// Feel free to change this version of Solidity. We support >=0.6.0 <0.7.0;
// These are the core Yearn libraries
interface ITradeFactory {
function enable(address, address) external;
function disable(address, address) external;
}
interface IPercentageFeeModel {
function getEarlyWithdrawFeeAmount(
address pool,
uint64 depositID,
uint256 withdrawnDepositAmount
) external view returns (uint256 feeAmount);
}
contract Strategy is BaseStrategy, IERC721Receiver {
string internal strategyName;
// deposit position nft
INft public depositNft;
// primary interface for entering/exiting protocol
IDInterest public pool;
// nft for redeeming mph that vests linearly
IVesting public vestNft;
bytes internal constant DEPOSIT = "deposit";
bytes internal constant VEST = "vest";
uint64 public depositId;
uint64 public maturationPeriod;
address public oldStrategy;
// Decimal precision for withdraws
uint256 public minWithdraw;
bool public allowEarlyWithdrawFee;
uint256 internal constant basisMax = 10000;
IERC20 public reward;
uint256 private constant max = type(uint256).max;
address public keep;
uint256 public keepBips;
ITradeFactory public tradeFactory;
constructor(
address _vault,
address _pool,
string memory _strategyName
)
public BaseStrategy(_vault) {
_initializeStrat(_vault, _pool, _strategyName);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _pool,
string memory _strategyName
) external {
_initialize(_vault, _strategist, _rewards, _keeper);
_initializeStrat(_vault, _pool, _strategyName);
}
function _initializeStrat(
address _vault,
address _pool,
string memory _strategyName
) internal {
strategyName = _strategyName;
pool = IDInterest(_pool);
require(address(want) == pool.stablecoin(), "Wrong pool!");
vestNft = IVesting(IMphMinter(pool.mphMinter()).vesting02());
reward = IERC20(vestNft.token());
depositNft = INft(pool.depositNFT());
healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012);
// default 5 days
maturationPeriod = 5 * 24 * 60 * 60;
want.safeApprove(address(pool), max);
// 0% to chad by default
keep = governance();
keepBips = 0;
}
// VAULT OPERATIONS //
function name() external view override returns (string memory) {
return strategyName;
}
// fixed rate interest only unlocks after deposit has matured
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(balanceOfPooled());
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
uint256 totalAssets = estimatedTotalAssets();
_profit = totalAssets > totalDebt ? totalAssets.sub(totalDebt) : 0;
uint256 freed;
if (hasMatured()) {
freed = liquidateAllPositions();
_loss = _debtOutstanding > freed ? _debtOutstanding.sub(freed) : 0;
} else {
uint256 toLiquidate = _debtOutstanding.add(_profit);
if (toLiquidate > 0) {
(freed, _loss) = liquidatePosition(toLiquidate);
}
}
_debtPayment = Math.min(_debtOutstanding, freed);
// net out PnL
if (_profit > _loss) {
_profit = _profit.sub(_loss);
_loss = 0;
} else {
_loss = _loss.sub(_profit);
_profit = 0;
}
if (hasMatured()) {
depositId = 0;
}
}
// claim vested mph, pool loose wants
function adjustPosition(uint256 _debtOutstanding) internal override {
_claim();
_invest();
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
if (_amountNeeded > 0) {
uint256 loose = balanceOfWant();
if (_amountNeeded > loose) {
uint256 toExitAmount = _amountNeeded.sub(loose);
IDInterest.Deposit memory depositInfo = getDepositInfo();
uint256 toExitVirtualAmount =
toExitAmount.mul(depositInfo.interestRate.add(1e18)).div(
1e18
);
_poolWithdraw(toExitVirtualAmount);
_liquidatedAmount = Math.min(balanceOfWant(), _amountNeeded);
_loss = _amountNeeded.sub(_liquidatedAmount);
} else {
_liquidatedAmount = _amountNeeded;
_loss = 0;
}
}
}
// exit everything
function liquidateAllPositions() internal override returns (uint256) {
IDInterest.Deposit memory depositInfo = getDepositInfo();
_poolWithdraw(depositInfo.virtualTokenTotalSupply);
return balanceOfWant();
}
// transfer both nfts to new strategy
function prepareMigration(address _newStrategy) internal override {
depositNft.safeTransferFrom(
address(this),
_newStrategy,
depositId,
DEPOSIT
);
vestNft.safeTransferFrom(address(this), _newStrategy, vestId(), VEST);
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
function ethToWant(uint256 _amtInWei)
public
view
virtual
override
returns (uint256)
{
return 0;
}
// INTERNAL OPERATIONS //
function closeEpoch() external onlyEmergencyAuthorized {
_closeEpoch();
}
function _closeEpoch() internal {
liquidateAllPositions();
}
function invest() external onlyVaultManagers {
_invest();
}
// pool wants
function _invest() internal {
uint256 loose = balanceOfWant();
if (depositId != 0) {
// top up the current deposit aka add more loose to the depositNft position.
// If matured, no action
if (loose > 0 && !hasMatured()) {
uint256 timeLeft = uint256(getDepositInfo().maturationTimestamp).sub(now);
uint256 futureInterest = pool.calculateInterestAmount(loose, timeLeft);
if (futureInterest > 0) {
pool.topupDeposit(depositId, loose);
}
}
} else {
// if loose amount is too small to generate interest due to loss of precision, deposits will revert
uint256 futureInterest = pool.calculateInterestAmount(loose, maturationPeriod);
// if there's no depositId, we haven't opened a position yet
if (loose > 0 && futureInterest > 0) {
// open a position with a fixed period. Fixed-rate yield can be collected after this period.
(depositId,) = pool.deposit(
loose,
uint64(now + maturationPeriod)
);
}
}
}
function claim() external onlyVaultManagers {
_claim();
}
// claim mph. Make sure this always happens before _pool(), otherwise old depositId's rewards could be lost
function _claim() internal {
uint256 _rewardBalanceBeforeClaim = balanceOfReward();
if (depositId != 0 && balanceOfClaimableReward() > 0) {
vestNft.withdraw(vestId());
uint256 _rewardAmountToKeep =
balanceOfReward()
.sub(_rewardBalanceBeforeClaim)
.mul(keepBips)
.div(basisMax);
if (_rewardAmountToKeep > 0) {
reward.safeTransfer(keep, _rewardAmountToKeep);
}
}
}
function poolWithdraw(uint256 _virtualAmount) external onlyVaultManagers {
_poolWithdraw(_virtualAmount);
}
// withdraw from pool.
function _poolWithdraw(uint256 _virtualAmount) internal {
// if early withdraw and we don't allow fees, enforce that there's no fees.
// This makes sure that we don't get tricked by MPH with empty promises of waived fees.
// Otherwise we can lose some principal
if (!hasMatured() && !allowEarlyWithdrawFee) {
require(getEarlyWithdrawFee() == 0, "!free");
}
// ensure that withdraw amount is more than minWithdraw amount, otherwise some protocols will revert
if (_virtualAmount > minWithdraw) {
// +1 bc of rounding error sometimes exiting 1 wei less
_virtualAmount = Math.min(_virtualAmount.add(1), getDepositInfo().virtualTokenTotalSupply);
pool.withdraw(depositId, _virtualAmount, !hasMatured());
}
}
function overrideDepositId(uint64 _id) external onlyVaultManagers {
depositId = _id;
}
// HELPERS //
// virtualTokenTotalSupply = deposit + fixed-rate interest. Before maturation, the fixed-rate interest is not withdrawable
function balanceOfPooled() public view returns (uint256 _amount) {
if (depositId != 0) {
uint256 depositWithInterest =
getDepositInfo().virtualTokenTotalSupply;
uint256 interestRate = getDepositInfo().interestRate;
uint256 depositWithoutInterest =
depositWithInterest.mul(1e18).div(interestRate.add(1e18));
return hasMatured() ? depositWithInterest : depositWithoutInterest;
}
}
function balanceOfWant() public view returns (uint256 _amount) {
return want.balanceOf(address(this));
}
function balanceOfReward() public view returns (uint256 _amount) {
return reward.balanceOf(address(this));
}
function balanceOfClaimableReward() public view returns (uint256 _amount) {
return vestNft.getVestWithdrawableAmount(vestId());
}
function getDepositInfo()
public
view
returns (IDInterest.Deposit memory _deposit)
{
return pool.getDeposit(depositId);
}
function getVest() public view returns (IVesting.Vest memory _vest) {
return vestNft.getVest(vestId());
}
function hasMatured() public view returns (bool) {
return
depositId != 0 ? now > getDepositInfo().maturationTimestamp : false;
}
function vestId() public view returns (uint64 _vestId) {
return vestNft.depositIDToVestID(address(pool), depositId);
}
// fee on full withdrawal
function getEarlyWithdrawFee() public view returns (uint256 _feeAmount) {
return
IPercentageFeeModel(pool.feeModel()).getEarlyWithdrawFeeAmount(
address(pool),
depositId,
estimatedTotalAssets()
);
}
// SETTERS //
function setTradeFactory(address _tradeFactory) public onlyGovernance {
_setTradeFactory(_tradeFactory);
}
function _setTradeFactory(address _tradeFactory) internal {
tradeFactory = ITradeFactory(_tradeFactory);
reward.safeApprove(address(tradeFactory), max);
tradeFactory.enable(address(reward), address(want));
}
function disableTradeFactory() public onlyVaultManagers {
_disableTradeFactory();
}
function _disableTradeFactory() internal {
delete tradeFactory;
reward.safeApprove(address(tradeFactory), 0);
tradeFactory.disable(address(reward), address(want));
}
function setMaturationPeriod(uint64 _maturationUnix)
public
onlyVaultManagers
{
// minimum 1 day
require(_maturationUnix > 24 * 60 * 60);
maturationPeriod = _maturationUnix;
}
// For migration. This acts as a password so random nft drops won't mess up the depositId
function setOldStrategy(address _oldStrategy) public onlyVaultManagers {
oldStrategy = _oldStrategy;
}
// Some protocol pools enforce a minimum amount withdraw, like cTokens w/ different decimal places.
function setMinWithdraw(uint256 _minWithdraw) public onlyVaultManagers {
minWithdraw = _minWithdraw;
}
function setAllowWithdrawFee(bool _allow) public onlyVaultManagers {
allowEarlyWithdrawFee = _allow;
}
function setKeepParams(address _keep, uint256 _keepBips)
external
onlyGovernance
{
require(keepBips <= basisMax);
keep = _keep;
keepBips = _keepBips;
}
// only receive nft from oldStrategy otherwise, random nfts will mess up the depositId
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
if (
msg.sender == address(depositNft) &&
from == oldStrategy &&
keccak256(data) == keccak256(DEPOSIT)
) {
depositId = uint64(tokenId);
}
return IERC721Receiver.onERC721Received.selector;
}
receive() external payable {}
} | transfer both nfts to new strategy | function prepareMigration(address _newStrategy) internal override {
depositNft.safeTransferFrom(
address(this),
_newStrategy,
depositId,
DEPOSIT
);
vestNft.safeTransferFrom(address(this), _newStrategy, vestId(), VEST);
}
| 1,465,194 |
pragma solidity 0.5.16;
import "./math/SafeMath.sol";
import "./ownership/Ownable.sol";
import "./token/ERC721/ERC721Mintable.sol";
import "./token/ERC721/ERC721Full.sol";
/**
* @title EtherPet Token
* @dev Simple ERC721 token example
*/
contract EtherPetToken is ERC721, ERC721Enumerable, ERC721Mintable, Ownable {
using SafeMath for uint256;
event NewEntity(uint entityId, string name, uint dna);
event Withdrawn(uint256 weiAmount);
string public constant name = "EtherPet";
string public constant symbol = "EP";
uint8 public constant decimals = 0;
uint dnaDigits = 16;
uint dnaModulus = 10 ** dnaDigits;
uint256 private randomEntityPrice = 1000000000000000;
// Entity structure
struct Entity {
string name;
uint256 dna;
// You can add your own parameters here
}
// entities data
Entity[] public entities;
/**
* @dev Get entity name
* @param _entityId Entity Id
* @return name of an entity
*/
function getEntityName(uint256 _entityId) public view returns(string memory) {
Entity memory _entity = entities[_entityId];
return _entity.name;
}
/**
* @dev Get entity DNA
* @param _entityId Entity Id
* @return DNA of an entity
*/
function getEntityDNA(uint256 _entityId) public view returns(uint256) {
Entity memory _entity = entities[_entityId];
return _entity.dna;
}
/**
* @dev Buy random entity
* @param _name Entity Name
*/
function buyRandomEntity(string calldata _name) external payable {
// User should pay sufficient amount of funds and no more than that
require(msg.value == randomEntityPrice);
uint randDna = _generateRandomDna(_name);
randDna = randDna - randDna % 100;
_createEntity(msg.sender, _name, randDna);
}
/**
* @dev Grant random entity (can be used only by owner of contract)
* @param _entityOwner Entity Owner
* @param _name Entity Name
*/
function grantRandomEntity(address _entityOwner, string calldata _name) external onlyOwner {
uint randDna = _generateRandomDna(_name);
randDna = randDna - randDna % 100;
_createEntity(_entityOwner, _name, randDna);
}
/**
* @dev Create random entity, if sender doesn't have any entities
* @param _name Entity Name
*/
function createFreeRandomEntity(string calldata _name) external {
// Only first entity is free
require(balanceOf(msg.sender) == 0);
uint randDna = _generateRandomDna(_name);
randDna = randDna - randDna % 100;
_createEntity(msg.sender, _name, randDna);
}
/**
* @dev Create a new entity
* @param _entityOwner Entity Owner
* @param _name Entity Name
* @param _dna Entity DNA
*/
function _createEntity(address _entityOwner, string memory _name, uint256 _dna) internal {
uint entityId = entities.push(Entity(_name, _dna)) - 1;
_mint(_entityOwner, entityId);
emit NewEntity(entityId, _name, _dna);
}
/**
* @dev Generate random DNA for the entity
* @param _name Entity Name
* @return randomDNA Random DNA of a entity
*/
function _generateRandomDna(string memory _name) private view returns (uint256) {
uint256 rand = uint256(keccak256(abi.encode(_name)));
return rand % dnaModulus;
}
/**
* @dev Get price of the random entity
* @return randomEntityPrice random entity price in Wei
*/
function getRandomEntityPrice() public view returns(uint256) {
return randomEntityPrice;
}
/**
* @dev Set random entity price in Wei
* @param _price New Price
*/
function setRandomEntityPrice(uint256 _price) external onlyOwner {
randomEntityPrice = _price;
}
/**
* @dev Withdrawn funds from selling random entities, to the owner of a contract
*/
function withdrawFunds() external onlyOwner {
uint256 balance = address(this).balance;
address payable ownerPayableAddress = ownerPayable();
ownerPayableAddress.transfer(address(this).balance);
emit Withdrawn(balance);
}
}
| Create a new entity _entityOwner Entity Owner _name Entity Name _dna Entity DNA/ | function _createEntity(address _entityOwner, string memory _name, uint256 _dna) internal {
uint entityId = entities.push(Entity(_name, _dna)) - 1;
_mint(_entityOwner, entityId);
emit NewEntity(entityId, _name, _dna);
}
| 5,356,849 |
./full_match/1/0x0f08eEf2C785AA5e7539684aF04755dEC1347b7c/sources/contracts/gauges/StakelessGaugeCheckpointer.sol | Performs checkpoint for non-Arbitrum gauge; does not forward any ETH./ | function _checkpointCostlessBridgeGauge(address gauge) private {
_authorizerAdaptorEntrypoint.performAction(gauge, abi.encodeWithSelector(IStakelessGauge.checkpoint.selector));
}
| 17,154,159 |
./partial_match/3/0xb77421fc64a2a0db4dd53c9bE41713FB29e42a3A/sources/EdgeXToken.sol | Requirements: - `target` must be a contract. - calling `target` with `data` must not revert. _Available since v3.1._/ | highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Call Failed");
}
| 5,235,282 |
//author: 谛听
// File: localhost/contracts/interfaces/IOKra.sol
pragma solidity >=0.5.0;
interface IOKra {
function mint(address _to, uint256 _amount) external returns (uint);
function balanceOf(address owner) external view returns (uint);
}
// File: localhost/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
event Harvest(address indexed sender, uint amount);
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,address user,bool emerg) external returns (uint amount0, uint amount1);
function swap(uint[3] memory amount, address to, bytes calldata data) external;
function skim(address to) external;
function pending(address user) external view returns (uint);
function harvestNow(address to) external;
function sync() external;
function initialize(address, address,address) external;
}
// File: localhost/contracts/interfaces/IUniswapV2Callee.sol
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// File: localhost/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IERC20Uniswap {
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: localhost/contracts/libraries/UQ112x112.sol
pragma solidity =0.6.12;
// 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: localhost/contracts/libraries/Math.sol
pragma solidity =0.6.12;
// 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: localhost/contracts/interfaces/IUniswapV2ERC20.sol
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// File: localhost/contracts/libraries/SafeMath.sol
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
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');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'ds-math-div-overflow');
uint256 c = a / b;
return c;
}
}
// File: localhost/contracts/OKSwapERC20.sol
pragma solidity =0.6.12;
contract OKSwapERC20 is IUniswapV2ERC20 {
using SafeMathUniswap for uint;
string public override constant name = 'OKSwap LPT';
string public override constant symbol = 'OKLP';
uint8 public override constant decimals = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public override 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 override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override 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 override {
require(deadline >= block.timestamp, 'OKSwapERC20: 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, 'OKSwapERC20: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// File: localhost/contracts/OKSwapPair.sol
pragma solidity =0.6.12;
contract OKSwapPair is OKSwapERC20 {
address public okra;
using SafeMathUniswap for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10 ** 3;
uint public constant BONUS_BLOCKNUM = 36000;
uint public constant BASECAP = 5120 * (10 ** 18);
uint public constant TEAM_BLOCKNUM = 13200000;
uint private constant TEAM_CAP = 15000000 * (10 ** 18);
uint private constant VC_CAP = 5000000 * (10 ** 18);
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
mapping(address => uint) public userPools;
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'OKSwap: 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))), 'OKSwap: 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);
event Harvest(address indexed sender, uint amount);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1, address _okra) external {
require(msg.sender == factory, 'OKSwap: FORBIDDEN');
// sufficient check
token0 = _token0;
token1 = _token1;
okra = _okra;
}
// 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), 'OKSwap: 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 = IOkswapFactory(factory).feeTo();
(,,,address feeHolder,address burnHolder,) = IOkswapFactory(factory).getBonusConfig(address(this));
feeOn = true;
uint _kLast = kLast;
// gas savings
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.mul(2) / denominator;
if (liquidity > 0) {
if (feeHolder != address(0)) _mint(feeHolder, liquidity);
if (burnHolder != address(0)) _mint(burnHolder, liquidity);
}
}
}
}
// 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();
uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));
uint balance1 = IERC20Uniswap(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);
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'OKSwap: INSUFFICIENT_LIQUIDITY_MINTED');
if (IOkswapFactory(factory).isBonusPair(address(this))) {
uint startAtBlock = userPools[to];
if (startAtBlock > 0) {
uint liquid = balanceOf[to];
userPools[to] = startAtBlock.mul(liquid).add(block.number.mul(liquidity)) / liquid.add(liquidity);
}else{
userPools[to] = block.number;
}
}
_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,address user,bool emerg) 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 = IERC20Uniswap(_token0).balanceOf(address(this));
uint balance1 = IERC20Uniswap(_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;
amount1 = liquidity.mul(balance1) / _totalSupply;
// using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'OKSwap: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1);
// reserve0 and reserve1 are up-to-date
if (!emerg) _getHarvest(user);
emit Burn(msg.sender, amount0, amount1, to);
}
function _getHarvest(address _to) private {
(uint based,,,,,) = IOkswapFactory(factory).getBonusConfig(address(this));
if (based > 0 ) {
uint harvestLiquid = balanceOf[_to];
uint pendingAmount = _getHarvestAmount(harvestLiquid, based, userPools[_to]);
uint max = BASECAP + IOKra(okra).balanceOf(_to);
uint mintAmount = pendingAmount <= max ? pendingAmount : max;
userPools[_to] = block.number;
IOkswapFactory(factory).realize(_to, mintAmount);
emit Harvest(msg.sender, mintAmount);
}
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint[3] memory amount, address to, bytes calldata data) external lock {
uint amount0Out = amount[0];
uint amount1Out = amount[1];
uint amountIn = amount[2];
require(amount0Out > 0 || amount1Out > 0, 'OKSwap: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves();
// gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'OKSwap: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{// scope for _token{0,1}, avoids stack too deep errors
require(to != token0 && to != token1, 'OKSwap: INVALID_TO');
if (amount0Out > 0) {_safeTransfer(token0, to, amount0Out);assign(amount0Out,token1,token0,amountIn,to);}
if (amount1Out > 0) {_safeTransfer(token1, to, amount1Out);assign(amount1Out,token0,token1,amountIn,to);}
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20Uniswap(token0).balanceOf(address(this));
balance1 = IERC20Uniswap(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, 'OKSwap: 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), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
function assign(uint amountOut,address tokenIn, address tokenOut, uint amountIn, address to) private {
(,,address tokenAddress,,,) = IOkswapFactory(factory).getBonusConfig(address(this));
if (tokenAddress == tokenIn) {
_tradeBonus(tokenIn, amountIn, to);
}else if (tokenAddress == tokenOut) {
_tradeBonus(tokenIn, amountOut, to);
}
}
function _tradeBonus(address _token, uint _amountOut, address _to) private {
IOkswapFactory _factory = IOkswapFactory(factory);
if (_token != address(okra) && _factory.isBonusPair(address(this))) {
uint sysCf = _factory.getSysCf();
(uint elac0,uint elac1) = IOkswapFactory(factory).getElac();
(,uint share, ,address teamHolder,,address vcHolder) = _factory.getBonusConfig(address(this));
uint tradeMint = _amountOut.div(100).mul(share).div(sysCf);
tradeMint = tradeMint.mul(elac0).div(elac1);
_realize(tradeMint,_to,teamHolder,vcHolder);
}
}
function _realize(uint tradeMint,address _to,address teamHolder,address vcHolder) private {
if (tradeMint > 0) {
IOkswapFactory(factory).realize(_to, tradeMint);
uint syncMint = tradeMint.div(100).mul(2);
uint vcNum = IOkswapFactory(factory).vcAmount();
uint vcMint = vcNum.add(syncMint) >= VC_CAP ? VC_CAP.sub(vcNum) : syncMint;
if (vcMint > 0 && vcHolder != address(0)) {
IOkswapFactory(factory).updateVcAmount(vcMint);
IOkswapFactory(factory).realize(vcHolder, vcMint);
}
if (block.number >= TEAM_BLOCKNUM) {
uint teamNum = IOkswapFactory(factory).teamAmount();
syncMint = syncMint.mul(3);
uint teamMint = teamNum.add(syncMint) >= TEAM_CAP ? TEAM_CAP.sub(teamNum) : syncMint;
if (teamMint > 0 && teamHolder != address(0)){
IOkswapFactory(factory).updateTeamAmount(teamMint);
IOkswapFactory(factory).realize(teamHolder, teamMint);
}
}
emit Harvest(msg.sender, tradeMint);
}
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0;
address _token1 = token1;
_safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1));
}
function _getHarvestAmount(uint _amount, uint _based, uint _startBlock) private view returns (uint){
uint sysCf = IOkswapFactory(factory).getSysCf();
(uint elac0,uint elac1) = IOkswapFactory(factory).getElac();
uint point = (block.number.sub(_startBlock)) / BONUS_BLOCKNUM;
uint mintAmount;
if (point == 0) {
mintAmount = _amount.mul(block.number.sub(_startBlock));
} else if (point == 1) {
uint amount0 = _amount.mul(BONUS_BLOCKNUM);
uint amount1 = _amount.mul(block.number.sub(_startBlock).sub(BONUS_BLOCKNUM));
mintAmount = amount0.add(amount1.mul(2));
} else {
uint amount0 = _amount.mul(BONUS_BLOCKNUM);
uint amount1 = _amount.mul(block.number.sub(_startBlock).sub(BONUS_BLOCKNUM).sub(BONUS_BLOCKNUM));
mintAmount = amount0.add(amount0.mul(2)).add(amount1.mul(3));
}
return mintAmount.mul(elac0).div(elac1).div(sysCf).mul(100).div(_based);
}
function getblock(address _user) external view returns (uint256){
return userPools[_user];
}
function pending(address _user) external view returns (uint256) {
(uint _based,,,,,) = IOkswapFactory(factory).getBonusConfig(address(this));
uint sysCf = IOkswapFactory(factory).getSysCf();
(uint elac0,uint elac1) = IOkswapFactory(factory).getElac();
uint _startBlock = userPools[_user];
uint _amount = balanceOf[_user];
require(block.number >= _startBlock, "OKSwap:FAIL");
uint point = (block.number.sub(_startBlock)) / BONUS_BLOCKNUM;
uint mintAmount;
if (point == 0) {
mintAmount = _amount.mul(block.number.sub(_startBlock));
} else if (point == 1) {
uint amount0 = _amount.mul(BONUS_BLOCKNUM);
uint amount1 = _amount.mul(block.number.sub(_startBlock).sub(BONUS_BLOCKNUM));
mintAmount = amount0.add(amount1.mul(2));
} else {
uint amount0 = _amount.mul(BONUS_BLOCKNUM);
uint amount1 = _amount.mul(block.number.sub(_startBlock).sub(BONUS_BLOCKNUM).sub(BONUS_BLOCKNUM));
mintAmount = amount0.add(amount0.mul(2)).add(amount1.mul(3));
}
return mintAmount.mul(elac0).div(elac1).div(sysCf).mul(100).div(_based);
}
function harvestNow() external {
address _to = msg.sender;
(uint based,,,,, ) = IOkswapFactory(factory).getBonusConfig(address(this));
require(based > 0, 'OKSwap: FAIL_BASED');
uint _amount = balanceOf[_to];
uint pendingAmount = _getHarvestAmount(_amount, based, userPools[_to]);
uint max = BASECAP + IOKra(okra).balanceOf(_to);
uint mintAmount = pendingAmount <= max ? pendingAmount : max;
userPools[_to] = block.number;
IOkswapFactory(factory).realize(_to, mintAmount);
emit Harvest(msg.sender, mintAmount);
}
// force reserves to match balances
function sync() external lock {
_update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
// File: localhost/contracts/interfaces/IOkswapFactory.sol
pragma solidity >=0.5.0;
interface IOkswapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function teamAmount() external view returns (uint);
function vcAmount() external view returns (uint);
function isBonusPair(address) external view returns (bool);
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 changeSetter(address) external;
function setFeeHolder(address) external;
function setBurnHolder(address) external;
function setVcHolder(address) external;
function pairCodeHash() external pure returns (bytes32);
function addBonusPair(uint, uint, address, address, bool) external ;
function getBonusConfig(address) external view returns (uint, uint,address,address,address,address);
function getElac() external view returns (uint, uint);
function setElac(uint,uint) external;
function updateTeamAmount(uint) external;
function updateVcAmount(uint) external;
function realize(address,uint) external;
function getSysCf() external view returns (uint);
}
// File: localhost/contracts/OKSwapFactory.sol
pragma solidity =0.6.12;
contract OKSwapFactory is IOkswapFactory {
address private setter;
uint public startBlock;
address public okra;
address public feeHolder;
address public burnHolder;
address public vcHolder;
address public elacSetter;
uint public override teamAmount;
uint public override vcAmount;
uint private elac0;
uint private elac1;
mapping(address => mapping(address => address)) public override getPair;
address[] public override allPairs;
mapping(address => bool) public override isBonusPair;
struct mintPair {
uint32 based;
uint8 share;
address token;
}
mapping(address => mintPair) public mintPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address _setter,address _okra) public {
setter = _setter;
startBlock = block.number;
okra = _okra;
elacSetter = _setter;
elac0 = 1;
elac1 = 1;
}
function allPairsLength() external override view returns (uint) {
return allPairs.length;
}
function pairCodeHash() external override pure returns (bytes32) {
return keccak256(type(OKSwapPair).creationCode);
}
function createPair(address tokenA, address tokenB) external override returns (address pair) {
require(tokenA != tokenB, 'OKSwap: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'OKSwap: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'OKSwap: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(OKSwapPair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
OKSwapPair(pair).initialize(token0, token1,okra);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function changeSetter(address _setter) external override {
require(msg.sender == setter, 'OKSwap: FORBIDDEN');
setter = _setter;
}
function setFeeHolder(address _holder) external override {
require(msg.sender == setter, 'OKSwap: FORBIDDEN');
feeHolder = _holder;
}
function setBurnHolder(address _holder) external override {
require(msg.sender == setter, 'OKSwap: FORBIDDEN');
burnHolder = _holder;
}
function setVcHolder(address _holder) external override {
require(msg.sender == setter, 'OKSwap: FORBIDDEN');
vcHolder = _holder;
}
function setElacContract(address _setter) external {
require(msg.sender == elacSetter, 'OKSwap: FORBIDDEN');
elacSetter = _setter;
}
function getSysCf() external override view returns (uint){
uint cf = (block.number - startBlock) / 512000 ;
return cf <= 0 ? 1 : (2 ** cf);
}
function addBonusPair(uint _based, uint _share, address _pair, address _token, bool _update) external override {
require(msg.sender == setter, "OKSwap: FORBIDDEN");
if (_update) {
require(mintPairs[_pair].token != address(0),"OKSwap: TOKEN");
mintPairs[_pair].based = uint32(_based);
mintPairs[_pair].share = uint8(_share);
mintPairs[_pair].token = _token;
isBonusPair[_pair] = !isBonusPair[_pair];
}
mintPairs[_pair].based = uint32(_based);
mintPairs[_pair].share = uint8(_share);
mintPairs[_pair].token = _token;
isBonusPair[_pair] = true;
}
function getBonusConfig(address _pair) external override view returns (uint _based, uint _share,address _token,address _feeHolder,address _burnHolder,address _vcHolder) {
_based = mintPairs[_pair].based;
_share = mintPairs[_pair].share;
_token = mintPairs[_pair].token;
_feeHolder = feeHolder;
_burnHolder = burnHolder;
_vcHolder = vcHolder;
}
function getElac() external override view returns (uint _elac0, uint _elac1) {
_elac0 = elac0;
_elac1 = elac1;
}
function setElac(uint _elac0,uint _elac1) external override {
require(msg.sender == elacSetter, 'OKSwap: FORBIDDEN');
elac0 = _elac0;
elac1 = _elac1;
}
function updateVcAmount(uint amount) external override {
require(isBonusPair[msg.sender], "OKSwap: FORBIDDEN");
require(amount > 0, "OKSwap: Ops");
vcAmount += amount;
}
function updateTeamAmount(uint amount) external override {
require(isBonusPair[msg.sender], "OKSwap: FORBIDDEN");
require(amount > 0, "OKSwap: Ops");
teamAmount += amount;
}
function realize(address _to,uint amount) external override {
require(isBonusPair[msg.sender], "OKSwap: FORBIDDEN");
IOKra(okra).mint(_to, amount);
}
} | this low-level function should be called from a contract which performs important safety checks gas savings | function swap(uint[3] memory amount, address to, bytes calldata data) external lock {
uint amount0Out = amount[0];
uint amount1Out = amount[1];
uint amountIn = amount[2];
require(amount0Out > 0 || amount1Out > 0, 'OKSwap: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves();
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'OKSwap: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
require(to != token0 && to != token1, 'OKSwap: INVALID_TO');
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20Uniswap(token0).balanceOf(address(this));
balance1 = IERC20Uniswap(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, 'OKSwap: INSUFFICIENT_INPUT_AMOUNT');
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), 'UniswapV2: K');
| 171,320 |
pragma solidity ^0.4.15;
interface TokenInterface {
function mint(address _to, uint256 _amount) public returns (bool);
function finishMinting() public returns (bool);
function totalSupply() public constant returns (uint);
function balanceOf(address _address) public constant returns (uint);
function burn(address burner);
function hold(address addr, uint duration) external;
function transfer(address _to, uint _amount) external;
function contributeTo(address _to, uint256 _amount) public;
}
interface VotingFactoryInterface {
function createRegular(address _creator, string _name, string _description, uint _duration, bytes32[] _options) external returns (address);
function createWithdrawal(address _creator, string _name, string _description, uint _duration, uint _sum, address withdrawalWallet, bool _dxc) external returns (address);
function createRefund(address _creator, string _name, string _description, uint _duration) external returns (address);
function createModule(address _creator, string _name, string _description, uint _duration, uint _module, address _newAddress) external returns (address);
function setDaoFactory(address _dao) external;
}
library DAOLib {
event VotingCreated(
address voting,
string votingType,
address dao,
string name,
string description,
uint duration,
address sender
);
/*
* @dev Receives parameters from crowdsale module in case of successful crowdsale and processes them
* @param token Instance of token contract
* @param commissionRaised Amount of funds which were sent via commission contract
* @param serviceContract Address of contract which receives commission
* @param teamBonuses Array of percents which indicates the number of token for every team member
* @param team Array of team members' addresses
* @param teamHold Array of timestamp until which the tokens will be held for every team member
* @return uint Amount of tokens minted for team
*/
function handleFinishedCrowdsale(TokenInterface token, uint commissionRaised, address serviceContract, uint[] teamBonuses, address[] team, uint[] teamHold) returns (uint) {
uint commission = (commissionRaised / 100) * 4;
serviceContract.call.gas(200000).value(commission)();
uint totalSupply = token.totalSupply() / 100;
uint teamTokensAmount = 0;
for (uint i = 0; i < team.length; i++) {
uint teamMemberTokensAmount = SafeMath.mul(totalSupply, teamBonuses[i]);
teamTokensAmount += teamMemberTokensAmount;
token.mint(team[i], teamMemberTokensAmount);
token.hold(team[i], teamHold[i]);
}
return teamTokensAmount;
}
function delegatedCreateRegular(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, bytes32[] _options, address _dao) returns (address) {
address _votingAddress = _votingFactory.createRegular(msg.sender, _name, _description, _duration, _options);
VotingCreated(_votingAddress, "Regular", _dao, _name, _description, _duration, msg.sender);
return _votingAddress;
}
function delegatedCreateWithdrawal(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, uint _sum, address withdrawalWallet, bool _dxc, address _dao)
returns (address)
{
address _votingAddress = _votingFactory.createWithdrawal(msg.sender, _name, _description, _duration, _sum, withdrawalWallet, _dxc);
VotingCreated(_votingAddress, "Withdrawal", _dao, _name, _description, _duration, msg.sender);
return _votingAddress;
}
function delegatedCreateRefund(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, address _dao) returns (address) {
address _votingAddress = _votingFactory.createRefund(msg.sender, _name, _description, _duration);
VotingCreated(_votingAddress, "Refund", _dao, _name, _description, _duration, msg.sender);
return _votingAddress;
}
function delegatedCreateModule(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, uint _module, address _newAddress, address _dao) returns (address) {
address _votingAddress = _votingFactory.createModule(msg.sender, _name, _description, _duration, _module, _newAddress);
VotingCreated(_votingAddress, "Module", _dao, _name, _description, _duration, msg.sender);
return _votingAddress;
}
/*
* @dev Counts the number of tokens that should be minted according to amount of sent funds and current rate
* @param value Amount of sent funds
* @param bonusPeriods Array of timestamps indicating bonus periods
* @param bonusRates Array of rates for every bonus period
* @param rate Default rate
* @return uint Amount of tokens that should be minted
*/
function countTokens(uint value, uint[] bonusPeriods, uint[] bonusRates, uint rate) constant returns (uint) {
if (bonusRates.length == 0) return value * rate; // DXC bonus rates could be empty
for (uint i = 0; i < bonusPeriods.length; i++) {
if (now < bonusPeriods[i]) {
rate = bonusRates[i];
break;
}
}
uint tokensAmount = SafeMath.mul(value, rate);
return tokensAmount;
}
/*
* @dev Counts the amount of funds that must be returned to participant
* @param tokensAmount Amount of tokens on participant's balance
* @param etherRate Rate for ether during the crowdsale
* @param newRate Current rate according to left funds and total supply of tokens
* @param multiplier Multiplier that was used in previous calculations to avoid issues with float numbers
* @return uint Amount of funds that must be returned to participant
*/
function countRefundSum(uint tokensAmount, uint etherRate, uint newRate, uint multiplier) constant returns (uint) {
uint fromPercentDivider = 100;
return (tokensAmount / fromPercentDivider * newRate) / (multiplier * etherRate);
}
}
contract CrowdsaleDAOFields {
uint public etherRate;
uint public DXCRate;
uint public softCap;
uint public hardCap;
uint public startTime;
uint public endTime;
bool public canInitCrowdsaleParameters = true;
bool public canInitStateParameters = true;
bool public canInitBonuses = true;
bool public canSetWhiteList = true;
uint public commissionRaised = 0; // Funds which were provided via commission contract
uint public weiRaised = 0;
uint public DXCRaised = 0;
uint public fundsRaised = 0;
mapping(address => uint) public depositedWei; // Used for refund in case of not reached soft cap
mapping(address => uint) public depositedDXC; // Used for refund in case of not reached soft cap
bool public crowdsaleFinished;
bool public refundableSoftCap = false;
uint public newEtherRate = 0; // Used for refund after accept of Refund proposal
uint public newDXCRate = 0; // Used for refund after accept of Refund proposal
address public serviceContract; //Contract which gets commission funds if soft cap was reached during the crowdsale
uint[] public teamBonusesArr;
address[] public team;
mapping(address => bool) public teamMap;
uint[] public teamHold;
bool[] public teamServiceMember;
TokenInterface public token;
VotingFactoryInterface public votingFactory;
address public commissionContract; //Contract that is used to mark funds which were provided through daox.org platform
string public name;
string public description;
uint public created_at = now; // UNIX time
mapping(address => bool) public votings;
bool public refundable = false;
uint public lastWithdrawalTimestamp = 0;
address[] public whiteListArr;
mapping(address => bool) public whiteList;
mapping(address => uint) public teamBonuses;
uint[] public bonusPeriods;
uint[] public bonusEtherRates;
uint[] public bonusDXCRates;
uint public teamTokensAmount;
uint constant internal withdrawalPeriod = 120 * 24 * 60 * 60;
TokenInterface public DXC;
uint public tokensMintedByEther;
uint public tokensMintedByDXC;
bool public dxcPayments; //Flag indicating whether it is possible to invest via DXC token or not
uint internal constant multiplier = 100000;
uint internal constant percentMultiplier = 100;
}
contract Owned {
address public owner;
function Owned(address _owner) {
owner = _owner;
}
function transferOwnership(address newOwner) onlyOwner(msg.sender) {
owner = newOwner;
}
modifier onlyOwner(address _sender) {
require(_sender == owner);
_;
}
}
interface IDAOPayable {
function handleCommissionPayment(address _sender) payable;
}
contract Commission {
IDAOPayable dao;
function Commission(address _dao) {
dao = IDAOPayable(_dao);
}
function() payable {
dao.handleCommissionPayment.value(msg.value)(msg.sender);
}
}
contract State is CrowdsaleDAOFields {
address public owner;
event State(address _comission);
/*
* @dev Sets addresses of token which will be minted during the crowdsale and address of DXC token contract so that
* DAO will be able to handle investments via DXC. Also function creates instance of Commission contract for this DAO
* @param value Amount of sent funds
*/
function initState(address _tokenAddress, address _DXC)
external
onlyOwner(msg.sender)
canInit
crowdsaleNotStarted
{
require(_tokenAddress != 0x0 && _DXC != 0x0);
token = TokenInterface(_tokenAddress);
DXC = TokenInterface(_DXC);
created_at = block.timestamp;
commissionContract = new Commission(this);
canInitStateParameters = false;
State(commissionContract);
}
modifier canInit() {
require(canInitStateParameters);
_;
}
modifier crowdsaleNotStarted() {
require(startTime == 0 || block.timestamp < startTime);
_;
}
modifier onlyOwner(address _sender) {
require(_sender == owner);
_;
}
}
contract Crowdsale is CrowdsaleDAOFields {
address public owner;
/*
* @dev Receives info about ether payment from CrowdsaleDAO contract then mints tokens for sender and saves info about
* sent funds to either return it in case of refund or get commission from them in case of successful crowdsale
* @param _sender Address of sender
* @param _commission Boolean indicating whether it is needed to take commission from sent funds or not
*/
function handlePayment(address _sender, bool _commission) external payable CrowdsaleIsOngoing validEtherPurchase(msg.value) {
require(_sender != 0x0);
uint weiAmount = msg.value;
if (_commission) {
commissionRaised = commissionRaised + weiAmount;
}
weiRaised += weiAmount;
depositedWei[_sender] += weiAmount;
uint tokensAmount = DAOLib.countTokens(weiAmount, bonusPeriods, bonusEtherRates, etherRate);
tokensMintedByEther = SafeMath.add(tokensMintedByEther, tokensAmount);
token.mint(_sender, tokensAmount);
}
/*
* @dev Receives info about DXC payment from CrowdsaleDAO contract then mints tokens for sender and saves info about
* sent funds to return it in case of refund
* @param _from Address of sender
* @param _dxcAmount Amount of DXC token which were sent to DAO
*/
function handleDXCPayment(address _from, uint _dxcAmount) external CrowdsaleIsOngoing validDXCPurchase(_dxcAmount) onlyDXC {
DXCRaised += _dxcAmount;
depositedDXC[_from] += _dxcAmount;
uint tokensAmount = DAOLib.countTokens(_dxcAmount, bonusPeriods, bonusDXCRates, DXCRate);
tokensMintedByDXC = SafeMath.add(tokensMintedByDXC, tokensAmount);
token.mint(_from, tokensAmount);
}
/*
* @dev Sets main parameters for upcoming crowdsale
* @param _softCap The minimal amount of funds that must be collected by DAO for crowdsale to be considered successful
* @param _hardCap The maximal amount of funds that can be raised during the crowdsale
* @param _etherRate Amount of tokens that will be minted per one ether
* @param _DXCRate Amount of tokens that will be minted per one DXC
* @param _startTime Unix timestamp that indicates the moment when crowdsale will start
* @param _endTime Unix timestamp which indicates the moment when crowdsale will end
* @param _dxcPayments Boolean indicating whether it is possible to invest via DXC token or not
*/
function initCrowdsaleParameters(uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments)
external
onlyOwner(msg.sender)
canInit
{
require(_softCap != 0 && _hardCap != 0 && _etherRate != 0 && _DXCRate != 0 && _startTime != 0 && _endTime != 0);
require(_softCap < _hardCap && _startTime > block.timestamp);
softCap = _softCap * 1 ether;
hardCap = _hardCap * 1 ether;
(startTime, endTime) = (_startTime, _endTime);
(dxcPayments, etherRate, DXCRate) = (_dxcPayments, _etherRate, _DXCRate);
canInitCrowdsaleParameters = false;
}
/*
* @dev Finishes the crowdsale and analyzes whether it is successful or not. If it is not then DAO goes to refundableSoftCap
* state otherwise it counts and mints tokens for team members and holds them for certain period of time according to
* parameters which were set for every member via initBonuses function. In addition function sends commission to service contract
*/
function finish() external {
fundsRaised = DXCRate != 0 ? weiRaised + (DXC.balanceOf(this)) / (etherRate / DXCRate) : weiRaised;
require((block.timestamp >= endTime || fundsRaised == hardCap) && !crowdsaleFinished);
crowdsaleFinished = true;
if (fundsRaised >= softCap) {
teamTokensAmount = DAOLib.handleFinishedCrowdsale(token, commissionRaised, serviceContract, teamBonusesArr, team, teamHold);
} else {
refundableSoftCap = true;
}
token.finishMinting();
}
modifier canInit() {
require(canInitCrowdsaleParameters);
_;
}
modifier onlyCommission() {
require(commissionContract == msg.sender);
_;
}
modifier CrowdsaleIsOngoing() {
require(block.timestamp >= startTime && block.timestamp < endTime && !crowdsaleFinished);
_;
}
modifier validEtherPurchase(uint value) {
require(DXCRate != 0 ?
hardCap - DXCRaised / (etherRate / DXCRate) >= weiRaised + value :
hardCap >= weiRaised + value);
_;
}
modifier validDXCPurchase(uint value) {
require(dxcPayments && (hardCap - weiRaised >= (value + DXCRaised) / (etherRate / DXCRate)));
_;
}
modifier onlyDXC() {
require(msg.sender == address(DXC));
_;
}
modifier onlyOwner(address _sender) {
require(_sender == owner);
_;
}
}
contract Payment is CrowdsaleDAOFields {
/*
* @dev Returns funds to participant according to amount of funds that left in DAO and amount of tokens for this participant
*/
function refund() whenRefundable notTeamMember {
uint tokensMintedSum = SafeMath.add(tokensMintedByEther, tokensMintedByDXC);
uint etherPerDXCRate = SafeMath.mul(tokensMintedByEther, percentMultiplier) / tokensMintedSum;
uint dxcPerEtherRate = SafeMath.mul(tokensMintedByDXC, percentMultiplier) / tokensMintedSum;
uint tokensAmount = token.balanceOf(msg.sender);
token.burn(msg.sender);
if (etherPerDXCRate != 0)
msg.sender.transfer(DAOLib.countRefundSum(etherPerDXCRate * tokensAmount, etherRate, newEtherRate, multiplier));
if (dxcPerEtherRate != 0)
DXC.transfer(msg.sender, DAOLib.countRefundSum(dxcPerEtherRate * tokensAmount, DXCRate, newDXCRate, multiplier));
}
/*
* @dev Returns funds which were sent to crowdsale contract back to backer and burns tokens that were minted for him
*/
function refundSoftCap() whenRefundableSoftCap {
require(depositedWei[msg.sender] != 0 || depositedDXC[msg.sender] != 0);
token.burn(msg.sender);
uint weiAmount = depositedWei[msg.sender];
uint tokensAmount = depositedDXC[msg.sender];
delete depositedWei[msg.sender];
delete depositedDXC[msg.sender];
DXC.transfer(msg.sender, tokensAmount);
msg.sender.transfer(weiAmount);
}
modifier whenRefundable() {
require(refundable);
_;
}
modifier whenRefundableSoftCap() {
require(refundableSoftCap);
_;
}
modifier onlyParticipant {
require(token.balanceOf(msg.sender) > 0);
_;
}
modifier notTeamMember() {
require(!teamMap[msg.sender]);
_;
}
}
contract VotingDecisions is CrowdsaleDAOFields {
/*
* @dev Transfers withdrawal sum in ether or DXC tokens to the whitelisted address. Calls from Withdrawal proposal
* @param _address Whitelisted address
* @param _withdrawalSum Amount of ether/DXC to be sent
* @param _dxc Should withdrawal be in DXC tokens
*/
function withdrawal(address _address, uint _withdrawalSum, bool _dxc) notInRefundableState onlyVoting external {
lastWithdrawalTimestamp = block.timestamp;
_dxc ? DXC.transfer(_address, _withdrawalSum) : _address.transfer(_withdrawalSum);
}
/*
* @dev Change DAO's mode to `refundable`. Can be called by any tokenholder
*/
function makeRefundableByUser() external {
require(lastWithdrawalTimestamp == 0 && block.timestamp >= created_at + withdrawalPeriod
|| lastWithdrawalTimestamp != 0 && block.timestamp >= lastWithdrawalTimestamp + withdrawalPeriod);
makeRefundable();
}
/*
* @dev Change DAO's mode to `refundable`. Calls from Refund proposal
*/
function makeRefundableByVotingDecision() external onlyVoting {
makeRefundable();
}
/*
* @dev Change DAO's mode to `refundable`. Calls from this contract `makeRefundableByUser` or `makeRefundableByVotingDecision` functions
*/
function makeRefundable() notInRefundableState private {
refundable = true;
newEtherRate = SafeMath.mul(this.balance * etherRate, multiplier) / tokensMintedByEther;
newDXCRate = tokensMintedByDXC != 0 ? SafeMath.mul(DXC.balanceOf(this) * DXCRate, multiplier) / tokensMintedByDXC : 0;
}
/*
* @dev Make tokens of passed address non-transferable for passed period
* @param _address Address of tokenholder
* @param _duration Hold's duration in seconds
*/
function holdTokens(address _address, uint _duration) onlyVoting external {
token.hold(_address, _duration);
}
/*
* @dev Throws if called not by any voting contract
*/
modifier onlyVoting() {
require(votings[msg.sender]);
_;
}
/*
* @dev Throws if DAO is in refundable state
*/
modifier notInRefundableState {
require(!refundable && !refundableSoftCap);
_;
}
}
interface DAOFactoryInterface {
function exists(address _address) external constant returns (bool);
}
library DAODeployer {
function deployCrowdsaleDAO(string _name, string _description, address _serviceContractAddress, address _votingFactoryContractAddress) returns(CrowdsaleDAO dao) {
dao = new CrowdsaleDAO(_name, _description, _serviceContractAddress, _votingFactoryContractAddress);
}
function transferOwnership(address _dao, address _newOwner) {
CrowdsaleDAO(_dao).transferOwnership(_newOwner);
}
}
library DAOProxy {
function delegatedInitState(address stateModule, address _tokenAddress, address _DXC) {
require(stateModule.delegatecall(bytes4(keccak256("initState(address,address)")), _tokenAddress, _DXC));
}
function delegatedHoldState(address stateModule, uint _tokenHoldTime) {
require(stateModule.delegatecall(bytes4(keccak256("initHold(uint256)")), _tokenHoldTime));
}
function delegatedGetCommissionTokens(address paymentModule) {
require(paymentModule.delegatecall(bytes4(keccak256("getCommissionTokens()"))));
}
function delegatedRefund(address paymentModule) {
require(paymentModule.delegatecall(bytes4(keccak256("refund()"))));
}
function delegatedRefundSoftCap(address paymentModule) {
require(paymentModule.delegatecall(bytes4(keccak256("refundSoftCap()"))));
}
function delegatedWithdrawal(address votingDecisionModule, address _address, uint withdrawalSum, bool dxc) {
require(votingDecisionModule.delegatecall(bytes4(keccak256("withdrawal(address,uint256,bool)")), _address, withdrawalSum, dxc));
}
function delegatedMakeRefundableByUser(address votingDecisionModule) {
require(votingDecisionModule.delegatecall(bytes4(keccak256("makeRefundableByUser()"))));
}
function delegatedMakeRefundableByVotingDecision(address votingDecisionModule) {
require(votingDecisionModule.delegatecall(bytes4(keccak256("makeRefundableByVotingDecision()"))));
}
function delegatedHoldTokens(address votingDecisionModule, address _address, uint duration) {
require(votingDecisionModule.delegatecall(bytes4(keccak256("holdTokens(address,uint256)")), _address, duration));
}
function delegatedInitCrowdsaleParameters(
address crowdsaleModule,
uint _softCap,
uint _hardCap,
uint _etherRate,
uint _DXCRate,
uint _startTime,
uint _endTime,
bool _dxcPayments
) {
require(crowdsaleModule.delegatecall(bytes4(keccak256("initCrowdsaleParameters(uint256,uint256,uint256,uint256,uint256,uint256,bool)"))
, _softCap, _hardCap, _etherRate, _DXCRate, _startTime, _endTime, _dxcPayments));
}
function delegatedFinish(address crowdsaleModule) {
require(crowdsaleModule.delegatecall(bytes4(keccak256("finish()"))));
}
function delegatedHandlePayment(address crowdsaleModule, address _sender, bool _commission) {
require(crowdsaleModule.delegatecall(bytes4(keccak256("handlePayment(address,bool)")), _sender, _commission));
}
function delegatedHandleDXCPayment(address crowdsaleModule, address _from, uint _amount) {
require(crowdsaleModule.delegatecall(bytes4(keccak256("handleDXCPayment(address,uint256)")), _from, _amount));
}
}
library Common {
function stringToBytes32(string memory source) constant returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
function percent(uint numerator, uint denominator, uint precision) constant returns(uint quotient) {
uint _numerator = numerator * 10 ** (precision+1);
quotient = ((_numerator / denominator) + 5) / 10;
}
function toString(bytes32 _bytes) internal constant returns(string) {
bytes memory arrayTemp = new bytes(32);
uint currentLength = 0;
for (uint i = 0; i < 32; i++) {
arrayTemp[i] = _bytes[i];
if (arrayTemp[i] != 0) currentLength+=1;
}
bytes memory arrayRes = new bytes(currentLength);
for (i = 0; i < currentLength; i++) {
arrayRes[i] = arrayTemp[i];
}
return string(arrayRes);
}
}
contract CrowdsaleDAO is CrowdsaleDAOFields, Owned {
address public stateModule;
address public paymentModule;
address public votingDecisionModule;
address public crowdsaleModule;
function CrowdsaleDAO(string _name, string _description, address _serviceContractAddress, address _votingFactoryContractAddress)
Owned(msg.sender) {
(name, description, serviceContract, votingFactory) = (_name, _description, _serviceContractAddress, VotingFactoryInterface(_votingFactoryContractAddress));
}
/*
* @dev Receives ether and forwards to the crowdsale module via a delegatecall with commission flag equal to false
*/
function() payable {
DAOProxy.delegatedHandlePayment(crowdsaleModule, msg.sender, false);
}
/*
* @dev Receives ether from commission contract and forwards to the crowdsale module
* via a delegatecall with commission flag equal to true
* @param _sender Address which sent ether to commission contract
*/
function handleCommissionPayment(address _sender) payable {
DAOProxy.delegatedHandlePayment(crowdsaleModule, _sender, true);
}
/*
* @dev Receives info about address which sent DXC tokens to current contract and about amount of sent tokens from
* DXC token contract and then forwards this data to the crowdsale module
* @param _from Address which sent DXC tokens
* @param _amount Amount of tokens which were sent
*/
function handleDXCPayment(address _from, uint _amount) {
DAOProxy.delegatedHandleDXCPayment(crowdsaleModule, _from, _amount);
}
/*
* @dev Receives decision from withdrawal voting and forwards it to the voting decisions module
* @param _address Address for withdrawal
* @param _withdrawalSum Amount of ether/DXC tokens which must be sent to withdrawal address
* @param _dxc boolean indicating whether withdrawal should be made through DXC tokens or not
*/
function withdrawal(address _address, uint _withdrawalSum, bool _dxc) external {
DAOProxy.delegatedWithdrawal(votingDecisionModule, _address, _withdrawalSum, _dxc);
}
/*
* @dev Receives decision from refund voting and forwards it to the voting decisions module
*/
function makeRefundableByVotingDecision() external {
DAOProxy.delegatedMakeRefundableByVotingDecision(votingDecisionModule);
}
/*
* @dev Called by voting contract to hold tokens of voted address.
* It is needed to prevent multiple votes with same tokens
* @param _address Voted address
* @param _duration Amount of time left for voting to be finished
*/
function holdTokens(address _address, uint _duration) external {
DAOProxy.delegatedHoldTokens(votingDecisionModule, _address, _duration);
}
function setStateModule(address _stateModule) external canSetAddress(stateModule) {
stateModule = _stateModule;
}
function setPaymentModule(address _paymentModule) external canSetAddress(paymentModule) {
paymentModule = _paymentModule;
}
function setVotingDecisionModule(address _votingDecisionModule) external canSetAddress(votingDecisionModule) {
votingDecisionModule = _votingDecisionModule;
}
function setCrowdsaleModule(address _crowdsaleModule) external canSetAddress(crowdsaleModule) {
crowdsaleModule = _crowdsaleModule;
}
function setVotingFactoryAddress(address _votingFactory) external canSetAddress(votingFactory) {
votingFactory = VotingFactoryInterface(_votingFactory);
}
/*
* @dev Checks if provided address has tokens of current DAO
* @param _participantAddress Address of potential participant
* @return boolean indicating if the address has at least one token
*/
function isParticipant(address _participantAddress) external constant returns (bool) {
return token.balanceOf(_participantAddress) > 0;
}
/*
* @dev Function which is used to set address of token which will be distributed by DAO during the crowdsale and
* address of DXC token contract to use it for handling payment operations with DXC. Delegates call to state module
* @param _tokenAddress Address of token which will be distributed during the crowdsale
* @param _DXC Address of DXC contract
*/
function initState(address _tokenAddress, address _DXC) public {
DAOProxy.delegatedInitState(stateModule, _tokenAddress, _DXC);
}
/*
* @dev Delegates parameters which describe conditions of crowdsale to the crowdsale module.
* @param _softCap The minimal amount of funds that must be collected by DAO for crowdsale to be considered successful
* @param _hardCap The maximal amount of funds that can be raised during the crowdsale
* @param _etherRate Amount of tokens that will be minted per one ether
* @param _DXCRate Amount of tokens that will be minted per one DXC
* @param _startTime Unix timestamp that indicates the moment when crowdsale will start
* @param _endTime Unix timestamp that indicates the moment when crowdsale will end
* @param _dxcPayments Boolean indicating whether it is possible to invest via DXC token or not
*/
function initCrowdsaleParameters(uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments) public {
DAOProxy.delegatedInitCrowdsaleParameters(crowdsaleModule, _softCap, _hardCap, _etherRate, _DXCRate, _startTime, _endTime, _dxcPayments);
}
/*
* @dev Delegates request of creating "regular" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
* @param _options List of options
*/
function addRegular(string _name, string _description, uint _duration, bytes32[] _options) public {
votings[DAOLib.delegatedCreateRegular(votingFactory, _name, _description, _duration, _options, this)] = true;
}
/*
* @dev Delegates request of creating "withdrawal" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
* @param _sum Amount of funds that is supposed to be withdrawn
* @param _withdrawalWallet Address for withdrawal
* @param _dxc Boolean indicating whether withdrawal must be in DXC tokens or in ether
*/
function addWithdrawal(string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc) public {
votings[DAOLib.delegatedCreateWithdrawal(votingFactory, _name, _description, _duration, _sum, _withdrawalWallet, _dxc, this)] = true;
}
/*
* @dev Delegates request of creating "refund" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
*/
function addRefund(string _name, string _description, uint _duration) public {
votings[DAOLib.delegatedCreateRefund(votingFactory, _name, _description, _duration, this)] = true;
}
/*
* @dev Delegates request of creating "module" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
* @param _module Number of module which must be replaced
* @param _newAddress Address of new module
*/
function addModule(string _name, string _description, uint _duration, uint _module, address _newAddress) public {
votings[DAOLib.delegatedCreateModule(votingFactory, _name, _description, _duration, _module, _newAddress, this)] = true;
}
/*
* @dev Delegates request for going into refundable state to voting decisions module
*/
function makeRefundableByUser() public {
DAOProxy.delegatedMakeRefundableByUser(votingDecisionModule);
}
/*
* @dev Delegates request for refund to payment module
*/
function refund() public {
DAOProxy.delegatedRefund(paymentModule);
}
/*
* @dev Delegates request for refund of soft cap to payment module
*/
function refundSoftCap() public {
DAOProxy.delegatedRefundSoftCap(paymentModule);
}
/*
* @dev Delegates request for finish of crowdsale to crowdsale module
*/
function finish() public {
DAOProxy.delegatedFinish(crowdsaleModule);
}
/*
* @dev Sets team addresses and bonuses for crowdsale
* @param _team The addresses that will be defined as team members
* @param _tokenPercents Array of bonuses in percents which will go te every member in case of successful crowdsale
* @param _bonusPeriods Array of timestamps which show when tokens will be minted with higher rate
* @param _bonusEtherRates Array of ether rates for every bonus period
* @param _bonusDXCRates Array of DXC rates for every bonus period
* @param _teamHold Array of timestamps which show the hold duration of tokens for every team member
* @param service Array of booleans which show whether member is a service address or not
*/
function initBonuses(address[] _team, uint[] _tokenPercents, uint[] _bonusPeriods, uint[] _bonusEtherRates, uint[] _bonusDXCRates, uint[] _teamHold, bool[] _service) public onlyOwner(msg.sender) {
require(
_team.length == _tokenPercents.length &&
_team.length == _teamHold.length &&
_team.length == _service.length &&
_bonusPeriods.length == _bonusEtherRates.length &&
(_bonusDXCRates.length == 0 || _bonusPeriods.length == _bonusDXCRates.length) &&
canInitBonuses &&
(block.timestamp < startTime || canInitCrowdsaleParameters)
);
team = _team;
teamHold = _teamHold;
teamBonusesArr = _tokenPercents;
teamServiceMember = _service;
for(uint i = 0; i < _team.length; i++) {
teamMap[_team[i]] = true;
teamBonuses[_team[i]] = _tokenPercents[i];
}
bonusPeriods = _bonusPeriods;
bonusEtherRates = _bonusEtherRates;
bonusDXCRates = _bonusDXCRates;
canInitBonuses = false;
}
/*
* @dev Sets addresses which can be used to get funds via withdrawal votings
* @param _addresses Array of addresses which will be used for withdrawals
*/
function setWhiteList(address[] _addresses) public onlyOwner(msg.sender) {
require(canSetWhiteList);
whiteListArr = _addresses;
for(uint i = 0; i < _addresses.length; i++) {
whiteList[_addresses[i]] = true;
}
canSetWhiteList = false;
}
/*
Modifiers
*/
modifier canSetAddress(address module) {
require(votings[msg.sender] || (module == 0x0 && msg.sender == owner));
_;
}
}
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() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library VotingLib {
struct Option {
uint votes;
bytes32 description;
}
function delegatecallCreate(address _v, address _dao, string _name, string _description, uint _duration, uint _quorum) {
require(_v.delegatecall(bytes4(keccak256("create(address,bytes32,bytes32,uint256,uint256)")),
_dao,
Common.stringToBytes32(_name),
Common.stringToBytes32(_description),
_duration,
_quorum)
);
}
function delegatecallAddVote(address _v, uint optionID) {
require(_v.delegatecall(bytes4(keccak256("addVote(uint256)")), optionID));
}
function delegatecallFinish(address _v) {
require(_v.delegatecall(bytes4(keccak256("finish()"))));
}
function isValidWithdrawal(address _dao, uint _sum, bool _dxc) constant returns(bool) {
return !_dxc ? _dao.balance >= _sum : ICrowdsaleDAO(_dao).DXC().balanceOf(_dao) >= _sum;
}
}
contract IDAO {
function isParticipant(address _participantAddress) external constant returns (bool);
function teamMap(address _address) external constant returns (bool);
function whiteList(address _address) constant returns (bool);
}
contract ICrowdsaleDAO is IDAO {
bool public crowdsaleFinished;
uint public teamTokensAmount;
uint public endTime;
uint public weiRaised;
uint public softCap;
uint public fundsRaised;
function addRegular(string _description, uint _duration, bytes32[] _options) external;
function addWithdrawal(string _description, uint _duration, uint _sum) external;
function addRefund(string _description, uint _duration) external;
function addModule(string _description, uint _duration, uint _module, address _newAddress) external;
function holdTokens(address _address, uint duration) external;
function makeRefundableByVotingDecision();
function withdrawal(address _address, uint withdrawalSum, bool dxc);
function setStateModule(address _stateModule);
function setPaymentModule(address _paymentModule);
function setVotingDecisionModule(address _votingDecisionModule);
function setCrowdsaleModule(address _crowdsaleModule);
function setVotingFactoryAddress(address _votingFactory);
function teamBonuses(address _address) constant returns (uint);
function token() constant returns (TokenInterface);
function DXC() constant returns(TokenInterface);
}
contract VotingFields {
ICrowdsaleDAO dao;
string public name;
string public description;
VotingLib.Option[11] public options;
mapping (address => uint) public voted;
VotingLib.Option public result;
uint public votesCount;
uint public duration; // UNIX
uint public created_at = now;
bool public finished = false;
uint public quorum;
string public votingType;
uint public minimalDuration = 60 * 60 * 24 * 7; // 7 days
}
interface VotingInterface {
function addVote(uint optionID) external;
function finish() external;
function getOptions() external constant returns(uint[2] result);
function finished() external constant returns(bool);
function voted(address _address) external constant returns (uint);
}
contract BaseProposal is VotingFields {
address baseVoting;
/*
* @dev Returns amount of votes for `yes` and `no` options
*/
function getOptions() public constant returns(uint[2]) {
return [options[1].votes, options[2].votes];
}
/*
* @dev Delegates request of adding vote to the Voting base contract
* @param _optionID ID of option which will be added as vote
*/
function addVote(uint _optionID) public {
VotingLib.delegatecallAddVote(baseVoting, _optionID);
}
/*
* @dev Initiates options `yes` and `no`
*/
function createOptions() internal {
options[1] = VotingLib.Option(0, "yes");
options[2] = VotingLib.Option(0, "no");
}
}
contract Regular is VotingFields {
address baseVoting;
function Regular(address _baseVoting, address _dao, string _name, string _description, uint _duration, bytes32[] _options){
require(_options.length >= 2 && _options.length <= 10);
baseVoting = _baseVoting;
votingType = "Regular";
VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 0);
createOptions(_options);
}
/*
* @dev Returns amount of votes for all regular proposal's options
* @return Array[10] of int
*/
function getOptions() external constant returns(uint[10]) {
return [options[1].votes, options[2].votes, options[3].votes, options[4].votes, options[5].votes,
options[6].votes, options[7].votes, options[8].votes, options[9].votes, options[10].votes];
}
/*
* @dev Delegates request of adding vote to the Voting base contract
* @param _optionID ID of option which will be added as vote
*/
function addVote(uint _optionID) public {
VotingLib.delegatecallAddVote(baseVoting, _optionID);
}
/*
* @dev Delegates request of finishing to the Voting base contract
*/
function finish() public {
VotingLib.delegatecallFinish(baseVoting);
}
/*
* @dev Creates up to 10 options of votes
* @param _options Array of votes options
*/
function createOptions(bytes32[] _options) private {
for (uint i = 0; i < _options.length; i++) {
options[i + 1] = VotingLib.Option(0, _options[i]);
}
}
}
contract Withdrawal is BaseProposal {
uint public withdrawalSum;
address public withdrawalWallet;
bool public dxc;
function Withdrawal(address _baseVoting, address _dao, string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc) {
require(_sum > 0 && VotingLib.isValidWithdrawal(_dao, _sum, _dxc));
baseVoting = _baseVoting;
votingType = "Withdrawal";
VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 0);
withdrawalSum = _sum;
withdrawalWallet = _withdrawalWallet;
dxc = _dxc;
createOptions();
}
/*
* @dev Delegates request of finishing to the Voting base contract
*/
function finish() public {
VotingLib.delegatecallFinish(baseVoting);
if(result.description == "yes") dao.withdrawal(withdrawalWallet, withdrawalSum, dxc);
}
}
contract Refund is BaseProposal {
function Refund(address _baseVoting, address _dao, string _name, string _description, uint _duration) {
baseVoting = _baseVoting;
votingType = "Refund";
VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 90);
createOptions();
}
function finish() public {
VotingLib.delegatecallFinish(baseVoting);
if(result.description == "yes") dao.makeRefundableByVotingDecision();
}
}
contract Voting is VotingFields {
/*
* @dev Initiate storage variables for caller contract via `delegatecall`
* @param _dao Address of dao where voting is creating
* @param _name Voting name
* @param _description Voting description
* @param _duration Voting duration
* @param _quorum Minimal percentage of token holders who must to take part in voting
*/
function create(address _dao, bytes32 _name, bytes32 _description, uint _duration, uint _quorum)
succeededCrowdsale(ICrowdsaleDAO(_dao))
correctDuration(_duration)
external
{
dao = ICrowdsaleDAO(_dao);
name = Common.toString(_name);
description = Common.toString(_description);
duration = _duration;
quorum = _quorum;
}
/*
* @dev Add vote with passed optionID for the caller voting via `delegatecall`
* @param _optionID ID of option
*/
function addVote(uint _optionID) external notFinished canVote correctOption(_optionID) {
require(block.timestamp - duration < created_at);
uint tokensAmount = dao.token().balanceOf(msg.sender);
options[_optionID].votes += tokensAmount;
voted[msg.sender] = _optionID;
votesCount += tokensAmount;
dao.holdTokens(msg.sender, (duration + created_at) - now);
}
/*
* @dev Finish voting for the caller voting contract via `delegatecall`
* @param _optionID ID of option
*/
function finish() external notFinished {
require(block.timestamp - duration >= created_at);
finished = true;
if (keccak256(votingType) == keccak256("Withdrawal")) return finishNotRegular();
if (keccak256(votingType) == keccak256("Regular")) return finishRegular();
//Other two cases of votings (`Module` and `Refund`) requires quorum
if (Common.percent(options[1].votes, dao.token().totalSupply() - dao.teamTokensAmount(), 2) >= quorum) {
result = options[1];
return;
}
result = options[2];
}
/*
* @dev Finish regular voting. Calls from `finish` function
*/
function finishRegular() private {
VotingLib.Option memory _result = options[1];
bool equal = false;
for (uint i = 2; i < options.length; i++) {
if (_result.votes == options[i].votes) equal = true;
else if (_result.votes < options[i].votes) {
_result = options[i];
equal = false;
}
}
if (!equal) result = _result;
}
/*
* @dev Finish non-regular voting. Calls from `finish` function
*/
function finishNotRegular() private {
if (options[1].votes > options[2].votes) result = options[1];
else result = options[2];
}
/*
* @dev Throws if caller is team member, not participant or has voted already
*/
modifier canVote() {
require(!dao.teamMap(msg.sender) && dao.isParticipant(msg.sender) && voted[msg.sender] == 0);
_;
}
/*
* @dev Throws if voting is finished already
*/
modifier notFinished() {
require(!finished);
_;
}
/*
* @dev Throws if crowdsale is not finished or if soft cap is not achieved
*/
modifier succeededCrowdsale(ICrowdsaleDAO dao) {
require(dao.crowdsaleFinished() && dao.fundsRaised() >= dao.softCap());
_;
}
/*
* @dev Throws if description of provided option ID is empty
*/
modifier correctOption(uint optionID) {
require(options[optionID].description != 0x0);
_;
}
/*
* @dev Throws if passed voting duration is not greater than minimal
*/
modifier correctDuration(uint _duration) {
require(_duration >= minimalDuration || keccak256(votingType) == keccak256("Module"));
_;
}
}
contract Module is BaseProposal {
enum Modules{State, Payment, VotingDecisions, Crowdsale, VotingFactory}
Modules public module;
address public newModuleAddress;
function Module(address _baseVoting, address _dao, string _name, string _description, uint _duration, uint _module, address _newAddress) {
require(_module >= 0 && _module <= 4);
baseVoting = _baseVoting;
votingType = "Module";
module = Modules(_module);
newModuleAddress = _newAddress;
VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 80);
createOptions();
}
/*
* @dev Delegates request of finishing to the Voting base contract
*/
function finish() public {
VotingLib.delegatecallFinish(baseVoting);
if(result.description == "no") return;
//Sorry but solidity doesn't support `switch` keyword
if (uint(module) == uint(Modules.State)) dao.setStateModule(newModuleAddress);
if (uint(module) == uint(Modules.Payment)) dao.setPaymentModule(newModuleAddress);
if (uint(module) == uint(Modules.VotingDecisions)) dao.setVotingDecisionModule(newModuleAddress);
if (uint(module) == uint(Modules.Crowdsale)) dao.setCrowdsaleModule(newModuleAddress);
if (uint(module) == uint(Modules.VotingFactory)) dao.setVotingFactoryAddress(newModuleAddress);
}
}
contract VotingFactory is VotingFactoryInterface {
address baseVoting;
DAOFactoryInterface public daoFactory;
function VotingFactory(address _baseVoting) {
baseVoting = _baseVoting;
}
/*
* @dev Create regular proposal with passed parameters. Calls from DAO contract
* @param _creator Address of caller of DAO's respectively function
* @param _name Voting's name
* @param _description Voting's description
* @param _duration Voting's duration
* @param _options Voting's options
*/
function createRegular(address _creator, string _name, string _description, uint _duration, bytes32[] _options)
external
onlyDAO
onlyParticipant(_creator)
returns (address)
{
return new Regular(baseVoting, msg.sender, _name, _description, _duration, _options);
}
/*
* @dev Create withdrawal proposal with passed parameters. Calls from DAO contract
* @param _creator Address of caller of DAO's respectively function
* @param _name Voting's name
* @param _description Voting's description
* @param _duration Voting's duration
* @param _sum Sum to withdraw from DAO
* @param _withdrawalWallet Address to send withdrawal sum
* @param _dxc Should withdrawal sum be interpret as amount of DXC tokens
*/
function createWithdrawal(address _creator, string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc)
external
onlyTeamMember(_creator)
onlyDAO
onlyWhiteList(_withdrawalWallet)
returns (address)
{
return new Withdrawal(baseVoting, msg.sender, _name, _description, _duration, _sum, _withdrawalWallet, _dxc);
}
/*
* @dev Create refund proposal with passed parameters. Calls from DAO contract
* @param _creator Address of caller of DAO's respectively function
* @param _name Voting's name
* @param _description Voting's description
* @param _duration Voting's duration
*/
function createRefund(address _creator, string _name, string _description, uint _duration) external onlyDAO onlyParticipant(_creator) returns (address) {
return new Refund(baseVoting, msg.sender, _name, _description, _duration);
}
/*
* @dev Create module proposal with passed parameters. Calls from DAO contract
* @param _creator Address of caller of DAO's respectively function
* @param _name Voting's name
* @param _description Voting's description
* @param _duration Voting's duration
* @param _module Which module should be changed
* @param _newAddress Address of new module
*/
function createModule(address _creator, string _name, string _description, uint _duration, uint _module, address _newAddress)
external
onlyDAO
onlyParticipant(_creator)
returns (address)
{
return new Module(baseVoting, msg.sender, _name, _description, _duration, _module, _newAddress);
}
/*
* @dev Set dao factory address. Calls ones from just deployed DAO
* @param _dao Address of dao factory
*/
function setDaoFactory(address _dao) external {
require(address(daoFactory) == 0x0 && _dao != 0x0);
daoFactory = DAOFactoryInterface(_dao);
}
/*
* @dev Throws if caller is not correct DAO
*/
modifier onlyDAO() {
require(daoFactory.exists(msg.sender));
_;
}
/*
* @dev Throws if creator is not participant of passed DAO
*/
modifier onlyParticipant(address creator) {
require(IDAO(msg.sender).isParticipant(creator));
_;
}
/*
* @dev Throws if creator is not team member of passed DAO
*/
modifier onlyTeamMember(address creator) {
require(IDAO(msg.sender).teamMap(creator));
_;
}
/*
* @dev Throws if creator is not member of white list in specified DAO
*/
modifier onlyWhiteList(address creator) {
require(IDAO(msg.sender).whiteList(creator));
_;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Token is MintableToken {
event TokenCreation(address _address);
string public name;
string public symbol;
uint constant public decimals = 18;
mapping(address => uint) public held;
function Token(string _name, string _symbol) {
name = _name;
symbol = _symbol;
TokenCreation(this);
}
function hold(address addr, uint duration) external onlyOwner {
uint holdTime = now + duration;
if (held[addr] == 0 || holdTime > held[addr]) held[addr] = holdTime;
}
function burn(address _burner) external onlyOwner {
require(_burner != 0x0);
uint balance = balanceOf(_burner);
balances[_burner] = balances[_burner].sub(balance);
totalSupply = totalSupply.sub(balance);
}
function transfer(address to, uint256 value) public notHolded(msg.sender) returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public notHolded(from) returns (bool) {
return super.transferFrom(from, to, value);
}
modifier notHolded(address _address) {
require(held[_address] == 0 || now >= held[_address]);
_;
}
}
contract DAOx is Ownable {
uint public balance;
DAOFactoryInterface public daoFactory;
function DAOx() {
}
function() payable onlyDAO {
balance += msg.value;
}
function setDaoFactory(address _dao) external {
require(address(daoFactory) == 0x0 && _dao != 0x0);
daoFactory = DAOFactoryInterface(_dao);
}
function withdraw(uint _weiToWithdraw) public onlyOwner {
balance -= _weiToWithdraw;
msg.sender.transfer(_weiToWithdraw);
}
modifier onlyDAO() {
require(daoFactory.exists(msg.sender));
_;
}
}
contract CrowdsaleDAOFactory is DAOFactoryInterface {
event CrowdsaleDAOCreated(
address _address,
string _name
);
address public serviceContractAddress;
address public votingFactoryContractAddress;
// DAOs created by factory
mapping(address => string) DAOs;
// Functional modules which will be used by DAOs to delegate calls
address[4] modules;
function CrowdsaleDAOFactory(address _serviceContractAddress, address _votingFactoryAddress, address[4] _modules) {
require(_serviceContractAddress != 0x0 && _votingFactoryAddress != 0x0);
serviceContractAddress = _serviceContractAddress;
votingFactoryContractAddress = _votingFactoryAddress;
modules = _modules;
require(votingFactoryContractAddress.call(bytes4(keccak256("setDaoFactory(address)")), this));
require(serviceContractAddress.call(bytes4(keccak256("setDaoFactory(address)")), this));
}
/*
* @dev Checks if provided address is an address of some DAO contract created by this factory
* @param _address Address of contract
* @return boolean indicating whether the contract was created by this factory or not
*/
function exists(address _address) external constant returns (bool) {
return keccak256(DAOs[_address]) != keccak256("");
}
/*
* @dev Creates new CrowdsaleDAO contract, provides it with addresses of modules, transfers ownership to tx sender
* and saves address of created contract to DAOs mapping
* @param _name Name of the DAO
* @param _name Description for the DAO
*/
function createCrowdsaleDAO(string _name, string _description) public {
address dao = DAODeployer.deployCrowdsaleDAO(_name, _description, serviceContractAddress, votingFactoryContractAddress);
require(dao.call(bytes4(keccak256("setStateModule(address)")), modules[0]));
require(dao.call(bytes4(keccak256("setPaymentModule(address)")), modules[1]));
require(dao.call(bytes4(keccak256("setVotingDecisionModule(address)")), modules[2]));
require(dao.call(bytes4(keccak256("setCrowdsaleModule(address)")), modules[3]));
DAODeployer.transferOwnership(dao, msg.sender);
DAOs[dao] = _name;
CrowdsaleDAOCreated(dao, _name);
}
}
contract DXC is MintableToken {
address[] public additionalOwnersList; // List of addresses which are able to call `mint` function
mapping(address => bool) public additionalOwners; // Mapping of addresses which are able to call `mint` function
uint public maximumSupply = 300000000 * 10**18; // Maximum supply of DXC tokens equals 300 millions
event TokenCreation(address _address);
event SetAdditionalOwners(address[] oldOwners, address[] newOwners);
string public constant name = "Daox Coin";
string public constant symbol = "DXC";
uint public constant decimals = 18;
/**
* @dev Transfer specified amount of tokens to the specified address and call
* standard `handleDXCPayment` method of Crowdsale DAO
* @param _to The address of Crowdsale DAO
* @param _amount The amount of tokens to send
*/
function contributeTo(address _to, uint256 _amount) public {
super.transfer(_to, _amount);
require(_to.call(bytes4(keccak256("handleDXCPayment(address,uint256)")), msg.sender, _amount));
}
/**
* @dev Overrides function to mint tokens from `MintableToken` contract with new modifier
* @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) isOwnerOrAdditionalOwner canMint maximumSupplyWasNotReached(_amount) public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Define array and mapping of addresses that will be additional owners
* @param _owners The addresses that will be defined as additional owners
*/
function setAdditionalOwners(address[] _owners) onlyOwner {
SetAdditionalOwners(additionalOwnersList, _owners);
for (uint i = 0; i < additionalOwnersList.length; i++) {
additionalOwners[additionalOwnersList[i]] = false;
}
for (i = 0; i < _owners.length; i++) {
additionalOwners[_owners[i]] = true;
}
additionalOwnersList = _owners;
}
/**
* @dev Throws an exception if called not by owner or additional owner
*/
modifier isOwnerOrAdditionalOwner() {
require(msg.sender == owner || additionalOwners[msg.sender]);
_;
}
/**
* @dev Throws an exception if maximumSupply will be exceeded after minting
* @param _amount The amount of tokens to mint
*/
modifier maximumSupplyWasNotReached(uint256 _amount) {
require(totalSupply.add(_amount) <= maximumSupply);
_;
}
} | Set dao factory address. Calls ones from just deployed DAO _dao Address of dao factory/ | function setDaoFactory(address _dao) external {
require(address(daoFactory) == 0x0 && _dao != 0x0);
daoFactory = DAOFactoryInterface(_dao);
}
| 12,948,354 |
// SPDX-License-Identifier: MIT
/*
* @title TemperaturesContract
* @author Yuichi Takata <[email protected]>
*
* @dev このコントラクトは温度の登録、参照を目的としています。
* また、DeviceArea、Timeコントラクトを継承し、
* 外部のライブラリとしてsafemath,Ownableを
* 使用しています。
*
*/
pragma solidity ^0.8.7;
import "./devicearea.sol";
import "./safemath.sol";
import "./time.sol";
import "./ownable.sol";
contract Temperatures is DeviceArea, Time, Ownable {
using SafeMath for uint256;
struct TemperaturesData {
//温度構造体
string areaName; //地域名
uint256 timestamp; //タイムスタンプ
int8 temperature; //温度
}
event addTempData(
//温度構造体が登録された時に発火するイベント
address indexed from,
string areaName, //地域名
uint256 timestamp, //タイムスタンプ
int8 temperature, //温度
uint256 id //登録ID(温度構造体の配列のインデックス)
);
mapping(uint256 => address) IdToAddr; //登録IDをキーとしてアドレス(登録者)を参照
mapping(string => uint256) AreaDataCount; //その地域名で登録されたデータの数
mapping(address => uint256) UsersDataCount; //そのアカウントが登録したデータの数
TemperaturesData[] public TemperaturesDataList;
/*
* @dev 温度を登録します。情報の質を高めるために、地域名と時間も一緒に構造体として保存します。
* 構造体は配列の後部に追加されます。
* @param 登録する温度を引数として持ちます。
*/
function temperaturesRegister(int8 _temperature) public {
uint256 id;
TemperaturesDataList.push(
TemperaturesData(
getAreaName(msg.sender),
getTimestamp(),
_temperature
)
);
id = TemperaturesDataList.length - 1;
IdToAddr[id] = msg.sender;
UsersDataCount[msg.sender] = UsersDataCount[msg.sender].add(1);
AreaDataCount[getAreaName(msg.sender)] = AreaDataCount[
getAreaName(msg.sender)
].add(1);
emit addTempData(
msg.sender,
getAreaName(msg.sender),
getTimestamp(),
_temperature,
id
);
}
/*
* @dev 登録ID(インデックス)から情報を取得します。
* @param uint型のIDを引数とします。
* @return 検索結果として温度構造体を返します。
*/
function getTemperaturesById(uint256 _id)
public
view
returns (TemperaturesData memory)
{
require(TemperaturesDataList.length != 0);
require(TemperaturesDataList.length >= _id);
return TemperaturesDataList[_id];
}
/*
* @dev 地域名から情報を取得します。
* @param string型の地域名を引数とします。
* @return 検索結果として温度構造体を返します。
*/
function getTemperaturesByArea(string calldata _areaName)
public
view
returns (TemperaturesData[] memory resData)
{
require(AreaDataCount[_areaName] >= 1);
resData = new TemperaturesData[](AreaDataCount[_areaName]);
uint256 dataCount = 0;
for (uint256 i = 0; i < TemperaturesDataList.length; i++) {
if (isSameString(_areaName, TemperaturesDataList[i].areaName)) {
resData[dataCount] = TemperaturesDataList[i];
dataCount = dataCount.add(1);
}
}
return resData;
}
/*
* @dev アドレス(EOA)から情報を取得します。
* @param 対象のアドレスを引数とします。
* @return 検索結果として温度構造体を返します。
*/
function getTemperaturesByEOA(address _userId)
public
view
returns (TemperaturesData[] memory resData)
{
require(UsersDataCount[_userId] >= 1);
resData = new TemperaturesData[](UsersDataCount[_userId]);
uint256 dataCount = 0;
for (uint256 i = 0; i < TemperaturesDataList.length; i++) {
if (IdToAddr[i] == _userId) {
resData[dataCount] = TemperaturesDataList[i];
dataCount = dataCount.add(1);
}
}
return resData;
}
/*
* @dev 全体でデータが幾つ登録されたかの確認をします。
* @param 引数はありません。
* @return データの個数をuint型で返します。
*/
function getTemperaturesDataCount() public view returns (uint256) {
return TemperaturesDataList.length;
}
/*
* @dev 対象のアドレスが登録したデータのID一覧を確認できます。
* @param 対象のアドレスを引数とします。
* @return ID一覧を配列で返します。
*/
function getSetDataIDsByEOA(address _address)
public
view
returns (uint256[] memory res)
{
res = new uint256[](UsersDataCount[_address]);
uint256 dataCount = 0;
for (uint256 i = 0; i < TemperaturesDataList.length; i++) {
if (IdToAddr[i] == _address) {
res[dataCount] = i;
dataCount = dataCount.add(1);
}
}
return res;
}
/*
* @dev 全ての登録データを確認できます。コントラクトの作成者が実行できます。
* @param 引数はありません。
* @return 温度構造体を配列で返します。
*/
function getTemperaturesDataList()
public
view
onlyOwner
returns (TemperaturesData[] memory)
{
return TemperaturesDataList;
}
}
| 全体でデータが幾つ登録されたかの確認をします。 引数はありません。 return データの個数をuint型で返します。/ | function getTemperaturesDataCount() public view returns (uint256) {
return TemperaturesDataList.length;
}
| 7,293,796 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
import "./IERC20.sol";
contract TokenTimeLock {
IERC20 private _token;
address private _beneficiary;
uint256 private _releaseTime;
constructor(IERC20 _token_, address _beneficiary_, uint256 _releaseTime_) {
_token = _token_;
_beneficiary = _beneficiary_;
_releaseTime = block.timestamp + _releaseTime_;
}
function token() public view returns(IERC20) {
return _token;
}
function beneficiary() public view returns(address) {
return _beneficiary;
}
function releaseTime() public view returns(uint256) {
return _releaseTime;
}
function release() public {
require(block.timestamp >= _releaseTime, "TokenTimeLock: current time is before release time");
uint256 _amount = _token.balanceOf(address(this));
require(_amount > 0, "TokenTimeLock:Empty balance");
_token.transfer(_beneficiary, _amount);
selfdestruct(payable(_beneficiary));
}
}
contract TokenSaleWithTimeLock {
IERC20 public tokenContract;
uint256 public price;
uint256 public tokensSold;
uint256 public releaseTime;
event Sold(address indexed buyer, address indexed timelock, uint256 amount);
address public owner;
constructor(IERC20 _tokenContract, uint256 _price, uint256 _releaseTime) {
owner = msg.sender;
tokenContract = _tokenContract;
price = _price;
releaseTime = _releaseTime;
}
function buyTokens(uint256 _numberOfTokens) public payable {
require(msg.value == _numberOfTokens * price);
uint256 _scaledAmount = _numberOfTokens * (10**tokenContract.decimals());
require(tokenContract.balanceOf(address(this)) >= _scaledAmount);
// require(tokenContract.transfer(msg.sender, _scaledAmount));
TokenTimeLock _tokenTimeLock = new TokenTimeLock(tokenContract, msg.sender, 60);
require(tokenContract.transfer(address(_tokenTimeLock), _scaledAmount));
tokensSold += _scaledAmount;
emit Sold(msg.sender, address(_tokenTimeLock), _scaledAmount);
}
function endSale() public {
require(msg.sender == owner,"restricted access");
uint256 _amount = tokenContract.balanceOf(address(this));
// Sending unsold tokens to the owner
require(tokenContract.transfer(msg.sender, _amount));
// destroy , send the balance of ether from this contract
selfdestruct(payable(owner));
}
} | require(tokenContract.transfer(msg.sender, _scaledAmount)); | function buyTokens(uint256 _numberOfTokens) public payable {
require(msg.value == _numberOfTokens * price);
uint256 _scaledAmount = _numberOfTokens * (10**tokenContract.decimals());
require(tokenContract.balanceOf(address(this)) >= _scaledAmount);
TokenTimeLock _tokenTimeLock = new TokenTimeLock(tokenContract, msg.sender, 60);
require(tokenContract.transfer(address(_tokenTimeLock), _scaledAmount));
tokensSold += _scaledAmount;
emit Sold(msg.sender, address(_tokenTimeLock), _scaledAmount);
}
| 5,392,775 |
./full_match/7700/0x865dE7F1Bf53B71b296e88E213cBD0503B7913cb/sources/contracts/external/cantolp/CErc20Delegator.sol | Sender redeems cTokens in exchange for the underlying asset Accrues interest whether or not the operation succeeds, unless reverted redeemTokens The number of cTokens to redeem into underlying return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function redeem(uint256 redeemTokens)
external
override
returns (uint256)
{
bytes memory data = delegateToImplementation(
abi.encodeWithSignature("redeem(uint256)", redeemTokens)
);
return abi.decode(data, (uint256));
}
| 4,657,761 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/**
* @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 for managing the Raum Public and Private Sale
*/
contract RaumSale {
using SafeMath for uint256;
struct vault {
uint256 privateSalebalance;
uint256 privateSaleWithdrawDate;
uint256 publicSalebalance1;
uint256 publicSaleWithdrawDate1;
uint256 publicSalebalance2;
uint256 publicSaleWithdrawDate2;
}
mapping(address => vault) public saleBalances;
address payable admin;
address RNTokens;
uint256 rnTokenPerMatic;
bool isPublicSale1 = false;
bool isPublicSale2 = false;
event print(uint256 amount);
/**
* @dev Sets the values for {admin}, {RNTokens}, {startSaleBlock} and {price}.
*
*
*/
constructor(address _RNAddress,uint256 _rnTokenPerMatic) {
admin = payable(msg.sender);
RNTokens = _RNAddress;
rnTokenPerMatic = _rnTokenPerMatic;
}
/**
* @dev Set the Updated price for public and private sale.
*/
function setrnTokenPerMatic(uint256 _rnTokenPerMatic) public {
require ( msg.sender == admin, "Only admin callable function");
rnTokenPerMatic = _rnTokenPerMatic;
}
/**
* @dev Set the close the public sale 1
*/
function changePublicSale1(bool _start) public {
require ( msg.sender == admin, "Only admin callable function");
isPublicSale1 = _start;
}
/**
* @dev Set the close the public sale 2
*/
function changePublicSale2(bool _start) public {
require ( msg.sender == admin, "Only admin callable function");
isPublicSale2 = _start;
}
/**
* @dev Allows account to Book Tokens and lock them for 12 months
*/
function privateSale(uint256 rnTokens, address investor) public {
require ( msg.sender == admin, "Only admin callable function");
saleBalances[investor].privateSalebalance = saleBalances[msg.sender].privateSalebalance.add(rnTokens);
saleBalances[investor].privateSaleWithdrawDate = block.timestamp + 360 days;
}
/**
* @dev Allows account to Book Tokens and lock them for 8 months
*/
function publicSale1() public payable {
require( isPublicSale1==true, "Public Sale 1 is closed");
require( msg.value>=50*(10**18) && msg.value<=7500*(10**18), "You can buy a minimum of tokens worth 50 Matic and maximum of 7500 Matic" );
uint256 noOfTokens = rnTokenPerMatic*(msg.value);
saleBalances[msg.sender].publicSalebalance1 = saleBalances[msg.sender].publicSalebalance1.add(noOfTokens);
saleBalances[msg.sender].publicSaleWithdrawDate1 = block.timestamp + 240 days;
}
/**
* @dev Allows account to Book Tokens and lock them for 6 months
*/
function publicSale2() public payable {
require( isPublicSale2==true, "Public Sale 2 is closed");
require( msg.value>=50*(10**18) && msg.value<=7500*(10**18), "You can buy a minimum of tokens worth 50 Matic and maximum of 7500 Matic" );
uint256 noOfTokens = rnTokenPerMatic*(msg.value);
saleBalances[msg.sender].publicSalebalance2 = saleBalances[msg.sender].publicSalebalance2.add(noOfTokens);
saleBalances[msg.sender].publicSaleWithdrawDate2 = block.timestamp + 180 days;
}
/**
* @dev Allows account to withdraw the Public sale 1 tokens
*/
function withdrawPublicSale1() public {
require( block.timestamp >= saleBalances[msg.sender].publicSaleWithdrawDate1, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].publicSalebalance1);
saleBalances[msg.sender].publicSalebalance1 = 0;
}
/**
* @dev Allows account to withdraw the Public sale 2 tokens
*/
function withdrawPublicSale2() public {
require( block.timestamp >= saleBalances[msg.sender].publicSaleWithdrawDate2, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].publicSalebalance2);
saleBalances[msg.sender].publicSalebalance2 = 0;
}
/**
* @dev Allows account to withdraw the Private token sale
*/
function withdrawPrivateSale() public {
require( block.timestamp >= saleBalances[msg.sender].privateSaleWithdrawDate, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].privateSalebalance);
saleBalances[msg.sender].privateSalebalance = 0;
}
/**
* @dev Returnnumber of RN Tokens in this contract
*/
function getRNBalance() public view returns (uint) {
return IERC20(RNTokens).balanceOf(address(this));
}
/**
* @dev Returnnumber of MATIC Tokens in this contract
*/
function getMaticBalance() public view returns (uint) {
return address(this).balance;
}
/**
* @dev allows admin to withdraw MATIC Tokens.
*/
function withdrawMatic() public {
require ( msg.sender == admin, "Only admin callable function");
admin.transfer(getMaticBalance());
}
/**
* @dev allows admin to withdraw RN Tokens.
*/
function withdrawRN() public {
require ( msg.sender == admin, "Only admin callable function");
IERC20(RNTokens).transfer(admin, getRNBalance());
}
}
| Returnnumber of RN Tokens in this contract/ | function getRNBalance() public view returns (uint) {
return IERC20(RNTokens).balanceOf(address(this));
}
| 5,427,833 |
/*
* ___ _ _ _ _ ___ _ ___ ___ ___
* / __>| | || \ || . >| || . \| . \/ __>
* \__ \| ' || || . \| || /| | |\__ \
* <___/`___'|_\_||___/|_||_\_\|___/<___/
*
* Sun's out, birds out.
*/
// SPDX-License-Identifier: UNLICENSED
// Sources flattened with hardhat v2.9.3 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// 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/token/ERC721/[email protected]
// 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/[email protected]
// 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/token/ERC721/extensions/[email protected]
// 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/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
// 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/introspection/[email protected]
// 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 erc721a/contracts/[email protected]
// Creator: Chiru Labs
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
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 extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 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**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
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;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 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_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* 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 (_startTokenId() <= curr && 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 virtual 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 (to.isContract() && !_checkContractOnERC721Received(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 _startTokenId() <= tokenId && 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 > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 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;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// 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**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.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;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// 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**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.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;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, 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 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 _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
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))
}
}
}
}
/**
* @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 contracts/SUNBIRD.sol
pragma solidity ^0.8.13;
error MaxQuantityExceeded();
error InsufficientEther();
error ExceedsMaximumSupply();
error PromoAlreadyRun();
contract Sunbirds is ERC721A, Ownable, Pausable {
uint256 public constant MINT_PRICE = 0.025 ether;
uint256 public constant MAX_MILFERS = 10000;
string public baseURI = "ipfs://QmfXTabGWKkMbxEDnVqy5ZCgv5prBfWyJTxzKdTndsnUvz/";
constructor() ERC721A("Sunbirds", "SUNBIRD") {
_pause();
}
function hatchSunbirds(uint256 qty) public payable {
if(qty > 100) revert MaxQuantityExceeded();
unchecked {
if(MINT_PRICE * qty > msg.value) revert InsufficientEther();
if(totalSupply() + qty > MAX_MILFERS) revert ExceedsMaximumSupply();
_safeMint(msg.sender, qty);
}
}
// Mint the first 50 sunbirds to the project wallet
function promoHatch() public onlyOwner {
unchecked {
if(totalSupply() > 0) revert PromoAlreadyRun();
_safeMint(msg.sender, 50);
}
_unpause();
}
function withdraw() public onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory newBaseURI) public onlyOwner {
baseURI = newBaseURI;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
} | Mint the first 50 sunbirds to the project wallet | function promoHatch() public onlyOwner {
unchecked {
if(totalSupply() > 0) revert PromoAlreadyRun();
_safeMint(msg.sender, 50);
}
_unpause();
}
| 10,847,112 |
// SPDX-License-Identifier: MIT
// Developed by KG Technologies (https://kgtechnologies.io)
pragma solidity 0.8.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract IBreedingContract {
/**
* @notice function to set the merkle root for breeding.
*
* @param _merkleRoot. The new merkle root to set.
*/
function setMerkleRoot(bytes32 _merkleRoot) external {}
/**
* @notice function to turn on/off breeding.
*
* @param _status. The new state of the breeding.
*/
function setBreedingStatus(bool _status) external {}
/**
* @notice function to set the maximum amount of juniors that can be bred.
*
* @param max. The new maximum.
*/
function setMaxBreedableJuniors(uint256 max) external {}
/**
* @notice function to set the cooldown period for breeding a slotie.
*
* @param coolDown. The new cooldown period.
*/
function setBreedCoolDown(uint256 coolDown) external {}
/**
* @notice function to set the watts price for breeding two sloties.
*
* @param price. The new watts price.
*/
function setBreedPice(uint256 price) external {}
/**
* @dev WATTS OWNER
*/
function WATTSOWNER_TransferOwnership(address newOwner) external {}
function WATTSOWNER_SetSlotieNFT(address newSlotie) external {}
function WATTSOWNER_SetLockPeriod(uint256 newLockPeriod) external {}
function WATTSOWNER_SetIsBlackListed(address _set, bool _is) external {}
function WATTSOWNER_seeClaimableBalanceOfUser(address user) external view returns (uint256) {}
function WATTSOWNER_seeClaimableTotalSupply() external view returns (uint256) {}
function transferOwnership(address newOwner) public {}
}
abstract contract IWatts is IERC20 {
function burn(address _from, uint256 _amount) external {}
function seeClaimableBalanceOfUser(address user) external view returns(uint256) {}
function seeClaimableTotalSupply() external view returns(uint256) {}
function burnClaimable(address _from, uint256 _amount) public {}
function mintClaimable(address _to, uint256 _amount) public {}
function transferOwnership(address newOwner) public {}
function setSlotieNFT(address newSlotieNFT) external {}
function setLockPeriod(uint256 newLockPeriod) external {}
function setIsBlackListed(address _address, bool _isBlackListed) external {}
}
abstract contract ISlotie is IERC721 {
function nextTokenId() external view returns(uint256){}
}
/**
* @title WattsTransferExtensionV2.
*
* @author KG Technologies (https://kgtechnologies.io).
*
* @notice This Smart Contract extends on the WATTS ERC-20 token with transfer functionality.
*
*/
contract WattsTransferExtensionV2 is Ownable {
/**
* @notice The Smart Contract of Watts.
* @dev ERC-20 Smart Contract
*/
IWatts public watts;
/**
* @notice The Breeding Contract.
* @dev Breeding Smart Contract
*/
IBreedingContract public breeding;
/**
* @notice The Slotie Contract.
* @dev Slotie Smart Contract
*/
ISlotie public slotie;
mapping(address => bool) public blackListedRecipients;
/**
* @dev Events
*/
event transferFromExtension(address indexed sender, address indexed recipient, uint256 claimableTransfered, uint256 balanceTransfered);
event blackListRecipientEvent(address indexed recipient, bool indexed shouldBlackList);
event ReceivedEther(address indexed sender, uint256 indexed amount);
event WithdrawAllEvent(address indexed recipient, uint256 amount);
constructor(
address slotieAddress,
address wattsAddress,
address breedingAddress
) Ownable() {
slotie = ISlotie(slotieAddress);
watts = IWatts(wattsAddress);
breeding = IBreedingContract(breedingAddress);
blackListedRecipients[0x1C075F1c3083F67add5FFAb240DE1f604F978E83] = true; // Sushiswap WETH-WATTS LP Pair
}
/**
* @dev TRANSFER
*/
/**
* @dev Allows users to transfer accumulated watts
* to other addresses.
*/
function transfer(
uint256 amount,
address recipient
) external {
require(address(watts) != address(0), "WATTS ADDRESS NOT SET");
require(watts.balanceOf(msg.sender) >= amount, "TRANSFER EXCEEDS BALANCE");
require(amount > 0, "CANNOT TRANSFER 0");
require(!blackListedRecipients[recipient], "RECIPIENT BLACKLISTED");
uint256 claimableBalance = breeding.WATTSOWNER_seeClaimableBalanceOfUser(msg.sender);
uint256 transferFromClaimable = claimableBalance >= amount ? amount : claimableBalance;
uint256 transferFromBalance = claimableBalance >= amount ? 0 : amount - claimableBalance;
require(watts.allowance(msg.sender, address(this)) >= transferFromBalance, "AMOUNT EXCEEDS ALLOWANCE");
if (claimableBalance > 0) {
watts.burnClaimable(msg.sender, transferFromClaimable);
watts.mintClaimable(recipient, transferFromClaimable);
}
if (transferFromBalance > 0) {
watts.transferFrom(msg.sender, recipient, transferFromBalance);
}
emit transferFromExtension(msg.sender, recipient, transferFromClaimable, transferFromBalance);
}
/**
* @dev SLOTIE ENUMERABLE EXTENSION
*/
function slotieWalletOfOwner(address owner) external view returns (uint256[] memory) {
uint256 _balance = slotie.balanceOf(owner);
uint256[] memory _tokens = new uint256[] (_balance);
uint256 _index;
uint256 _loopThrough = slotie.nextTokenId();
for (uint i = 1; i < _loopThrough; i++) {
if (slotie.ownerOf(i) == address(0x0) && _tokens[_balance - 1] == 0) {
_loopThrough++;
}
if (slotie.ownerOf(i) == owner) {
_tokens[_index] = i;
_index++;
}
}
return _tokens;
}
/**
* @dev OWNER ONLY
*/
/**
* @dev Method to blacklist or whitelist
* an address from receiving WATTS
*/
function blackListRecipient(address recipient, bool shouldBlackList) external onlyOwner {
blackListedRecipients[recipient] = shouldBlackList;
emit blackListRecipientEvent(recipient, shouldBlackList);
}
/**
* @notice function to set the merkle root for breeding.
*
* @param _merkleRoot. The new merkle root to set.
*/
function BREEDOWNER_setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
breeding.setMerkleRoot(_merkleRoot);
}
/**
* @notice function to turn on/off breeding.
*
* @param _status. The new state of the breeding.
*/
function BREEDOWNER_setBreedingStatus(bool _status) external onlyOwner {
breeding.setBreedingStatus(_status);
}
/**
* @notice function to set the maximum amount of juniors that can be bred.
*
* @param max. The new maximum.
*/
function BREEDOWNER_setMaxBreedableJuniors(uint256 max) external onlyOwner {
breeding.setMaxBreedableJuniors(max);
}
/**
* @notice function to set the cooldown period for breeding a slotie.
*
* @param coolDown. The new cooldown period.
*/
function BREEDOWNER_setBreedCoolDown(uint256 coolDown) external onlyOwner {
breeding.setBreedCoolDown(coolDown);
}
/**
* @notice function to set the watts price for breeding two sloties.
*
* @param price. The new watts price.
*/
function BREEDOWNER_setBreedPice(uint256 price) external onlyOwner {
breeding.setBreedPice(price);
}
function BREEDOWNER_TransferOwnership(address newOwner) external onlyOwner {
breeding.transferOwnership(newOwner);
}
/**
* @dev WATTS OWNER
*/
function WATTSOWNER_TransferOwnership(address newOwner) external onlyOwner {
breeding.WATTSOWNER_TransferOwnership(newOwner);
}
function WATTSOWNER_SetSlotieNFT(address newSlotie) external onlyOwner {
breeding.WATTSOWNER_SetSlotieNFT(newSlotie);
}
function WATTSOWNER_SetLockPeriod(uint256 newLockPeriod) external onlyOwner {
breeding.WATTSOWNER_SetLockPeriod(newLockPeriod);
}
function WATTSOWNER_SetIsBlackListed(address _set, bool _is) external onlyOwner {
breeding.WATTSOWNER_SetIsBlackListed(_set, _is);
}
function WATTSOWNER_seeClaimableBalanceOfUser(address user) external view returns (uint256) {
return breeding.WATTSOWNER_seeClaimableBalanceOfUser(user);
}
function WATTSOWNER_seeClaimableTotalSupply() external view returns (uint256) {
return breeding.WATTSOWNER_seeClaimableTotalSupply();
}
/**
* @dev FINANCE
*/
/**
* @notice Allows owner to withdraw funds generated from sale.
*
* @param _to. The address to send the funds to.
*/
function withdrawAll(address _to) external onlyOwner {
require(_to != address(0), "CANNOT WITHDRAW TO ZERO ADDRESS");
uint256 contractBalance = address(this).balance;
require(contractBalance > 0, "NO ETHER TO WITHDRAW");
payable(_to).transfer(contractBalance);
emit WithdrawAllEvent(_to, contractBalance);
}
/**
* @dev Fallback function for receiving Ether
*/
receive() external payable {
emit ReceivedEther(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/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);
} | function to set the merkle root for breeding. _merkleRoot. The new merkle root to set./ | function BREEDOWNER_setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
breeding.setMerkleRoot(_merkleRoot);
}
| 1,475,528 |
pragma solidity ^0.4.24;
/*--------------------------------------------------
____ ____ _
/ ___| _ _ _ __ ___ _ __ / ___|__ _ _ __ __| |
\___ \| | | | '_ \ / _ \ '__| | | / _` | '__/ _` |
___) | |_| | |_) | __/ | | |__| (_| | | | (_| |
|____/ \__,_| .__/ \___|_| \____\__,_|_| \__,_|
|_|
2018-08-08 V0.8
---------------------------------------------------*/
contract SPCevents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit, add pot directly by admin to next round
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract SuperCard is SPCevents {
using SafeMath for *;
using NameFilter for string;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xbac825cdb506dcf917a7715a4bf3fa1b06abe3e4);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
address private admin = msg.sender;
string constant public name = "SuperCard";
string constant public symbol = "SPC";
uint256 private rndExtra_ = 0; // length of the very first ICO
uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 6 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // last rID
uint256 public pID_; // last pID
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => SPCdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => SPCdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => SPCdatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
mapping (uint256 => uint256) public attend; // (index => pID) player ID attend current round
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => SPCdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => SPCdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
fees_[0] = SPCdatasets.TeamFee(80,2);
fees_[1] = SPCdatasets.TeamFee(80,2);
fees_[2] = SPCdatasets.TeamFee(80,2);
fees_[3] = SPCdatasets.TeamFee(80,2);
// how to split up the final pot based on which team was picked
potSplit_[0] = SPCdatasets.PotSplit(20,10);
potSplit_[1] = SPCdatasets.PotSplit(20,10);
potSplit_[2] = SPCdatasets.PotSplit(20,10);
potSplit_[3] = SPCdatasets.PotSplit(20,10);
/*
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
*/
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
if ( activated_ == false ){
if ( (now >= pre_active_time) && (pre_active_time > 0) ){
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
require(activated_ == true, "its not ready yet.");
_;
}
/**
* @dev prevents contracts from interacting with SuperCard
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
SPCdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
SPCdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core, team set to 2, snake
buyCore(_pID, _affID, 2, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
SPCdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core, team set to 2, snake
reLoadCore(_pID, _affID, _eth, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
SPCdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// reload core, team set to 2, snake
reLoadCore(_pID, _affCode, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
SPCdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core, team set to 2, snake
reLoadCore(_pID, _affID, _eth, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 myrID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 upperLimit = 0;
uint256 usedGen = 0;
// eth send to player
uint256 ethout = 0;
uint256 over_gen = 0;
updateGenVault(_pID, plyr_[_pID].lrnd);
if (plyr_[_pID].gen > 0)
{
upperLimit = (calceth(plyrRnds_[_pID][myrID].keys).mul(105))/100;
if(plyr_[_pID].gen >= upperLimit)
{
over_gen = (plyr_[_pID].gen).sub(upperLimit);
round_[myrID].keys = (round_[myrID].keys).sub(plyrRnds_[_pID][myrID].keys);
plyrRnds_[_pID][myrID].keys = 0;
round_[myrID].pot = (round_[myrID].pot).add(over_gen);
usedGen = upperLimit;
}
else
{
plyrRnds_[_pID][myrID].keys = (plyrRnds_[_pID][myrID].keys).sub(calckeys(((plyr_[_pID].gen).mul(100))/105));
round_[myrID].keys = (round_[myrID].keys).sub(calckeys(((plyr_[_pID].gen).mul(100))/105));
usedGen = plyr_[_pID].gen;
}
ethout = ((plyr_[_pID].win).add(plyr_[_pID].aff)).add(usedGen);
}
else
{
ethout = ((plyr_[_pID].win).add(plyr_[_pID].aff));
}
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
plyr_[_pID].addr.transfer(ethout);
// check to see if round has ended and no one has run round end yet
if (_now > round_[myrID].end && round_[myrID].ended == false && round_[myrID].plyr != 0)
{
// set up our tx event data
SPCdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[myrID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit SPCevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
ethout,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// fire withdraw event
emit SPCevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, ethout, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit SPCevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// price 0.01 ETH
return(10000000000000000);
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// if round has ended. but round end has not been run (so contract has not distributed winnings)
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
SPCdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core, team set to 2, snake
buyCore(_pID, _affID, 2, _eventData_);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, SPCdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, 2, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit SPCevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault, to win vault
plyr_[_pID].win = plyr_[_pID].win.add(msg.value);
}
}
/**
* @dev gen limit handle
*/
function genLimit(uint256 _pID)
private
returns(uint256)
{
// setup local rID
uint256 myrID = rID_;
uint256 upperLimit = 0;
uint256 usedGen = 0;
uint256 over_gen = 0;
uint256 eth_can_use = 0;
uint256 tempnum = 0;
updateGenVault(_pID, plyr_[_pID].lrnd);
if (plyr_[_pID].gen > 0)
{
upperLimit = ((plyrRnds_[_pID][myrID].keys).mul(105))/10000;
if(plyr_[_pID].gen >= upperLimit)
{
over_gen = (plyr_[_pID].gen).sub(upperLimit);
round_[myrID].keys = (round_[myrID].keys).sub(plyrRnds_[_pID][myrID].keys);
plyrRnds_[_pID][myrID].keys = 0;
round_[myrID].pot = (round_[myrID].pot).add(over_gen);
usedGen = upperLimit;
}
else
{
tempnum = ((plyr_[_pID].gen).mul(10000))/105;
plyrRnds_[_pID][myrID].keys = (plyrRnds_[_pID][myrID].keys).sub(tempnum);
round_[myrID].keys = (round_[myrID].keys).sub(tempnum);
usedGen = plyr_[_pID].gen;
}
eth_can_use = ((plyr_[_pID].win).add(plyr_[_pID].aff)).add(usedGen);
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
else
{
eth_can_use = (plyr_[_pID].win).add(plyr_[_pID].aff);
plyr_[_pID].win = 0;
plyr_[_pID].aff = 0;
}
return(eth_can_use);
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, SPCdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 myrID = rID_;
// grab time
uint256 _now = now;
uint256 eth_can_use = 0;
// if round is active
if (_now > round_[myrID].strt + rndGap_ && (_now <= round_[myrID].end || (_now > round_[myrID].end && round_[myrID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
eth_can_use = genLimit(_pID);
if(eth_can_use > 0)
{
// call core
core(myrID, _pID, eth_can_use, _affID, 2, _eventData_);
}
// if round is not active and end round needs to be ran
} else if (_now > round_[myrID].end && round_[myrID].ended == false) {
// end the round (distributes pot) & start new round
round_[myrID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit SPCevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, SPCdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round。
if (plyrRnds_[_pID][_rID].jionflag != 1)
{
_eventData_ = managePlayer(_pID, _eventData_);
plyrRnds_[_pID][_rID].jionflag = 1;
attend[round_[_rID].attendNum] = _pID;
round_[_rID].attendNum = (round_[_rID].attendNum).add(1);
}
if (_eth > 10000000000000000)
{
// mint the new keys
uint256 _keys = calckeys(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
round_[_rID].team = 2;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][2] = _eth.add(rndTmEth_[_rID][2]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, 2, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, 2, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, 2, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
uint256 temp;
temp = (round_[_rIDlast].mask).mul((plyrRnds_[_pID][_rIDlast].keys)/1000000000000000000);
if(temp > plyrRnds_[_pID][_rIDlast].mask)
{
return( temp.sub(plyrRnds_[_pID][_rIDlast].mask) );
}
else
{
return( 0 );
}
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
return ( calckeys(_eth) );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
return ( _keys/100 );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(SPCdatasets.EventReturns memory _eventData_)
private
returns (SPCdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of SuperCard
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
pID_ = _pID; // save Last pID
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, SPCdatasets.EventReturns memory _eventData_)
private
returns (SPCdatasets.EventReturns)
{
uint256 temp_eth = 0;
// if player has played a previous round, move their unmasked earnings
// from that round to win vault.
if (plyr_[_pID].lrnd != 0)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
temp_eth = ((plyr_[_pID].win).add((plyr_[_pID].gen))).add(plyr_[_pID].aff);
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
plyr_[_pID].win = temp_eth;
}
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(SPCdatasets.EventReturns memory _eventData_)
private
returns (SPCdatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(30)) / 100;
uint256 _com = (_pot / 10);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
_com = _com.add(_p3d.sub(_p3d / 2));
admin.transfer(_com);
_res = _res.add(_p3d / 2);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, SPCdatasets.EventReturns memory _eventData_)
private
returns(SPCdatasets.EventReturns)
{
// pay 3% out to community rewards
uint256 _p3d = (_eth/100).mul(3);
// distribute share to affiliate
// 5%:3%:2%
uint256 _aff_cent = (_eth) / 100;
uint256 tempID = _affID;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
// 5%
if (tempID != _pID && plyr_[tempID].name != '')
{
plyr_[tempID].aff = (_aff_cent.mul(5)).add(plyr_[tempID].aff);
emit SPCevents.onAffiliatePayout(tempID, plyr_[tempID].addr, plyr_[tempID].name, _rID, _pID, _aff_cent.mul(5), now);
}
else
{
_p3d = _p3d.add(_aff_cent.mul(5));
}
tempID = PlayerBook.getPlayerID(plyr_[tempID].addr);
tempID = PlayerBook.getPlayerLAff(tempID);
if (tempID != _pID && plyr_[tempID].name != '')
{
plyr_[tempID].aff = (_aff_cent.mul(3)).add(plyr_[tempID].aff);
emit SPCevents.onAffiliatePayout(tempID, plyr_[tempID].addr, plyr_[tempID].name, _rID, _pID, _aff_cent.mul(3), now);
}
else
{
_p3d = _p3d.add(_aff_cent.mul(3));
}
tempID = PlayerBook.getPlayerID(plyr_[tempID].addr);
tempID = PlayerBook.getPlayerLAff(tempID);
if (tempID != _pID && plyr_[tempID].name != '')
{
plyr_[tempID].aff = (_aff_cent.mul(2)).add(plyr_[tempID].aff);
emit SPCevents.onAffiliatePayout(tempID, plyr_[tempID].addr, plyr_[tempID].name, _rID, _pID, _aff_cent.mul(2), now);
}
else
{
_p3d = _p3d.add(_aff_cent.mul(2));
}
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[2].p3d)) / (100));
if (_p3d > 0)
{
admin.transfer(_p3d);
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
/**
* @dev
*/
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit SPCevents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, SPCdatasets.EventReturns memory _eventData_)
private
returns(SPCdatasets.EventReturns)
{
// calculate gen share,80%
uint256 _gen = (_eth.mul(fees_[2].gen)) / 100;
// pot 5%
uint256 _pot = (_eth.mul(5)) / 100;
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, SPCdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (2 * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit SPCevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
//uint256 public pre_active_time = 0;
uint256 public pre_active_time = now + 600 seconds;
/**
* @dev return active flag 、time
* @return active flag
* @return active time
* @return system time
*/
function getRunInfo() public view returns(bool, uint256, uint256)
{
return
(
activated_, //0
pre_active_time, //1
now //2
);
}
function setPreActiveTime(uint256 _pre_time) public
{
// only team just can activate
require(msg.sender == admin, "only admin can activate");
pre_active_time = _pre_time;
}
function activate()
public
{
// only team just can activate
require(msg.sender == admin, "only admin can activate");
// can only be ran once
require(activated_ == false, "SuperCard already activated");
// activate the contract
activated_ = true;
//activated_ = false;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
function calckeys(uint256 _eth)
pure
public
returns(uint256)
{
return ( (_eth).mul(100) );
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function calceth(uint256 _keys)
pure
public
returns(uint256)
{
return( (_keys)/100 );
}
function clearKeys(uint256 num)
public
{
// setup local rID
uint256 myrID = rID_;
uint256 number = num;
if(num == 1)
{
number = 10000;
}
uint256 over_gen;
uint256 cleared = 0;
uint256 checkID;
uint256 upperLimit;
uint256 i;
for(i = 0; i< round_[myrID].attendNum; i++)
{
checkID = attend[i];
updateGenVault(checkID, plyr_[checkID].lrnd);
if (plyr_[checkID].gen > 0)
{
upperLimit = ((plyrRnds_[checkID][myrID].keys).mul(105))/10000;
if(plyr_[checkID].gen >= upperLimit)
{
over_gen = (plyr_[checkID].gen).sub(upperLimit);
cleared = cleared.add(plyrRnds_[checkID][myrID].keys);
round_[myrID].keys = (round_[myrID].keys).sub(plyrRnds_[checkID][myrID].keys);
plyrRnds_[checkID][myrID].keys = 0;
round_[myrID].pot = (round_[myrID].pot).add(over_gen);
plyr_[checkID].win = ((plyr_[checkID].win).add(upperLimit));
plyr_[checkID].gen = 0;
if(cleared >= number)
break;
}
}
}
}
/**
* @dev calc Invalid Keys by rID&pId
*/
function calcInvalidKeys(uint256 _rID,uint256 _pID)
private
returns(uint256)
{
uint256 InvalidKeys = 0;
uint256 upperLimit = 0;
updateGenVault(_pID, plyr_[_pID].lrnd);
if (plyr_[_pID].gen > 0)
{
upperLimit = ((plyrRnds_[_pID][_rID].keys).mul(105))/10000;
if(plyr_[_pID].gen >= upperLimit)
{
InvalidKeys = InvalidKeys.add(plyrRnds_[_pID][_rID].keys);
}
}
return(InvalidKeys);
}
/**
* @dev return Invalid Keys
* @return Invalid Keys
* @return Total Keys
* @return timestamp
*/
function getInvalidKeys() public view returns(uint256,uint256,uint256)
{
uint256 LastRID = rID_;
uint256 LastPID = pID_;
uint256 _rID = 0;
uint256 _pID = 0;
uint256 InvalidKeys = 0;
uint256 TotalKeys = 0;
for( _rID = 1 ; _rID <= LastRID ; _rID++)
{
TotalKeys = TotalKeys.add(round_[_rID].keys);
for( _pID = 1 ; _pID <= LastPID ; _pID++)
{
InvalidKeys = InvalidKeys.add(calcInvalidKeys(_rID,_pID));
}
}
return
(
InvalidKeys, //0
TotalKeys, //1
now //2
);
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library SPCdatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 jionflag; // player not jion round
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
uint256 attendNum; // number of players attend
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
/**
* @title -Name Filter- v0.1.9
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
} | ============================================================================== | _ _ _ | _ . |<(/_\/ (_(_||(_ .=======/====================================================================== | function calckeys(uint256 _eth)
pure
public
returns(uint256)
{
return ( (_eth).mul(100) );
}
| 1,229,912 |
./partial_match/1/0xDD6ed60e9e09E2554910902552a54f5986eee9f9/sources/GeneralizedDotc.sol | Update the mutable pool settings./ | function updateVsErc20Pool(
bytes32 poolID,
LatestPriceOracleInterface swapPairOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4
) external {
require(_vsErc20Pool[poolID].seller == msg.sender, "not the owner of the pool ID");
_updateVsErc20Pool(poolID, swapPairOracleAddress, bondPricerAddress, feeBaseE4);
}
| 11,020,296 |
./full_match/3/0xa296622B2883F6b8B27e43BDe257d34d3487290D/sources/https_/github.com/Mimir-Solutions/holyzeppelin/blob/master/contracts/protocols/exchanges/uniswap/v2/core/interfaces/IUniswapV2Pair.sol | 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; | interface IUniswapV2Pair is IUniswapV2ERC20 {
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Sync(uint112 reserve0, uint112 reserve1);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
pragma solidity 0.7.5;
}
| 8,107,131 |
//SPDX-License-Identifier: UNLICENSED
// Solidity files have to start with this pragma.
// It will be used by the Solidity compiler to validate its version.
pragma solidity ^0.8.0;
pragma abicoder v2;
// We import this library to be able to use console.log
import "hardhat/console.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// Main contract
contract SubNav {
enum OwnershipRequestStatus { Pending, Validated, Denied }
// Subnets object
struct Subnet {
string name;
string description;
address owner;
}
// User object
struct User {
string mail;
string twitterHandle;
// P-chain address => signature made with P-Chain address
mapping(string => string) signedControlKeys;
}
// SubnetID => Subnet
mapping(string => Subnet) public subnets;
// Array of SubnetIDs known by the contract
string[] subnetIDs;
// C-chain address to User contract struct
mapping(address => User) public users;
// SubnetID => C-Chain address
mapping(string => address) public subnetOwners;
event SubnetOwnershipRequest(
address indexed ownerAddress,
string subnetID,
string status
);
// Register User
function registerUser(string calldata mail, string calldata twitterHandle) external {
users[msg.sender].mail = mail;
users[msg.sender].twitterHandle = twitterHandle;
}
// Add a Control key signature to a user's P-chain address dictionnary
function addControlKeySig(string calldata pChainAddress, string calldata signedControlKey) external {
users[msg.sender].signedControlKeys[pChainAddress] = signedControlKey;
}
// Request ownership of a subnet
// TO DO: create a request object to be validated by external authority based on P-Chain signature
function requestSubnetOwnership(string calldata subnetID) external {
emit SubnetOwnershipRequest(msg.sender, subnetID, 'Pending');
validateSubnetOwnership(subnetID, msg.sender);
}
// Validate ownership of a subnet
// TO DO: function to be called by a script after P-Chain signature verification
function validateSubnetOwnership(string calldata subnetID, address ownerAddress)
public
// onlyOwner
{
subnetOwners[subnetID] = ownerAddress;
emit SubnetOwnershipRequest(ownerAddress, subnetID, 'Validated');
}
function denySubnetOwnership(address ownerAddress, string calldata subnetID)
public
// onlyOwner
{
emit SubnetOwnershipRequest(ownerAddress, subnetID, 'Denied');
}
// Register Subnet
function registerSubnet(string calldata subnetID, string calldata name, string calldata description) external {
require(subnetOwners[subnetID] == msg.sender, "Sender is not the subnet owner");
subnets[subnetID].name = name;
subnets[subnetID].description = description;
subnets[subnetID].owner = msg.sender;
// Push the subnetID to the list of know SubnetIDs if it is the first time we encounter it
subnetIDs.push(subnetID);
}
// Return known SubnetIDs
function getSubnetIDs() external view returns (string[] memory) {
return subnetIDs;
}
}
| Validate ownership of a subnet TO DO: function to be called by a script after P-Chain signature verification onlyOwner | function validateSubnetOwnership(string calldata subnetID, address ownerAddress)
public
{
subnetOwners[subnetID] = ownerAddress;
emit SubnetOwnershipRequest(ownerAddress, subnetID, 'Validated');
}
| 982,817 |
/**
*Submitted for verification at Etherscan.io on 2021-07-12
*/
// Sources flattened with hardhat v2.4.1 https://hardhat.org
// File @openzeppelin/contracts/utils/introspection/[email protected]
// SPDX-License-Identifier: MIT AND Zlib
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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract 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/utils/[email protected]
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/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 @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract 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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/Defungify.sol
pragma solidity ^0.8.0;
contract Defungify is ERC721, ERC721Enumerable, ERC721URIStorage, ERC721Burnable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
mapping(uint256 => uint256) private _amountInside;
IERC20 public token;
constructor(IERC20 token_, string memory name, string memory symbol) ERC721(name, symbol) {
token = token_;
}
function safeMint(address to, uint256 amount, string memory uri) public {
// Mint NFT, set amount
_safeMint(to, _tokenIdCounter.current());
_setTokenURI(_tokenIdCounter.current(), uri);
_amountInside[_tokenIdCounter.current()] = amount;
_tokenIdCounter.increment();
// Send funds to contract
bool t = token.transferFrom(msg.sender, address(this), amount);
require(t, "token transfer failed");
}
function burn(uint256 tokenId) public override(ERC721Burnable) {
// Burn token, set amount to 0
super.burn(tokenId);
uint256 amount = _amountInside[tokenId];
_amountInside[tokenId] = 0;
// Send
bool t = token.transfer(msg.sender, amount);
require(t, "token transfer failed");
}
function amountInside(uint256 tokenId) public view returns (uint256) {
return _amountInside[tokenId];
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory){
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool){
return super.supportsInterface(interfaceId);
}
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File contracts/DefungifyFactory.sol
pragma solidity ^0.8.0;
contract DefungifyFactory {
mapping(IERC20Metadata => address) public deployedContracts;
event Created(address indexed creator, address indexed df, address indexed erc20Token);
constructor() {}
function deployDf(IERC20Metadata token) public returns (address) {
require(deployedContracts[token] == address(0), "defungify token already exists");
string memory name = string(abi.encodePacked("Defungify ", token.name()));
string memory symbol = string(abi.encodePacked("df", token.symbol()));
Defungify df = new Defungify(token, name, symbol);
emit Created(msg.sender, address(df), address(token));
deployedContracts[token] = address(df);
return address(df);
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
// File @openzeppelin/contracts/security/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/utils/structs/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// File @openzeppelin/contracts/token/ERC20/presets/[email protected]
pragma solidity ^0.8.0;
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// File contracts/imports.sol
pragma solidity ^0.8.0; | Burn token, set amount to 0 Send | function burn(uint256 tokenId) public override(ERC721Burnable) {
super.burn(tokenId);
uint256 amount = _amountInside[tokenId];
_amountInside[tokenId] = 0;
bool t = token.transfer(msg.sender, amount);
require(t, "token transfer failed");
}
| 2,304,439 |
// File: contracts/lib/LibBytes.sol
pragma solidity ^0.5.7;
// Modified from 0x LibBytes
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
if (from > to || to > b.length) {
return "";
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
require(
b.length >= index + 4,
"GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
}
// File: contracts/lib/LibMath.sol
pragma solidity ^0.5.7;
contract LibMath {
// Copied from openzeppelin 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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
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);
}
// Modified from openzeppelin 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;
}
// Copied from 0x LibMath
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
require(
!isRoundingErrorFloor(
numerator,
denominator,
target
),
"ROUNDING_ERROR"
);
partialAmount = div(
mul(numerator, target),
denominator
);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
require(
!isRoundingErrorCeil(
numerator,
denominator,
target
),
"ROUNDING_ERROR"
);
partialAmount = div(
add(
mul(numerator, target),
sub(denominator, 1)
),
denominator
);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
partialAmount = div(
mul(numerator, target),
denominator
);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
partialAmount = div(
add(
mul(numerator, target),
sub(denominator, 1)
),
denominator
);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = mul(1000, remainder) >= mul(numerator, target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = sub(denominator, remainder) % denominator;
isError = mul(1000, remainder) >= mul(numerator, target);
return isError;
}
}
// File: contracts/lib/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: contracts/lib/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
// File: contracts/bank/IBank.sol
pragma solidity ^0.5.7;
/// Bank Interface.
interface IBank {
/// Modifies authorization of an address. Only contract owner can call this function.
/// @param target Address to authorize / deauthorize.
/// @param allowed Whether the target address is authorized.
function authorize(address target, bool allowed) external;
/// Modifies user approvals of an address.
/// @param target Address to approve / unapprove.
/// @param allowed Whether the target address is user approved.
function userApprove(address target, bool allowed) external;
/// Batch modifies user approvals.
/// @param targetList Array of addresses to approve / unapprove.
/// @param allowedList Array of booleans indicating whether the target address is user approved.
function batchUserApprove(address[] calldata targetList, bool[] calldata allowedList) external;
/// Gets all authorized addresses.
/// @return Array of authorized addresses.
function getAuthorizedAddresses() external view returns (address[] memory);
/// Gets all user approved addresses.
/// @return Array of user approved addresses.
function getUserApprovedAddresses() external view returns (address[] memory);
/// Checks whether the user has enough deposit.
/// @param token Token address.
/// @param user User address.
/// @param amount Token amount.
/// @param data Additional token data (e.g. tokenId for ERC721).
/// @return Whether the user has enough deposit.
function hasDeposit(address token, address user, uint256 amount, bytes calldata data) external view returns (bool);
/// Checks token balance available to use (including user deposit amount + user approved allowance amount).
/// @param token Token address.
/// @param user User address.
/// @param data Additional token data (e.g. tokenId for ERC721).
/// @return Token amount available.
function getAvailable(address token, address user, bytes calldata data) external view returns (uint256);
/// Gets balance of user's deposit.
/// @param token Token address.
/// @param user User address.
/// @return Token deposit amount.
function balanceOf(address token, address user) external view returns (uint256);
/// Deposits token from user wallet to bank.
/// @param token Token address.
/// @param user User address (allows third-party give tokens to any users).
/// @param amount Token amount.
/// @param data Additional token data (e.g. tokenId for ERC721).
function deposit(address token, address user, uint256 amount, bytes calldata data) external payable;
/// Withdraws token from bank to user wallet.
/// @param token Token address.
/// @param amount Token amount.
/// @param data Additional token data (e.g. tokenId for ERC721).
function withdraw(address token, uint256 amount, bytes calldata data) external;
/// Transfers token from one address to another address.
/// Only caller who are double-approved by both bank owner and token owner can invoke this function.
/// @param token Token address.
/// @param from The current token owner address.
/// @param to The new token owner address.
/// @param amount Token amount.
/// @param data Additional token data (e.g. tokenId for ERC721).
/// @param fromDeposit True if use fund from bank deposit. False if use fund from user wallet.
/// @param toDeposit True if deposit fund to bank deposit. False if send fund to user wallet.
function transferFrom(
address token,
address from,
address to,
uint256 amount,
bytes calldata data,
bool fromDeposit,
bool toDeposit
)
external;
}
// File: contracts/Common.sol
pragma solidity ^0.5.7;
contract Common {
struct Order {
address maker;
address taker;
address makerToken;
address takerToken;
address makerTokenBank;
address takerTokenBank;
address reseller;
address verifier;
uint256 makerAmount;
uint256 takerAmount;
uint256 expires;
uint256 nonce;
uint256 minimumTakerAmount;
bytes makerData;
bytes takerData;
bytes signature;
}
struct OrderInfo {
uint8 orderStatus;
bytes32 orderHash;
uint256 filledTakerAmount;
}
struct FillResults {
uint256 makerFilledAmount;
uint256 makerFeeExchange;
uint256 makerFeeReseller;
uint256 takerFilledAmount;
uint256 takerFeeExchange;
uint256 takerFeeReseller;
}
struct MatchedFillResults {
FillResults left;
FillResults right;
uint256 spreadAmount;
}
}
// File: contracts/verifier/Verifier.sol
pragma solidity ^0.5.7;
/// An abstract Contract of Verifier.
contract Verifier is Common {
/// Verifies trade for KYC purposes.
/// @param order Order object.
/// @param takerAmountToFill Desired amount of takerToken to sell.
/// @param taker Taker address.
/// @return Whether the trade is valid.
function verify(
Order memory order,
uint256 takerAmountToFill,
address taker
)
public
view
returns (bool);
/// Verifies user address for KYC purposes.
/// @param user User address.
/// @return Whether the user address is valid.
function verifyUser(address user)
external
view
returns (bool);
}
// File: contracts/EverbloomExchange.sol
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
/// Everbloom core exchange contract.
contract EverbloomExchange is Ownable, ReentrancyGuard, LibMath {
using LibBytes for bytes;
// All fees cannot beyond this percentage.
uint256 public constant MAX_FEE_PERCENTAGE = 0.005 * 10 ** 18; // 0.5%
// Exchange fee account.
address public feeAccount;
// Exchange fee schedule.
// fees[reseller][0] is maker fee charged by exchange.
// fees[reseller][1] is maker fee charged by reseller.
// fees[reseller][2] is taker fee charged by exchange.
// fees[reseller][3] is taker fee charged by reseller.
// fees[0][0] is default maker fee charged by exchange if no reseller.
// fees[0][1] is always 0 if no reseller.
// fees[0][2] is default taker fee charged by exchange if no reseller.
// fees[0][3] is always 0 if no reseller.
mapping(address => uint256[4]) public fees;
// Mapping of order filled amounts.
// filled[orderHash] = filledAmount
mapping(bytes32 => uint256) filled;
// Mapping of cancelled orders.
// cancelled[orderHash] = isCancelled
mapping(bytes32 => bool) cancelled;
// Mapping of different types of whitelists.
// whitelists[whitelistType][address] = isAllowed
mapping(uint8 => mapping(address => bool)) whitelists;
enum WhitelistType {
BANK,
FEE_EXEMPT_BANK, // No percentage fees for non-dividable tokens.
RESELLER,
VERIFIER
}
enum OrderStatus {
INVALID,
INVALID_SIGNATURE,
INVALID_MAKER_AMOUNT,
INVALID_TAKER_AMOUNT,
FILLABLE,
EXPIRED,
FULLY_FILLED,
CANCELLED
}
event SetFeeAccount(address feeAccount);
event SetFee(address reseller, uint256 makerFee, uint256 takerFee);
event SetWhitelist(uint8 wlType, address addr, bool allowed);
event CancelOrder(
bytes32 indexed orderHash,
address indexed maker,
address makerToken,
address takerToken,
address indexed reseller,
uint256 makerAmount,
uint256 takerAmount,
bytes makerData,
bytes takerData
);
event FillOrder(
bytes32 indexed orderHash,
address indexed maker,
address taker,
address makerToken,
address takerToken,
address indexed reseller,
uint256 makerFilledAmount,
uint256 makerFeeExchange,
uint256 makerFeeReseller,
uint256 takerFilledAmount,
uint256 takerFeeExchange,
uint256 takerFeeReseller,
bytes makerData,
bytes takerData
);
/// Sets fee account. Only contract owner can call this function.
/// @param _feeAccount Fee account address.
function setFeeAccount(
address _feeAccount
)
public
onlyOwner
{
feeAccount = _feeAccount;
emit SetFeeAccount(_feeAccount);
}
/// Sets fee schedule. Only contract owner can call this function.
/// Each fee is a fraction of 1 ETH in wei.
/// @param reseller Reseller address.
/// @param _fees Array of four fees: makerFeeExchange, makerFeeReseller, takerFeeExchange, takerFeeReseller.
function setFee(
address reseller,
uint256[4] calldata _fees
)
external
onlyOwner
{
if (reseller == address(0)) {
// If reseller is not set, reseller fee should not be set.
require(_fees[1] == 0 && _fees[3] == 0, "INVALID_NULL_RESELLER_FEE");
}
uint256 makerFee = add(_fees[0], _fees[1]);
uint256 takerFee = add(_fees[2], _fees[3]);
// Total fees of an order should not beyond MAX_FEE_PERCENTAGE.
require(add(makerFee, takerFee) <= MAX_FEE_PERCENTAGE, "FEE_TOO_HIGH");
fees[reseller] = _fees;
emit SetFee(reseller, makerFee, takerFee);
}
/// Sets address whitelist. Only contract owner can call this function.
/// @param wlType Whitelist type (defined in enum WhitelistType, e.g. BANK).
/// @param addr An address (e.g. a trusted bank address).
/// @param allowed Whether the address is trusted.
function setWhitelist(
WhitelistType wlType,
address addr,
bool allowed
)
external
onlyOwner
{
whitelists[uint8(wlType)][addr] = allowed;
emit SetWhitelist(uint8(wlType), addr, allowed);
}
/// Cancels an order. Only order maker can call this function.
/// @param order Order object.
function cancelOrder(
Common.Order memory order
)
public
nonReentrant
{
cancelOrderInternal(order);
}
/// Cancels multiple orders by batch. Only order maker can call this function.
/// @param orderList Array of order objects.
function cancelOrders(
Common.Order[] memory orderList
)
public
nonReentrant
{
for (uint256 i = 0; i < orderList.length; i++) {
cancelOrderInternal(orderList[i]);
}
}
/// Fills an order.
/// @param order Order object.
/// @param takerAmountToFill Desired amount of takerToken to sell.
/// @param allowInsufficient Whether insufficient order remaining is allowed to fill.
/// @return results Amounts filled and fees paid by maker and taker.
function fillOrder(
Common.Order memory order,
uint256 takerAmountToFill,
bool allowInsufficient
)
public
nonReentrant
returns (Common.FillResults memory results)
{
results = fillOrderInternal(
order,
takerAmountToFill,
allowInsufficient
);
return results;
}
/// Fills an order without throwing an exception.
/// @param order Order object.
/// @param takerAmountToFill Desired amount of takerToken to sell.
/// @param allowInsufficient Whether insufficient order remaining is allowed to fill.
/// @return results Amounts filled and fees paid by maker and taker.
function fillOrderNoThrow(
Common.Order memory order,
uint256 takerAmountToFill,
bool allowInsufficient
)
public
returns (Common.FillResults memory results)
{
bytes memory callData = abi.encodeWithSelector(
this.fillOrder.selector,
order,
takerAmountToFill,
allowInsufficient
);
assembly {
// Use raw assembly call to fill order and avoid EVM reverts.
let success := delegatecall(
gas, // forward all gas.
address, // call address of this contract.
add(callData, 32), // pointer to start of input (skip array length in first 32 bytes).
mload(callData), // length of input.
callData, // write output over input.
192 // output size is 192 bytes.
)
// Copy output data.
if success {
mstore(results, mload(callData))
mstore(add(results, 32), mload(add(callData, 32)))
mstore(add(results, 64), mload(add(callData, 64)))
mstore(add(results, 96), mload(add(callData, 96)))
mstore(add(results, 128), mload(add(callData, 128)))
mstore(add(results, 160), mload(add(callData, 160)))
}
}
return results;
}
/// Fills multiple orders by batch.
/// @param orderList Array of order objects.
/// @param takerAmountToFillList Array of desired amounts of takerToken to sell.
/// @param allowInsufficientList Array of booleans that whether insufficient order remaining is allowed to fill.
function fillOrders(
Common.Order[] memory orderList,
uint256[] memory takerAmountToFillList,
bool[] memory allowInsufficientList
)
public
nonReentrant
{
for (uint256 i = 0; i < orderList.length; i++) {
fillOrderInternal(
orderList[i],
takerAmountToFillList[i],
allowInsufficientList[i]
);
}
}
/// Fills multiple orders by batch without throwing an exception.
/// @param orderList Array of order objects.
/// @param takerAmountToFillList Array of desired amounts of takerToken to sell.
/// @param allowInsufficientList Array of booleans that whether insufficient order remaining is allowed to fill.
function fillOrdersNoThrow(
Common.Order[] memory orderList,
uint256[] memory takerAmountToFillList,
bool[] memory allowInsufficientList
)
public
nonReentrant
{
for (uint256 i = 0; i < orderList.length; i++) {
fillOrderNoThrow(
orderList[i],
takerAmountToFillList[i],
allowInsufficientList[i]
);
}
}
/// Match two complementary orders that have a profitable spread.
/// NOTE: (leftOrder.makerAmount / leftOrder.takerAmount) should be always greater than or equal to
/// (rightOrder.takerAmount / rightOrder.makerAmount).
/// @param leftOrder First order object to match.
/// @param rightOrder Second order object to match.
/// @param spreadReceiver Address to receive a profitable spread.
/// @param results Fill results of matched orders and spread amount.
function matchOrders(
Common.Order memory leftOrder,
Common.Order memory rightOrder,
address spreadReceiver
)
public
nonReentrant
returns (Common.MatchedFillResults memory results)
{
// Matching orders pre-check.
require(
leftOrder.makerToken == rightOrder.takerToken &&
leftOrder.takerToken == rightOrder.makerToken &&
mul(leftOrder.makerAmount, rightOrder.makerAmount) >= mul(leftOrder.takerAmount, rightOrder.takerAmount),
"UNMATCHED_ORDERS"
);
Common.OrderInfo memory leftOrderInfo = getOrderInfo(leftOrder);
Common.OrderInfo memory rightOrderInfo = getOrderInfo(rightOrder);
results = calculateMatchedFillResults(
leftOrder,
rightOrder,
leftOrderInfo.filledTakerAmount,
rightOrderInfo.filledTakerAmount
);
assertFillableOrder(
leftOrder,
leftOrderInfo,
msg.sender,
results.left.takerFilledAmount
);
assertFillableOrder(
rightOrder,
rightOrderInfo,
msg.sender,
results.right.takerFilledAmount
);
settleMatchedOrders(leftOrder, rightOrder, results, spreadReceiver);
filled[leftOrderInfo.orderHash] = add(leftOrderInfo.filledTakerAmount, results.left.takerFilledAmount);
filled[rightOrderInfo.orderHash] = add(rightOrderInfo.filledTakerAmount, results.right.takerFilledAmount);
emitFillOrderEvent(leftOrderInfo.orderHash, leftOrder, results.left);
emitFillOrderEvent(rightOrderInfo.orderHash, rightOrder, results.right);
return results;
}
/// Given a list of orders, fill them in sequence until total taker amount is reached.
/// NOTE: All orders should be in the same token pair.
/// @param orderList Array of order objects.
/// @param totalTakerAmountToFill Stop filling when the total taker amount is reached.
/// @return totalFillResults Total amounts filled and fees paid by maker and taker.
function marketTakerOrders(
Common.Order[] memory orderList,
uint256 totalTakerAmountToFill
)
public
returns (Common.FillResults memory totalFillResults)
{
for (uint256 i = 0; i < orderList.length; i++) {
Common.FillResults memory singleFillResults = fillOrderNoThrow(
orderList[i],
sub(totalTakerAmountToFill, totalFillResults.takerFilledAmount),
true
);
addFillResults(totalFillResults, singleFillResults);
if (totalFillResults.takerFilledAmount >= totalTakerAmountToFill) {
break;
}
}
return totalFillResults;
}
/// Given a list of orders, fill them in sequence until total maker amount is reached.
/// NOTE: All orders should be in the same token pair.
/// @param orderList Array of order objects.
/// @param totalMakerAmountToFill Stop filling when the total maker amount is reached.
/// @return totalFillResults Total amounts filled and fees paid by maker and taker.
function marketMakerOrders(
Common.Order[] memory orderList,
uint256 totalMakerAmountToFill
)
public
returns (Common.FillResults memory totalFillResults)
{
for (uint256 i = 0; i < orderList.length; i++) {
Common.FillResults memory singleFillResults = fillOrderNoThrow(
orderList[i],
getPartialAmountFloor(
orderList[i].takerAmount, orderList[i].makerAmount,
sub(totalMakerAmountToFill, totalFillResults.makerFilledAmount)
),
true
);
addFillResults(totalFillResults, singleFillResults);
if (totalFillResults.makerFilledAmount >= totalMakerAmountToFill) {
break;
}
}
return totalFillResults;
}
/// Gets information about an order.
/// @param order Order object.
/// @return orderInfo Information about the order status, order hash, and filled amount.
function getOrderInfo(Common.Order memory order)
public
view
returns (Common.OrderInfo memory orderInfo)
{
orderInfo.orderHash = getOrderHash(order);
orderInfo.filledTakerAmount = filled[orderInfo.orderHash];
if (
!whitelists[uint8(WhitelistType.RESELLER)][order.reseller] ||
!whitelists[uint8(WhitelistType.VERIFIER)][order.verifier] ||
!whitelists[uint8(WhitelistType.BANK)][order.makerTokenBank] ||
!whitelists[uint8(WhitelistType.BANK)][order.takerTokenBank]
) {
orderInfo.orderStatus = uint8(OrderStatus.INVALID);
return orderInfo;
}
if (!isValidSignature(orderInfo.orderHash, order.maker, order.signature)) {
orderInfo.orderStatus = uint8(OrderStatus.INVALID_SIGNATURE);
return orderInfo;
}
if (order.makerAmount == 0) {
orderInfo.orderStatus = uint8(OrderStatus.INVALID_MAKER_AMOUNT);
return orderInfo;
}
if (order.takerAmount == 0) {
orderInfo.orderStatus = uint8(OrderStatus.INVALID_TAKER_AMOUNT);
return orderInfo;
}
if (orderInfo.filledTakerAmount >= order.takerAmount) {
orderInfo.orderStatus = uint8(OrderStatus.FULLY_FILLED);
return orderInfo;
}
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= order.expires) {
orderInfo.orderStatus = uint8(OrderStatus.EXPIRED);
return orderInfo;
}
if (cancelled[orderInfo.orderHash]) {
orderInfo.orderStatus = uint8(OrderStatus.CANCELLED);
return orderInfo;
}
orderInfo.orderStatus = uint8(OrderStatus.FILLABLE);
return orderInfo;
}
/// Calculates hash of an order.
/// @param order Order object.
/// @return Hash of order.
function getOrderHash(Common.Order memory order)
public
view
returns (bytes32)
{
bytes memory part1 = abi.encodePacked(
address(this),
order.maker,
order.taker,
order.makerToken,
order.takerToken,
order.makerTokenBank,
order.takerTokenBank,
order.reseller,
order.verifier
);
bytes memory part2 = abi.encodePacked(
order.makerAmount,
order.takerAmount,
order.expires,
order.nonce,
order.minimumTakerAmount,
order.makerData,
order.takerData
);
return keccak256(abi.encodePacked(part1, part2));
}
/// Cancels an order.
/// @param order Order object.
function cancelOrderInternal(
Common.Order memory order
)
internal
{
Common.OrderInfo memory orderInfo = getOrderInfo(order);
require(orderInfo.orderStatus == uint8(OrderStatus.FILLABLE), "ORDER_UNFILLABLE");
require(order.maker == msg.sender, "INVALID_MAKER");
cancelled[orderInfo.orderHash] = true;
emit CancelOrder(
orderInfo.orderHash,
order.maker,
order.makerToken,
order.takerToken,
order.reseller,
order.makerAmount,
order.takerAmount,
order.makerData,
order.takerData
);
}
/// Fills an order.
/// @param order Order object.
/// @param takerAmountToFill Desired amount of takerToken to sell.
/// @param allowInsufficient Whether insufficient order remaining is allowed to fill.
/// @return results Amounts filled and fees paid by maker and taker.
function fillOrderInternal(
Common.Order memory order,
uint256 takerAmountToFill,
bool allowInsufficient
)
internal
returns (Common.FillResults memory results)
{
require(takerAmountToFill > 0, "INVALID_TAKER_AMOUNT");
Common.OrderInfo memory orderInfo = getOrderInfo(order);
uint256 remainingTakerAmount = sub(order.takerAmount, orderInfo.filledTakerAmount);
if (allowInsufficient) {
takerAmountToFill = min(takerAmountToFill, remainingTakerAmount);
} else {
require(takerAmountToFill <= remainingTakerAmount, "INSUFFICIENT_ORDER_REMAINING");
}
assertFillableOrder(
order,
orderInfo,
msg.sender,
takerAmountToFill
);
results = settleOrder(order, takerAmountToFill);
filled[orderInfo.orderHash] = add(orderInfo.filledTakerAmount, results.takerFilledAmount);
emitFillOrderEvent(orderInfo.orderHash, order, results);
return results;
}
/// Emits a FillOrder event.
/// @param orderHash Hash of order.
/// @param order Order object.
/// @param results Order fill results.
function emitFillOrderEvent(
bytes32 orderHash,
Common.Order memory order,
Common.FillResults memory results
)
internal
{
emit FillOrder(
orderHash,
order.maker,
msg.sender,
order.makerToken,
order.takerToken,
order.reseller,
results.makerFilledAmount,
results.makerFeeExchange,
results.makerFeeReseller,
results.takerFilledAmount,
results.takerFeeExchange,
results.takerFeeReseller,
order.makerData,
order.takerData
);
}
/// Validates context for fillOrder. Succeeds or throws.
/// @param order Order object to be filled.
/// @param orderInfo Information about the order status, order hash, and amount already filled of order.
/// @param taker Address of order taker.
/// @param takerAmountToFill Desired amount of takerToken to sell.
function assertFillableOrder(
Common.Order memory order,
Common.OrderInfo memory orderInfo,
address taker,
uint256 takerAmountToFill
)
view
internal
{
// An order can only be filled if its status is FILLABLE.
require(orderInfo.orderStatus == uint8(OrderStatus.FILLABLE), "ORDER_UNFILLABLE");
// Validate taker is allowed to fill this order.
if (order.taker != address(0)) {
require(order.taker == taker, "INVALID_TAKER");
}
// Validate minimum taker amount.
if (order.minimumTakerAmount > 0) {
require(takerAmountToFill >= order.minimumTakerAmount, "ORDER_MINIMUM_UNREACHED");
}
// Go through Verifier.
if (order.verifier != address(0)) {
require(Verifier(order.verifier).verify(order, takerAmountToFill, msg.sender), "FAILED_VALIDATION");
}
}
/// Verifies that an order signature is valid.
/// @param hash Message hash that is signed.
/// @param signer Address of signer.
/// @param signature Order signature.
/// @return Validity of order signature.
function isValidSignature(
bytes32 hash,
address signer,
bytes memory signature
)
internal
pure
returns (bool)
{
uint8 v = uint8(signature[0]);
bytes32 r = signature.readBytes32(1);
bytes32 s = signature.readBytes32(33);
return signer == ecrecover(
keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
hash
)),
v,
r,
s
);
}
/// Adds properties of a single FillResults to total FillResults.
/// @param totalFillResults Fill results instance that will be added onto.
/// @param singleFillResults Fill results instance that will be added to totalFillResults.
function addFillResults(
Common.FillResults memory totalFillResults,
Common.FillResults memory singleFillResults
)
internal
pure
{
totalFillResults.makerFilledAmount = add(totalFillResults.makerFilledAmount, singleFillResults.makerFilledAmount);
totalFillResults.makerFeeExchange = add(totalFillResults.makerFeeExchange, singleFillResults.makerFeeExchange);
totalFillResults.makerFeeReseller = add(totalFillResults.makerFeeReseller, singleFillResults.makerFeeReseller);
totalFillResults.takerFilledAmount = add(totalFillResults.takerFilledAmount, singleFillResults.takerFilledAmount);
totalFillResults.takerFeeExchange = add(totalFillResults.takerFeeExchange, singleFillResults.takerFeeExchange);
totalFillResults.takerFeeReseller = add(totalFillResults.takerFeeReseller, singleFillResults.takerFeeReseller);
}
/// Settles an order by swapping funds and paying fees.
/// @param order Order object.
/// @param takerAmountToFill Desired amount of takerToken to sell.
/// @param results Amounts to be filled and fees paid by maker and taker.
function settleOrder(
Common.Order memory order,
uint256 takerAmountToFill
)
internal
returns (Common.FillResults memory results)
{
results.takerFilledAmount = takerAmountToFill;
results.makerFilledAmount = safeGetPartialAmountFloor(order.makerAmount, order.takerAmount, results.takerFilledAmount);
// Calculate maker fees if makerTokenBank is non-fee-exempt.
if (!whitelists[uint8(WhitelistType.FEE_EXEMPT_BANK)][order.makerTokenBank]) {
if (fees[order.reseller][0] > 0) {
results.makerFeeExchange = mul(results.makerFilledAmount, fees[order.reseller][0]) / (1 ether);
}
if (fees[order.reseller][1] > 0) {
results.makerFeeReseller = mul(results.makerFilledAmount, fees[order.reseller][1]) / (1 ether);
}
}
// Calculate taker fees if takerTokenBank is non-fee-exempt.
if (!whitelists[uint8(WhitelistType.FEE_EXEMPT_BANK)][order.takerTokenBank]) {
if (fees[order.reseller][2] > 0) {
results.takerFeeExchange = mul(results.takerFilledAmount, fees[order.reseller][2]) / (1 ether);
}
if (fees[order.reseller][3] > 0) {
results.takerFeeReseller = mul(results.takerFilledAmount, fees[order.reseller][3]) / (1 ether);
}
}
if (results.makerFeeExchange > 0) {
// Transfer maker fee to exchange fee account.
IBank(order.makerTokenBank).transferFrom(
order.makerToken,
order.maker,
feeAccount,
results.makerFeeExchange,
order.makerData,
true,
false
);
}
if (results.makerFeeReseller > 0) {
// Transfer maker fee to reseller fee account.
IBank(order.makerTokenBank).transferFrom(
order.makerToken,
order.maker,
order.reseller,
results.makerFeeReseller,
order.makerData,
true,
false
);
}
if (results.takerFeeExchange > 0) {
// Transfer taker fee to exchange fee account.
IBank(order.takerTokenBank).transferFrom(
order.takerToken,
msg.sender,
feeAccount,
results.takerFeeExchange,
order.takerData,
true,
false
);
}
if (results.takerFeeReseller > 0) {
// Transfer taker fee to reseller fee account.
IBank(order.takerTokenBank).transferFrom(
order.takerToken,
msg.sender,
order.reseller,
results.takerFeeReseller,
order.takerData,
true,
false
);
}
// Transfer tokens from maker to taker.
IBank(order.makerTokenBank).transferFrom(
order.makerToken,
order.maker,
msg.sender,
results.makerFilledAmount,
order.makerData,
true,
true
);
// Transfer tokens from taker to maker.
IBank(order.takerTokenBank).transferFrom(
order.takerToken,
msg.sender,
order.maker,
results.takerFilledAmount,
order.takerData,
true,
true
);
}
/// Calculates fill amounts for matched orders that have a profitable spread.
/// NOTE: (leftOrder.makerAmount / leftOrder.takerAmount) should be always greater than or equal to
/// (rightOrder.takerAmount / rightOrder.makerAmount).
/// @param leftOrder First order object to match.
/// @param rightOrder Second order object to match.
/// @param leftFilledTakerAmount Amount of left order already filled.
/// @param rightFilledTakerAmount Amount of right order already filled.
/// @param results Fill results of matched orders and spread amount.
function calculateMatchedFillResults(
Common.Order memory leftOrder,
Common.Order memory rightOrder,
uint256 leftFilledTakerAmount,
uint256 rightFilledTakerAmount
)
internal
view
returns (Common.MatchedFillResults memory results)
{
uint256 leftRemainingTakerAmount = sub(leftOrder.takerAmount, leftFilledTakerAmount);
uint256 leftRemainingMakerAmount = safeGetPartialAmountFloor(
leftOrder.makerAmount,
leftOrder.takerAmount,
leftRemainingTakerAmount
);
uint256 rightRemainingTakerAmount = sub(rightOrder.takerAmount, rightFilledTakerAmount);
uint256 rightRemainingMakerAmount = safeGetPartialAmountFloor(
rightOrder.makerAmount,
rightOrder.takerAmount,
rightRemainingTakerAmount
);
if (leftRemainingTakerAmount >= rightRemainingMakerAmount) {
// Case 1: Right order is fully filled.
results.right.makerFilledAmount = rightRemainingMakerAmount;
results.right.takerFilledAmount = rightRemainingTakerAmount;
results.left.takerFilledAmount = results.right.makerFilledAmount;
// Round down to ensure the maker's exchange rate does not exceed the price specified by the order.
// We favor the maker when the exchange rate must be rounded.
results.left.makerFilledAmount = safeGetPartialAmountFloor(
leftOrder.makerAmount,
leftOrder.takerAmount,
results.left.takerFilledAmount
);
} else {
// Case 2: Left order is fully filled.
results.left.makerFilledAmount = leftRemainingMakerAmount;
results.left.takerFilledAmount = leftRemainingTakerAmount;
results.right.makerFilledAmount = results.left.takerFilledAmount;
// Round up to ensure the maker's exchange rate does not exceed the price specified by the order.
// We favor the maker when the exchange rate must be rounded.
results.right.takerFilledAmount = safeGetPartialAmountCeil(
rightOrder.takerAmount,
rightOrder.makerAmount,
results.right.makerFilledAmount
);
}
results.spreadAmount = sub(
results.left.makerFilledAmount,
results.right.takerFilledAmount
);
if (!whitelists[uint8(WhitelistType.FEE_EXEMPT_BANK)][leftOrder.makerTokenBank]) {
if (fees[leftOrder.reseller][0] > 0) {
results.left.makerFeeExchange = mul(results.left.makerFilledAmount, fees[leftOrder.reseller][0]) / (1 ether);
}
if (fees[leftOrder.reseller][1] > 0) {
results.left.makerFeeReseller = mul(results.left.makerFilledAmount, fees[leftOrder.reseller][1]) / (1 ether);
}
}
if (!whitelists[uint8(WhitelistType.FEE_EXEMPT_BANK)][rightOrder.makerTokenBank]) {
if (fees[rightOrder.reseller][2] > 0) {
results.right.makerFeeExchange = mul(results.right.makerFilledAmount, fees[rightOrder.reseller][2]) / (1 ether);
}
if (fees[rightOrder.reseller][3] > 0) {
results.right.makerFeeReseller = mul(results.right.makerFilledAmount, fees[rightOrder.reseller][3]) / (1 ether);
}
}
return results;
}
/// Settles matched order by swapping funds, paying fees and transferring spread.
/// @param leftOrder First matched order object.
/// @param rightOrder Second matched order object.
/// @param results Fill results of matched orders and spread amount.
/// @param spreadReceiver Address to receive a profitable spread.
function settleMatchedOrders(
Common.Order memory leftOrder,
Common.Order memory rightOrder,
Common.MatchedFillResults memory results,
address spreadReceiver
)
internal
{
if (results.left.makerFeeExchange > 0) {
// Transfer left maker fee to exchange fee account.
IBank(leftOrder.makerTokenBank).transferFrom(
leftOrder.makerToken,
leftOrder.maker,
feeAccount,
results.left.makerFeeExchange,
leftOrder.makerData,
true,
false
);
}
if (results.left.makerFeeReseller > 0) {
// Transfer left maker fee to reseller fee account.
IBank(leftOrder.makerTokenBank).transferFrom(
leftOrder.makerToken,
leftOrder.maker,
leftOrder.reseller,
results.left.makerFeeReseller,
leftOrder.makerData,
true,
false
);
}
if (results.right.makerFeeExchange > 0) {
// Transfer right maker fee to exchange fee account.
IBank(rightOrder.makerTokenBank).transferFrom(
rightOrder.makerToken,
rightOrder.maker,
feeAccount,
results.right.makerFeeExchange,
rightOrder.makerData,
true,
false
);
}
if (results.right.makerFeeReseller > 0) {
// Transfer right maker fee to reseller fee account.
IBank(rightOrder.makerTokenBank).transferFrom(
rightOrder.makerToken,
rightOrder.maker,
rightOrder.reseller,
results.right.makerFeeReseller,
rightOrder.makerData,
true,
false
);
}
// Note that there's no taker fees for matched orders.
// Transfer tokens from left order maker to right order maker.
IBank(leftOrder.makerTokenBank).transferFrom(
leftOrder.makerToken,
leftOrder.maker,
rightOrder.maker,
results.right.takerFilledAmount,
leftOrder.makerData,
true,
true
);
// Transfer tokens from right order maker to left order maker.
IBank(rightOrder.makerTokenBank).transferFrom(
rightOrder.makerToken,
rightOrder.maker,
leftOrder.maker,
results.left.takerFilledAmount,
rightOrder.makerData,
true,
true
);
if (results.spreadAmount > 0) {
// Transfer spread to spread receiver.
IBank(leftOrder.makerTokenBank).transferFrom(
leftOrder.makerToken,
leftOrder.maker,
spreadReceiver,
results.spreadAmount,
leftOrder.makerData,
true,
false
);
}
}
} | Given a list of orders, fill them in sequence until total maker amount is reached. NOTE: All orders should be in the same token pair. orderList Array of order objects. totalMakerAmountToFill Stop filling when the total maker amount is reached. return totalFillResults Total amounts filled and fees paid by maker and taker. | function marketMakerOrders(
Common.Order[] memory orderList,
uint256 totalMakerAmountToFill
)
public
returns (Common.FillResults memory totalFillResults)
{
for (uint256 i = 0; i < orderList.length; i++) {
Common.FillResults memory singleFillResults = fillOrderNoThrow(
orderList[i],
getPartialAmountFloor(
orderList[i].takerAmount, orderList[i].makerAmount,
sub(totalMakerAmountToFill, totalFillResults.makerFilledAmount)
),
true
);
addFillResults(totalFillResults, singleFillResults);
if (totalFillResults.makerFilledAmount >= totalMakerAmountToFill) {
break;
}
}
return totalFillResults;
}
| 6,454,721 |
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol";
import {ERC20} from "./vendored/OZERC20.sol";
// ============ External Imports ============
import {Version0} from "@celo-org/optics-sol/contracts/Version0.sol";
import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract BridgeToken is Version0, IBridgeToken, OwnableUpgradeable, ERC20 {
// ============ Immutables ============
// Immutables used in EIP 712 structured data hashing & signing
// https://eips.ethereum.org/EIPS/eip-712
bytes32 public immutable _PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
bytes32 private immutable _EIP712_STRUCTURED_DATA_VERSION =
keccak256(bytes("1"));
uint16 private immutable _EIP712_PREFIX_AND_VERSION = uint16(0x1901);
// ============ Public Storage ============
mapping(address => uint256) public nonces;
// ============ Upgrade Gap ============
uint256[49] private __GAP; // gap for upgrade safety
// ============ Initializer ============
function initialize() public override initializer {
__Ownable_init();
}
// ============ External Functions ============
/**
* @notice Destroys `_amnt` tokens from `_from`, reducing the
* total supply.
* @dev Emits a {Transfer} event with `to` set to the zero address.
* Requirements:
* - `_from` cannot be the zero address.
* - `_from` must have at least `_amnt` tokens.
* @param _from The address from which to destroy the tokens
* @param _amnt The amount of tokens to be destroyed
*/
function burn(address _from, uint256 _amnt) external override onlyOwner {
_burn(_from, _amnt);
}
/** @notice Creates `_amnt` tokens and assigns them to `_to`, increasing
* the total supply.
* @dev Emits a {Transfer} event with `from` set to the zero address.
* Requirements:
* - `to` cannot be the zero address.
* @param _to The destination address
* @param _amnt The amount of tokens to be minted
*/
function mint(address _to, uint256 _amnt) external override onlyOwner {
_mint(_to, _amnt);
}
/**
* @notice Set the details of a token
* @param _newName The new name
* @param _newSymbol The new symbol
* @param _newDecimals The new decimals
*/
function setDetails(
string calldata _newName,
string calldata _newSymbol,
uint8 _newDecimals
) external override onlyOwner {
// careful with naming convention change here
token.name = _newName;
token.symbol = _newSymbol;
token.decimals = _newDecimals;
}
/**
* @notice Sets approval from owner to spender to value
* as long as deadline has not passed
* by submitting a valid signature from owner
* Uses EIP 712 structured data hashing & signing
* https://eips.ethereum.org/EIPS/eip-712
* @param _owner The account setting approval & signing the message
* @param _spender The account receiving approval to spend owner's tokens
* @param _value The amount to set approval for
* @param _deadline The timestamp before which the signature must be submitted
* @param _v ECDSA signature v
* @param _r ECDSA signature r
* @param _s ECDSA signature s
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
require(block.timestamp <= _deadline, "ERC20Permit: expired deadline");
require(_owner != address(0), "ERC20Permit: owner zero address");
uint256 _nonce = nonces[_owner];
bytes32 _hashStruct = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
_owner,
_spender,
_value,
_nonce,
_deadline
)
);
bytes32 _digest = keccak256(
abi.encodePacked(
_EIP712_PREFIX_AND_VERSION,
domainSeparator(),
_hashStruct
)
);
address _signer = ecrecover(_digest, _v, _r, _s);
require(_signer == _owner, "ERC20Permit: invalid signature");
nonces[_owner] = _nonce + 1;
_approve(_owner, _spender, _value);
}
// ============ Public Functions ============
/**
* @dev silence the compiler being dumb
*/
function balanceOf(address _account)
public
view
override(IBridgeToken, ERC20)
returns (uint256)
{
return ERC20.balanceOf(_account);
}
/**
* @dev Returns the name of the token.
*/
function name() public view override returns (string memory) {
return token.name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view override returns (string memory) {
return token.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 override returns (uint8) {
return token.decimals;
}
/**
* @dev This is ALWAYS calculated at runtime
* because the token name may change
*/
function domainSeparator() public view returns (bytes32) {
uint256 _chainId;
assembly {
_chainId := chainid()
}
return
keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(token.name)),
_EIP712_STRUCTURED_DATA_VERSION,
_chainId,
address(this)
)
);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IBridgeToken {
function initialize() external;
function name() external returns (string memory);
function balanceOf(address _account) external view returns (uint256);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function burn(address _from, uint256 _amnt) external;
function mint(address _to, uint256 _amnt) external;
function setDetails(
string calldata _name,
string calldata _symbol,
uint8 _decimals
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
// This is modified from "@openzeppelin/contracts/token/ERC20/IERC20.sol"
// Modifications were made to make the tokenName, tokenSymbol, and
// tokenDecimals fields internal instead of private. Getters for them were
// removed to silence solidity inheritance issues
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/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 IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private balances;
mapping(address => mapping(address => uint256)) private allowances;
uint256 private supply;
struct Token {
string name;
string symbol;
uint8 decimals;
}
Token internal token;
/**
* @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(msg.sender, _recipient, _amount);
return true;
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `_spender` cannot be the zero address.
*/
function approve(address _spender, uint256 _amount)
public
virtual
override
returns (bool)
{
_approve(msg.sender, _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,
msg.sender,
allowances[_sender][msg.sender].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(
msg.sender,
_spender,
allowances[msg.sender][_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(
msg.sender,
_spender,
allowances[msg.sender][_spender].sub(
_subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return supply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address _account)
public
view
virtual
override
returns (uint256)
{
return balances[_account];
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address _owner, address _spender)
public
view
virtual
override
returns (uint256)
{
return allowances[_owner][_spender];
}
/**
* @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);
supply = supply.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"
);
supply = supply.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 {
token.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 OR Apache-2.0
pragma solidity >=0.6.11;
/**
* @title Version0
* @notice Version getter for contracts
**/
contract Version0 {
uint8 public constant VERSION = 0;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Home} from "./Home.sol";
import {Replica} from "./Replica.sol";
import {TypeCasts} from "../libs/TypeCasts.sol";
// ============ External Imports ============
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title XAppConnectionManager
* @author Celo Labs Inc.
* @notice Manages a registry of local Replica contracts
* for remote Home domains. Accepts Watcher signatures
* to un-enroll Replicas attached to fraudulent remote Homes
*/
contract XAppConnectionManager is Ownable {
// ============ Public Storage ============
// Home contract
Home public home;
// local Replica address => remote Home domain
mapping(address => uint32) public replicaToDomain;
// remote Home domain => local Replica address
mapping(uint32 => address) public domainToReplica;
// watcher address => replica remote domain => has/doesn't have permission
mapping(address => mapping(uint32 => bool)) private watcherPermissions;
// ============ Events ============
/**
* @notice Emitted when a new Replica is enrolled / added
* @param domain the remote domain of the Home contract for the Replica
* @param replica the address of the Replica
*/
event ReplicaEnrolled(uint32 indexed domain, address replica);
/**
* @notice Emitted when a new Replica is un-enrolled / removed
* @param domain the remote domain of the Home contract for the Replica
* @param replica the address of the Replica
*/
event ReplicaUnenrolled(uint32 indexed domain, address replica);
/**
* @notice Emitted when Watcher permissions are changed
* @param domain the remote domain of the Home contract for the Replica
* @param watcher the address of the Watcher
* @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed
*/
event WatcherPermissionSet(
uint32 indexed domain,
address watcher,
bool access
);
// ============ Modifiers ============
modifier onlyReplica() {
require(isReplica(msg.sender), "!replica");
_;
}
// ============ Constructor ============
// solhint-disable-next-line no-empty-blocks
constructor() Ownable() {}
// ============ External Functions ============
/**
* @notice Un-Enroll a replica contract
* in the case that fraud was detected on the Home
* @dev in the future, if fraud occurs on the Home contract,
* the Watcher will submit their signature directly to the Home
* and it can be relayed to all remote chains to un-enroll the Replicas
* @param _domain the remote domain of the Home contract for the Replica
* @param _updater the address of the Updater for the Home contract (also stored on Replica)
* @param _signature signature of watcher on (domain, replica address, updater address)
*/
function unenrollReplica(
uint32 _domain,
bytes32 _updater,
bytes memory _signature
) external {
// ensure that the replica is currently set
address _replica = domainToReplica[_domain];
require(_replica != address(0), "!replica exists");
// ensure that the signature is on the proper updater
require(
Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater),
"!current updater"
);
// get the watcher address from the signature
// and ensure that the watcher has permission to un-enroll this replica
address _watcher = _recoverWatcherFromSig(
_domain,
TypeCasts.addressToBytes32(_replica),
_updater,
_signature
);
require(watcherPermissions[_watcher][_domain], "!valid watcher");
// remove the replica from mappings
_unenrollReplica(_replica);
}
/**
* @notice Set the address of the local Home contract
* @param _home the address of the local Home contract
*/
function setHome(address _home) external onlyOwner {
home = Home(_home);
}
/**
* @notice Allow Owner to enroll Replica contract
* @param _replica the address of the Replica
* @param _domain the remote domain of the Home contract for the Replica
*/
function ownerEnrollReplica(address _replica, uint32 _domain)
external
onlyOwner
{
// un-enroll any existing replica
_unenrollReplica(_replica);
// add replica and domain to two-way mapping
replicaToDomain[_replica] = _domain;
domainToReplica[_domain] = _replica;
emit ReplicaEnrolled(_domain, _replica);
}
/**
* @notice Allow Owner to un-enroll Replica contract
* @param _replica the address of the Replica
*/
function ownerUnenrollReplica(address _replica) external onlyOwner {
_unenrollReplica(_replica);
}
/**
* @notice Allow Owner to set Watcher permissions for a Replica
* @param _watcher the address of the Watcher
* @param _domain the remote domain of the Home contract for the Replica
* @param _access TRUE to give the Watcher permissions, FALSE to remove permissions
*/
function setWatcherPermission(
address _watcher,
uint32 _domain,
bool _access
) external onlyOwner {
watcherPermissions[_watcher][_domain] = _access;
emit WatcherPermissionSet(_domain, _watcher, _access);
}
/**
* @notice Query local domain from Home
* @return local domain
*/
function localDomain() external view returns (uint32) {
return home.localDomain();
}
/**
* @notice Get access permissions for the watcher on the domain
* @param _watcher the address of the watcher
* @param _domain the domain to check for watcher permissions
* @return TRUE iff _watcher has permission to un-enroll replicas on _domain
*/
function watcherPermission(address _watcher, uint32 _domain)
external
view
returns (bool)
{
return watcherPermissions[_watcher][_domain];
}
// ============ Public Functions ============
/**
* @notice Check whether _replica is enrolled
* @param _replica the replica to check for enrollment
* @return TRUE iff _replica is enrolled
*/
function isReplica(address _replica) public view returns (bool) {
return replicaToDomain[_replica] != 0;
}
// ============ Internal Functions ============
/**
* @notice Remove the replica from the two-way mappings
* @param _replica replica to un-enroll
*/
function _unenrollReplica(address _replica) internal {
uint32 _currentDomain = replicaToDomain[_replica];
domainToReplica[_currentDomain] = address(0);
replicaToDomain[_replica] = 0;
emit ReplicaUnenrolled(_currentDomain, _replica);
}
/**
* @notice Get the Watcher address from the provided signature
* @return address of watcher that signed
*/
function _recoverWatcherFromSig(
uint32 _domain,
bytes32 _replica,
bytes32 _updater,
bytes memory _signature
) internal view returns (address) {
bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica))
.homeDomainHash();
bytes32 _digest = keccak256(
abi.encodePacked(_homeDomainHash, _domain, _updater)
);
_digest = ECDSA.toEthSignedMessageHash(_digest);
return ECDSA.recover(_digest, _signature);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Version0} from "./Version0.sol";
import {Common} from "./Common.sol";
import {QueueLib} from "../libs/Queue.sol";
import {MerkleLib} from "../libs/Merkle.sol";
import {Message} from "../libs/Message.sol";
import {MerkleTreeManager} from "./Merkle.sol";
import {QueueManager} from "./Queue.sol";
import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol";
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @title Home
* @author Celo Labs Inc.
* @notice Accepts messages to be dispatched to remote chains,
* constructs a Merkle tree of the messages,
* and accepts signatures from a bonded Updater
* which notarize the Merkle tree roots.
* Accepts submissions of fraudulent signatures
* by the Updater and slashes the Updater in this case.
*/
contract Home is
Version0,
QueueManager,
MerkleTreeManager,
Common,
OwnableUpgradeable
{
// ============ Libraries ============
using QueueLib for QueueLib.Queue;
using MerkleLib for MerkleLib.Tree;
// ============ Constants ============
// Maximum bytes per message = 2 KiB
// (somewhat arbitrarily set to begin)
uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10;
// ============ Public Storage Variables ============
// domain => next available nonce for the domain
mapping(uint32 => uint32) public nonces;
// contract responsible for Updater bonding, slashing and rotation
IUpdaterManager public updaterManager;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[48] private __GAP;
// ============ Events ============
/**
* @notice Emitted when a new message is dispatched via Optics
* @param leafIndex Index of message's leaf in merkle tree
* @param destinationAndNonce Destination and destination-specific
* nonce combined in single field ((destination << 32) & nonce)
* @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message
* @param committedRoot the latest notarized root submitted in the last signed Update
* @param message Raw bytes of message
*/
event Dispatch(
bytes32 indexed messageHash,
uint256 indexed leafIndex,
uint64 indexed destinationAndNonce,
bytes32 committedRoot,
bytes message
);
/**
* @notice Emitted when proof of an improper update is submitted,
* which sets the contract to FAILED state
* @param oldRoot Old root of the improper update
* @param newRoot New root of the improper update
* @param signature Signature on `oldRoot` and `newRoot
*/
event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature);
/**
* @notice Emitted when the Updater is slashed
* (should be paired with ImproperUpdater or DoubleUpdate event)
* @param updater The address of the updater
* @param reporter The address of the entity that reported the updater misbehavior
*/
event UpdaterSlashed(address indexed updater, address indexed reporter);
/**
* @notice Emitted when Updater is rotated by the UpdaterManager
* @param updater The address of the new updater
*/
event NewUpdater(address updater);
/**
* @notice Emitted when the UpdaterManager contract is changed
* @param updaterManager The address of the new updaterManager
*/
event NewUpdaterManager(address updaterManager);
// ============ Constructor ============
constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks
// ============ Initializer ============
function initialize(IUpdaterManager _updaterManager) public initializer {
// initialize owner & queue
__Ownable_init();
__QueueManager_initialize();
// set Updater Manager contract and initialize Updater
_setUpdaterManager(_updaterManager);
address _updater = updaterManager.updater();
__Common_initialize(_updater);
emit NewUpdater(_updater);
}
// ============ Modifiers ============
/**
* @notice Ensures that function is called by the UpdaterManager contract
*/
modifier onlyUpdaterManager() {
require(msg.sender == address(updaterManager), "!updaterManager");
_;
}
// ============ External: Updater & UpdaterManager Configuration ============
/**
* @notice Set a new Updater
* @param _updater the new Updater
*/
function setUpdater(address _updater) external onlyUpdaterManager {
_setUpdater(_updater);
}
/**
* @notice Set a new UpdaterManager contract
* @dev Home(s) will initially be initialized using a trusted UpdaterManager contract;
* we will progressively decentralize by swapping the trusted contract with a new implementation
* that implements Updater bonding & slashing, and rules for Updater selection & rotation
* @param _updaterManager the new UpdaterManager contract
*/
function setUpdaterManager(address _updaterManager) external onlyOwner {
_setUpdaterManager(IUpdaterManager(_updaterManager));
}
// ============ External Functions ============
/**
* @notice Dispatch the message it to the destination domain & recipient
* @dev Format the message, insert its hash into Merkle tree,
* enqueue the new Merkle root, and emit `Dispatch` event with message information.
* @param _destinationDomain Domain of destination chain
* @param _recipientAddress Address of recipient on destination chain as bytes32
* @param _messageBody Raw bytes content of message
*/
function dispatch(
uint32 _destinationDomain,
bytes32 _recipientAddress,
bytes memory _messageBody
) external notFailed {
require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long");
// get the next nonce for the destination domain, then increment it
uint32 _nonce = nonces[_destinationDomain];
nonces[_destinationDomain] = _nonce + 1;
// format the message into packed bytes
bytes memory _message = Message.formatMessage(
localDomain,
bytes32(uint256(uint160(msg.sender))),
_nonce,
_destinationDomain,
_recipientAddress,
_messageBody
);
// insert the hashed message into the Merkle tree
bytes32 _messageHash = keccak256(_message);
tree.insert(_messageHash);
// enqueue the new Merkle root after inserting the message
queue.enqueue(root());
// Emit Dispatch event with message information
// note: leafIndex is count() - 1 since new leaf has already been inserted
emit Dispatch(
_messageHash,
count() - 1,
_destinationAndNonce(_destinationDomain, _nonce),
committedRoot,
_message
);
}
/**
* @notice Submit a signature from the Updater "notarizing" a root,
* which updates the Home contract's `committedRoot`,
* and publishes the signature which will be relayed to Replica contracts
* @dev emits Update event
* @dev If _newRoot is not contained in the queue,
* the Update is a fraudulent Improper Update, so
* the Updater is slashed & Home is set to FAILED state
* @param _committedRoot Current updated merkle root which the update is building off of
* @param _newRoot New merkle root to update the contract state to
* @param _signature Updater signature on `_committedRoot` and `_newRoot`
*/
function update(
bytes32 _committedRoot,
bytes32 _newRoot,
bytes memory _signature
) external notFailed {
// check that the update is not fraudulent;
// if fraud is detected, Updater is slashed & Home is set to FAILED state
if (improperUpdate(_committedRoot, _newRoot, _signature)) return;
// clear all of the intermediate roots contained in this update from the queue
while (true) {
bytes32 _next = queue.dequeue();
if (_next == _newRoot) break;
}
// update the Home state with the latest signed root & emit event
committedRoot = _newRoot;
emit Update(localDomain, _committedRoot, _newRoot, _signature);
}
/**
* @notice Suggest an update for the Updater to sign and submit.
* @dev If queue is empty, null bytes returned for both
* (No update is necessary because no messages have been dispatched since the last update)
* @return _committedRoot Latest root signed by the Updater
* @return _new Latest enqueued Merkle root
*/
function suggestUpdate()
external
view
returns (bytes32 _committedRoot, bytes32 _new)
{
if (queue.length() != 0) {
_committedRoot = committedRoot;
_new = queue.lastItem();
}
}
// ============ Public Functions ============
/**
* @notice Hash of Home domain concatenated with "OPTICS"
*/
function homeDomainHash() public view override returns (bytes32) {
return _homeDomainHash(localDomain);
}
/**
* @notice Check if an Update is an Improper Update;
* if so, slash the Updater and set the contract to FAILED state.
*
* An Improper Update is an update building off of the Home's `committedRoot`
* for which the `_newRoot` does not currently exist in the Home's queue.
* This would mean that message(s) that were not truly
* dispatched on Home were falsely included in the signed root.
*
* An Improper Update will only be accepted as valid by the Replica
* If an Improper Update is attempted on Home,
* the Updater will be slashed immediately.
* If an Improper Update is submitted to the Replica,
* it should be relayed to the Home contract using this function
* in order to slash the Updater with an Improper Update.
*
* An Improper Update submitted to the Replica is only valid
* while the `_oldRoot` is still equal to the `committedRoot` on Home;
* if the `committedRoot` on Home has already been updated with a valid Update,
* then the Updater should be slashed with a Double Update.
* @dev Reverts (and doesn't slash updater) if signature is invalid or
* update not current
* @param _oldRoot Old merkle tree root (should equal home's committedRoot)
* @param _newRoot New merkle tree root
* @param _signature Updater signature on `_oldRoot` and `_newRoot`
* @return TRUE if update was an Improper Update (implying Updater was slashed)
*/
function improperUpdate(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) public notFailed returns (bool) {
require(
_isUpdaterSignature(_oldRoot, _newRoot, _signature),
"!updater sig"
);
require(_oldRoot == committedRoot, "not a current update");
// if the _newRoot is not currently contained in the queue,
// slash the Updater and set the contract to FAILED state
if (!queue.contains(_newRoot)) {
_fail();
emit ImproperUpdate(_oldRoot, _newRoot, _signature);
return true;
}
// if the _newRoot is contained in the queue,
// this is not an improper update
return false;
}
// ============ Internal Functions ============
/**
* @notice Set the UpdaterManager
* @param _updaterManager Address of the UpdaterManager
*/
function _setUpdaterManager(IUpdaterManager _updaterManager) internal {
require(
Address.isContract(address(_updaterManager)),
"!contract updaterManager"
);
updaterManager = IUpdaterManager(_updaterManager);
emit NewUpdaterManager(address(_updaterManager));
}
/**
* @notice Set the Updater
* @param _updater Address of the Updater
*/
function _setUpdater(address _updater) internal {
updater = _updater;
emit NewUpdater(_updater);
}
/**
* @notice Slash the Updater and set contract state to FAILED
* @dev Called when fraud is proven (Improper Update or Double Update)
*/
function _fail() internal override {
// set contract to FAILED
_setFailed();
// slash Updater
updaterManager.slashUpdater(msg.sender);
emit UpdaterSlashed(updater, msg.sender);
}
/**
* @notice Internal utility function that combines
* `_destination` and `_nonce`.
* @dev Both destination and nonce should be less than 2^32 - 1
* @param _destination Domain of destination chain
* @param _nonce Current nonce for given destination chain
* @return Returns (`_destination` << 32) & `_nonce`
*/
function _destinationAndNonce(uint32 _destination, uint32 _nonce)
internal
pure
returns (uint64)
{
return (uint64(_destination) << 32) | _nonce;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Version0} from "./Version0.sol";
import {Common} from "./Common.sol";
import {MerkleLib} from "../libs/Merkle.sol";
import {Message} from "../libs/Message.sol";
import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol";
// ============ External Imports ============
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
/**
* @title Replica
* @author Celo Labs Inc.
* @notice Track root updates on Home,
* prove and dispatch messages to end recipients.
*/
contract Replica is Version0, Common {
// ============ Libraries ============
using MerkleLib for MerkleLib.Tree;
using TypedMemView for bytes;
using TypedMemView for bytes29;
using Message for bytes29;
// ============ Enums ============
// Status of Message:
// 0 - None - message has not been proven or processed
// 1 - Proven - message inclusion proof has been validated
// 2 - Processed - message has been dispatched to recipient
enum MessageStatus {
None,
Proven,
Processed
}
// ============ Immutables ============
// Minimum gas for message processing
uint256 public immutable PROCESS_GAS;
// Reserved gas (to ensure tx completes in case message processing runs out)
uint256 public immutable RESERVE_GAS;
// ============ Public Storage ============
// Domain of home chain
uint32 public remoteDomain;
// Number of seconds to wait before root becomes confirmable
uint256 public optimisticSeconds;
// re-entrancy guard
uint8 private entered;
// Mapping of roots to allowable confirmation times
mapping(bytes32 => uint256) public confirmAt;
// Mapping of message leaves to MessageStatus
mapping(bytes32 => MessageStatus) public messages;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[44] private __GAP;
// ============ Events ============
/**
* @notice Emitted when message is processed
* @param messageHash Hash of message that failed to process
* @param success TRUE if the call was executed successfully, FALSE if the call reverted
* @param returnData the return data from the external call
*/
event Process(
bytes32 indexed messageHash,
bool indexed success,
bytes indexed returnData
);
// ============ Constructor ============
// solhint-disable-next-line no-empty-blocks
constructor(
uint32 _localDomain,
uint256 _processGas,
uint256 _reserveGas
) Common(_localDomain) {
require(_processGas >= 850_000, "!process gas");
require(_reserveGas >= 15_000, "!reserve gas");
PROCESS_GAS = _processGas;
RESERVE_GAS = _reserveGas;
}
// ============ Initializer ============
function initialize(
uint32 _remoteDomain,
address _updater,
bytes32 _committedRoot,
uint256 _optimisticSeconds
) public initializer {
__Common_initialize(_updater);
entered = 1;
remoteDomain = _remoteDomain;
committedRoot = _committedRoot;
confirmAt[_committedRoot] = 1;
optimisticSeconds = _optimisticSeconds;
}
// ============ External Functions ============
/**
* @notice Called by external agent. Submits the signed update's new root,
* marks root's allowable confirmation time, and emits an `Update` event.
* @dev Reverts if update doesn't build off latest committedRoot
* or if signature is invalid.
* @param _oldRoot Old merkle root
* @param _newRoot New merkle root
* @param _signature Updater's signature on `_oldRoot` and `_newRoot`
*/
function update(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) external notFailed {
// ensure that update is building off the last submitted root
require(_oldRoot == committedRoot, "not current update");
// validate updater signature
require(
_isUpdaterSignature(_oldRoot, _newRoot, _signature),
"!updater sig"
);
// Hook for future use
_beforeUpdate();
// set the new root's confirmation timer
confirmAt[_newRoot] = block.timestamp + optimisticSeconds;
// update committedRoot
committedRoot = _newRoot;
emit Update(remoteDomain, _oldRoot, _newRoot, _signature);
}
/**
* @notice First attempts to prove the validity of provided formatted
* `message`. If the message is successfully proven, then tries to process
* message.
* @dev Reverts if `prove` call returns false
* @param _message Formatted message (refer to Common.sol Message library)
* @param _proof Merkle proof of inclusion for message's leaf
* @param _index Index of leaf in home's merkle tree
*/
function proveAndProcess(
bytes memory _message,
bytes32[32] calldata _proof,
uint256 _index
) external {
require(prove(keccak256(_message), _proof, _index), "!prove");
process(_message);
}
/**
* @notice Given formatted message, attempts to dispatch
* message payload to end recipient.
* @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol)
* Reverts if formatted message's destination domain is not the Replica's domain,
* if message has not been proven,
* or if not enough gas is provided for the dispatch transaction.
* @param _message Formatted message
* @return _success TRUE iff dispatch transaction succeeded
*/
function process(bytes memory _message) public returns (bool _success) {
bytes29 _m = _message.ref(0);
// ensure message was meant for this domain
require(_m.destination() == localDomain, "!destination");
// ensure message has been proven
bytes32 _messageHash = _m.keccak();
require(messages[_messageHash] == MessageStatus.Proven, "!proven");
// check re-entrancy guard
require(entered == 1, "!reentrant");
entered = 0;
// update message status as processed
messages[_messageHash] = MessageStatus.Processed;
// A call running out of gas TYPICALLY errors the whole tx. We want to
// a) ensure the call has a sufficient amount of gas to make a
// meaningful state change.
// b) ensure that if the subcall runs out of gas, that the tx as a whole
// does not revert (i.e. we still mark the message processed)
// To do this, we require that we have enough gas to process
// and still return. We then delegate only the minimum processing gas.
require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas");
// get the message recipient
address _recipient = _m.recipientAddress();
// set up for assembly call
uint256 _toCopy;
uint256 _maxCopy = 256;
uint256 _gas = PROCESS_GAS;
// allocate memory for returndata
bytes memory _returnData = new bytes(_maxCopy);
bytes memory _calldata = abi.encodeWithSignature(
"handle(uint32,bytes32,bytes)",
_m.origin(),
_m.sender(),
_m.body().clone()
);
// dispatch message to recipient
// by assembly calling "handle" function
// we call via assembly to avoid memcopying a very large returndata
// returned by a malicious contract
assembly {
_success := call(
_gas, // gas
_recipient, // recipient
0, // ether value
add(_calldata, 0x20), // inloc
mload(_calldata), // inlen
0, // outloc
0 // outlen
)
// limit our copy to 256 bytes
_toCopy := returndatasize()
if gt(_toCopy, _maxCopy) {
_toCopy := _maxCopy
}
// Store the length of the copied bytes
mstore(_returnData, _toCopy)
// copy the bytes from returndata[0:_toCopy]
returndatacopy(add(_returnData, 0x20), 0, _toCopy)
}
// emit process results
emit Process(_messageHash, _success, _returnData);
// reset re-entrancy guard
entered = 1;
}
// ============ Public Functions ============
/**
* @notice Check that the root has been submitted
* and that the optimistic timeout period has expired,
* meaning the root can be processed
* @param _root the Merkle root, submitted in an update, to check
* @return TRUE iff root has been submitted & timeout has expired
*/
function acceptableRoot(bytes32 _root) public view returns (bool) {
uint256 _time = confirmAt[_root];
if (_time == 0) {
return false;
}
return block.timestamp >= _time;
}
/**
* @notice Attempts to prove the validity of message given its leaf, the
* merkle proof of inclusion for the leaf, and the index of the leaf.
* @dev Reverts if message's MessageStatus != None (i.e. if message was
* already proven or processed)
* @dev For convenience, we allow proving against any previous root.
* This means that witnesses never need to be updated for the new root
* @param _leaf Leaf of message to prove
* @param _proof Merkle proof of inclusion for leaf
* @param _index Index of leaf in home's merkle tree
* @return Returns true if proof was valid and `prove` call succeeded
**/
function prove(
bytes32 _leaf,
bytes32[32] calldata _proof,
uint256 _index
) public returns (bool) {
// ensure that message has not been proven or processed
require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None");
// calculate the expected root based on the proof
bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index);
// if the root is valid, change status to Proven
if (acceptableRoot(_calculatedRoot)) {
messages[_leaf] = MessageStatus.Proven;
return true;
}
return false;
}
/**
* @notice Hash of Home domain concatenated with "OPTICS"
*/
function homeDomainHash() public view override returns (bytes32) {
return _homeDomainHash(remoteDomain);
}
// ============ Internal Functions ============
/**
* @notice Moves the contract into failed state
* @dev Called when a Double Update is submitted
*/
function _fail() internal override {
_setFailed();
}
/// @notice Hook for potential future use
// solhint-disable-next-line no-empty-blocks
function _beforeUpdate() internal {}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
import "@summa-tx/memview-sol/contracts/TypedMemView.sol";
library TypeCasts {
using TypedMemView for bytes;
using TypedMemView for bytes29;
function coerceBytes32(string memory _s)
internal
pure
returns (bytes32 _b)
{
_b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length));
}
// treat it as a null-terminated string of max 32 bytes
function coerceString(bytes32 _buf)
internal
pure
returns (string memory _newStr)
{
uint8 _slen = 0;
while (_slen < 32 && _buf[_slen] != 0) {
_slen++;
}
// solhint-disable-next-line no-inline-assembly
assembly {
_newStr := mload(0x40)
mstore(0x40, add(_newStr, 0x40)) // may end up with extra
mstore(_newStr, _slen)
mstore(add(_newStr, 0x20), _buf)
}
}
// alignment preserving cast
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
// alignment preserving cast
function bytes32ToAddress(bytes32 _buf) internal pure returns (address) {
return address(uint160(uint256(_buf)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Message} from "../libs/Message.sol";
// ============ External Imports ============
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title Common
* @author Celo Labs Inc.
* @notice Shared utilities between Home and Replica.
*/
abstract contract Common is Initializable {
// ============ Enums ============
// States:
// 0 - UnInitialized - before initialize function is called
// note: the contract is initialized at deploy time, so it should never be in this state
// 1 - Active - as long as the contract has not become fraudulent
// 2 - Failed - after a valid fraud proof has been submitted;
// contract will no longer accept updates or new messages
enum States {
UnInitialized,
Active,
Failed
}
// ============ Immutable Variables ============
// Domain of chain on which the contract is deployed
uint32 public immutable localDomain;
// ============ Public Variables ============
// Address of bonded Updater
address public updater;
// Current state of contract
States public state;
// The latest root that has been signed by the Updater
bytes32 public committedRoot;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[47] private __GAP;
// ============ Events ============
/**
* @notice Emitted when update is made on Home
* or unconfirmed update root is submitted on Replica
* @param homeDomain Domain of home contract
* @param oldRoot Old merkle root
* @param newRoot New merkle root
* @param signature Updater's signature on `oldRoot` and `newRoot`
*/
event Update(
uint32 indexed homeDomain,
bytes32 indexed oldRoot,
bytes32 indexed newRoot,
bytes signature
);
/**
* @notice Emitted when proof of a double update is submitted,
* which sets the contract to FAILED state
* @param oldRoot Old root shared between two conflicting updates
* @param newRoot Array containing two conflicting new roots
* @param signature Signature on `oldRoot` and `newRoot`[0]
* @param signature2 Signature on `oldRoot` and `newRoot`[1]
*/
event DoubleUpdate(
bytes32 oldRoot,
bytes32[2] newRoot,
bytes signature,
bytes signature2
);
// ============ Modifiers ============
/**
* @notice Ensures that contract state != FAILED when the function is called
*/
modifier notFailed() {
require(state != States.Failed, "failed state");
_;
}
// ============ Constructor ============
constructor(uint32 _localDomain) {
localDomain = _localDomain;
}
// ============ Initializer ============
function __Common_initialize(address _updater) internal initializer {
updater = _updater;
state = States.Active;
}
// ============ External Functions ============
/**
* @notice Called by external agent. Checks that signatures on two sets of
* roots are valid and that the new roots conflict with each other. If both
* cases hold true, the contract is failed and a `DoubleUpdate` event is
* emitted.
* @dev When `fail()` is called on Home, updater is slashed.
* @param _oldRoot Old root shared between two conflicting updates
* @param _newRoot Array containing two conflicting new roots
* @param _signature Signature on `_oldRoot` and `_newRoot`[0]
* @param _signature2 Signature on `_oldRoot` and `_newRoot`[1]
*/
function doubleUpdate(
bytes32 _oldRoot,
bytes32[2] calldata _newRoot,
bytes calldata _signature,
bytes calldata _signature2
) external notFailed {
if (
Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) &&
Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) &&
_newRoot[0] != _newRoot[1]
) {
_fail();
emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2);
}
}
// ============ Public Functions ============
/**
* @notice Hash of Home domain concatenated with "OPTICS"
*/
function homeDomainHash() public view virtual returns (bytes32);
// ============ Internal Functions ============
/**
* @notice Hash of Home domain concatenated with "OPTICS"
* @param _homeDomain the Home domain to hash
*/
function _homeDomainHash(uint32 _homeDomain)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_homeDomain, "OPTICS"));
}
/**
* @notice Set contract state to FAILED
* @dev Called when a valid fraud proof is submitted
*/
function _setFailed() internal {
state = States.Failed;
}
/**
* @notice Moves the contract into failed state
* @dev Called when fraud is proven
* (Double Update is submitted on Home or Replica,
* or Improper Update is submitted on Home)
*/
function _fail() internal virtual;
/**
* @notice Checks that signature was signed by Updater
* @param _oldRoot Old merkle root
* @param _newRoot New merkle root
* @param _signature Signature on `_oldRoot` and `_newRoot`
* @return TRUE iff signature is valid signed by updater
**/
function _isUpdaterSignature(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) internal view returns (bool) {
bytes32 _digest = keccak256(
abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot)
);
_digest = ECDSA.toEthSignedMessageHash(_digest);
return (ECDSA.recover(_digest, _signature) == updater);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
/**
* @title QueueLib
* @author Celo Labs Inc.
* @notice Library containing queue struct and operations for queue used by
* Home and Replica.
**/
library QueueLib {
/**
* @notice Queue struct
* @dev Internally keeps track of the `first` and `last` elements through
* indices and a mapping of indices to enqueued elements.
**/
struct Queue {
uint128 first;
uint128 last;
mapping(uint256 => bytes32) queue;
}
/**
* @notice Initializes the queue
* @dev Empty state denoted by _q.first > q._last. Queue initialized
* with _q.first = 1 and _q.last = 0.
**/
function initialize(Queue storage _q) internal {
if (_q.first == 0) {
_q.first = 1;
}
}
/**
* @notice Enqueues a single new element
* @param _item New element to be enqueued
* @return _last Index of newly enqueued element
**/
function enqueue(Queue storage _q, bytes32 _item)
internal
returns (uint128 _last)
{
_last = _q.last + 1;
_q.last = _last;
if (_item != bytes32(0)) {
// saves gas if we're queueing 0
_q.queue[_last] = _item;
}
}
/**
* @notice Dequeues element at front of queue
* @dev Removes dequeued element from storage
* @return _item Dequeued element
**/
function dequeue(Queue storage _q) internal returns (bytes32 _item) {
uint128 _last = _q.last;
uint128 _first = _q.first;
require(_length(_last, _first) != 0, "Empty");
_item = _q.queue[_first];
if (_item != bytes32(0)) {
// saves gas if we're dequeuing 0
delete _q.queue[_first];
}
_q.first = _first + 1;
}
/**
* @notice Batch enqueues several elements
* @param _items Array of elements to be enqueued
* @return _last Index of last enqueued element
**/
function enqueue(Queue storage _q, bytes32[] memory _items)
internal
returns (uint128 _last)
{
_last = _q.last;
for (uint256 i = 0; i < _items.length; i += 1) {
_last += 1;
bytes32 _item = _items[i];
if (_item != bytes32(0)) {
_q.queue[_last] = _item;
}
}
_q.last = _last;
}
/**
* @notice Batch dequeues `_number` elements
* @dev Reverts if `_number` > queue length
* @param _number Number of elements to dequeue
* @return Array of dequeued elements
**/
function dequeue(Queue storage _q, uint256 _number)
internal
returns (bytes32[] memory)
{
uint128 _last = _q.last;
uint128 _first = _q.first;
// Cannot underflow unless state is corrupted
require(_length(_last, _first) >= _number, "Insufficient");
bytes32[] memory _items = new bytes32[](_number);
for (uint256 i = 0; i < _number; i++) {
_items[i] = _q.queue[_first];
delete _q.queue[_first];
_first++;
}
_q.first = _first;
return _items;
}
/**
* @notice Returns true if `_item` is in the queue and false if otherwise
* @dev Linearly scans from _q.first to _q.last looking for `_item`
* @param _item Item being searched for in queue
* @return True if `_item` currently exists in queue, false if otherwise
**/
function contains(Queue storage _q, bytes32 _item)
internal
view
returns (bool)
{
for (uint256 i = _q.first; i <= _q.last; i++) {
if (_q.queue[i] == _item) {
return true;
}
}
return false;
}
/// @notice Returns last item in queue
/// @dev Returns bytes32(0) if queue empty
function lastItem(Queue storage _q) internal view returns (bytes32) {
return _q.queue[_q.last];
}
/// @notice Returns element at front of queue without removing element
/// @dev Reverts if queue is empty
function peek(Queue storage _q) internal view returns (bytes32 _item) {
require(!isEmpty(_q), "Empty");
_item = _q.queue[_q.first];
}
/// @notice Returns true if queue is empty and false if otherwise
function isEmpty(Queue storage _q) internal view returns (bool) {
return _q.last < _q.first;
}
/// @notice Returns number of elements in queue
function length(Queue storage _q) internal view returns (uint256) {
uint128 _last = _q.last;
uint128 _first = _q.first;
// Cannot underflow unless state is corrupted
return _length(_last, _first);
}
/// @notice Returns number of elements between `_last` and `_first` (used internally)
function _length(uint128 _last, uint128 _first)
internal
pure
returns (uint256)
{
return uint256(_last + 1 - _first);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// work based on eth2 deposit contract, which is used under CC0-1.0
/**
* @title MerkleLib
* @author Celo Labs Inc.
* @notice An incremental merkle tree modeled on the eth2 deposit contract.
**/
library MerkleLib {
uint256 internal constant TREE_DEPTH = 32;
uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1;
/**
* @notice Struct representing incremental merkle tree. Contains current
* branch and the number of inserted leaves in the tree.
**/
struct Tree {
bytes32[TREE_DEPTH] branch;
uint256 count;
}
/**
* @notice Inserts `_node` into merkle tree
* @dev Reverts if tree is full
* @param _node Element to insert into tree
**/
function insert(Tree storage _tree, bytes32 _node) internal {
require(_tree.count < MAX_LEAVES, "merkle tree full");
_tree.count += 1;
uint256 size = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
if ((size & 1) == 1) {
_tree.branch[i] = _node;
return;
}
_node = keccak256(abi.encodePacked(_tree.branch[i], _node));
size /= 2;
}
// As the loop should always end prematurely with the `return` statement,
// this code should be unreachable. We assert `false` just to be safe.
assert(false);
}
/**
* @notice Calculates and returns`_tree`'s current root given array of zero
* hashes
* @param _zeroes Array of zero hashes
* @return _current Calculated root of `_tree`
**/
function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes)
internal
view
returns (bytes32 _current)
{
uint256 _index = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
bytes32 _next = _tree.branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _zeroes[i]));
}
}
}
/// @notice Calculates and returns`_tree`'s current root
function root(Tree storage _tree) internal view returns (bytes32) {
return rootWithCtx(_tree, zeroHashes());
}
/// @notice Returns array of TREE_DEPTH zero hashes
/// @return _zeroes Array of TREE_DEPTH zero hashes
function zeroHashes()
internal
pure
returns (bytes32[TREE_DEPTH] memory _zeroes)
{
_zeroes[0] = Z_0;
_zeroes[1] = Z_1;
_zeroes[2] = Z_2;
_zeroes[3] = Z_3;
_zeroes[4] = Z_4;
_zeroes[5] = Z_5;
_zeroes[6] = Z_6;
_zeroes[7] = Z_7;
_zeroes[8] = Z_8;
_zeroes[9] = Z_9;
_zeroes[10] = Z_10;
_zeroes[11] = Z_11;
_zeroes[12] = Z_12;
_zeroes[13] = Z_13;
_zeroes[14] = Z_14;
_zeroes[15] = Z_15;
_zeroes[16] = Z_16;
_zeroes[17] = Z_17;
_zeroes[18] = Z_18;
_zeroes[19] = Z_19;
_zeroes[20] = Z_20;
_zeroes[21] = Z_21;
_zeroes[22] = Z_22;
_zeroes[23] = Z_23;
_zeroes[24] = Z_24;
_zeroes[25] = Z_25;
_zeroes[26] = Z_26;
_zeroes[27] = Z_27;
_zeroes[28] = Z_28;
_zeroes[29] = Z_29;
_zeroes[30] = Z_30;
_zeroes[31] = Z_31;
}
/**
* @notice Calculates and returns the merkle root for the given leaf
* `_item`, a merkle branch, and the index of `_item` in the tree.
* @param _item Merkle leaf
* @param _branch Merkle proof
* @param _index Index of `_item` in tree
* @return _current Calculated merkle root
**/
function branchRoot(
bytes32 _item,
bytes32[TREE_DEPTH] memory _branch,
uint256 _index
) internal pure returns (bytes32 _current) {
_current = _item;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
bytes32 _next = _branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _next));
}
}
}
// keccak256 zero hashes
bytes32 internal constant Z_0 =
hex"0000000000000000000000000000000000000000000000000000000000000000";
bytes32 internal constant Z_1 =
hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5";
bytes32 internal constant Z_2 =
hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30";
bytes32 internal constant Z_3 =
hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85";
bytes32 internal constant Z_4 =
hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344";
bytes32 internal constant Z_5 =
hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d";
bytes32 internal constant Z_6 =
hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968";
bytes32 internal constant Z_7 =
hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83";
bytes32 internal constant Z_8 =
hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af";
bytes32 internal constant Z_9 =
hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0";
bytes32 internal constant Z_10 =
hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5";
bytes32 internal constant Z_11 =
hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892";
bytes32 internal constant Z_12 =
hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c";
bytes32 internal constant Z_13 =
hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb";
bytes32 internal constant Z_14 =
hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc";
bytes32 internal constant Z_15 =
hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2";
bytes32 internal constant Z_16 =
hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f";
bytes32 internal constant Z_17 =
hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a";
bytes32 internal constant Z_18 =
hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0";
bytes32 internal constant Z_19 =
hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0";
bytes32 internal constant Z_20 =
hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2";
bytes32 internal constant Z_21 =
hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9";
bytes32 internal constant Z_22 =
hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377";
bytes32 internal constant Z_23 =
hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652";
bytes32 internal constant Z_24 =
hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef";
bytes32 internal constant Z_25 =
hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d";
bytes32 internal constant Z_26 =
hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0";
bytes32 internal constant Z_27 =
hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e";
bytes32 internal constant Z_28 =
hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e";
bytes32 internal constant Z_29 =
hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322";
bytes32 internal constant Z_30 =
hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735";
bytes32 internal constant Z_31 =
hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9";
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
import "@summa-tx/memview-sol/contracts/TypedMemView.sol";
import {
TypeCasts
} from "./TypeCasts.sol";
/**
* @title Message Library
* @author Celo Labs Inc.
* @notice Library for formatted messages used by Home and Replica.
**/
library Message {
using TypedMemView for bytes;
using TypedMemView for bytes29;
// Number of bytes in formatted message before `body` field
uint256 internal constant PREFIX_LENGTH = 76;
/**
* @notice Returns formatted (packed) message with provided fields
* @param _originDomain Domain of home chain
* @param _sender Address of sender as bytes32
* @param _nonce Destination-specific nonce
* @param _destinationDomain Domain of destination chain
* @param _recipient Address of recipient on destination chain as bytes32
* @param _messageBody Raw bytes of message body
* @return Formatted message
**/
function formatMessage(
uint32 _originDomain,
bytes32 _sender,
uint32 _nonce,
uint32 _destinationDomain,
bytes32 _recipient,
bytes memory _messageBody
) internal pure returns (bytes memory) {
return
abi.encodePacked(
_originDomain,
_sender,
_nonce,
_destinationDomain,
_recipient,
_messageBody
);
}
/**
* @notice Returns leaf of formatted message with provided fields.
* @param _origin Domain of home chain
* @param _sender Address of sender as bytes32
* @param _nonce Destination-specific nonce number
* @param _destination Domain of destination chain
* @param _recipient Address of recipient on destination chain as bytes32
* @param _body Raw bytes of message body
* @return Leaf (hash) of formatted message
**/
function messageHash(
uint32 _origin,
bytes32 _sender,
uint32 _nonce,
uint32 _destination,
bytes32 _recipient,
bytes memory _body
) internal pure returns (bytes32) {
return
keccak256(
formatMessage(
_origin,
_sender,
_nonce,
_destination,
_recipient,
_body
)
);
}
/// @notice Returns message's origin field
function origin(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(0, 4));
}
/// @notice Returns message's sender field
function sender(bytes29 _message) internal pure returns (bytes32) {
return _message.index(4, 32);
}
/// @notice Returns message's nonce field
function nonce(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(36, 4));
}
/// @notice Returns message's destination field
function destination(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(40, 4));
}
/// @notice Returns message's recipient field as bytes32
function recipient(bytes29 _message) internal pure returns (bytes32) {
return _message.index(44, 32);
}
/// @notice Returns message's recipient field as an address
function recipientAddress(bytes29 _message)
internal
pure
returns (address)
{
return TypeCasts.bytes32ToAddress(recipient(_message));
}
/// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type)
function body(bytes29 _message) internal pure returns (bytes29) {
return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0);
}
function leaf(bytes29 _message) internal view returns (bytes32) {
return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message)));
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {MerkleLib} from "../libs/Merkle.sol";
/**
* @title MerkleTreeManager
* @author Celo Labs Inc.
* @notice Contains a Merkle tree instance and
* exposes view functions for the tree.
*/
contract MerkleTreeManager {
// ============ Libraries ============
using MerkleLib for MerkleLib.Tree;
MerkleLib.Tree public tree;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[49] private __GAP;
// ============ Public Functions ============
/**
* @notice Calculates and returns tree's current root
*/
function root() public view returns (bytes32) {
return tree.root();
}
/**
* @notice Returns the number of inserted leaves in the tree (current index)
*/
function count() public view returns (uint256) {
return tree.count;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {QueueLib} from "../libs/Queue.sol";
// ============ External Imports ============
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title QueueManager
* @author Celo Labs Inc.
* @notice Contains a queue instance and
* exposes view functions for the queue.
**/
contract QueueManager is Initializable {
// ============ Libraries ============
using QueueLib for QueueLib.Queue;
QueueLib.Queue internal queue;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[49] private __GAP;
// ============ Initializer ============
function __QueueManager_initialize() internal initializer {
queue.initialize();
}
// ============ Public Functions ============
/**
* @notice Returns number of elements in queue
*/
function queueLength() external view returns (uint256) {
return queue.length();
}
/**
* @notice Returns TRUE iff `_item` is in the queue
*/
function queueContains(bytes32 _item) external view returns (bool) {
return queue.contains(_item);
}
/**
* @notice Returns last item enqueued to the queue
*/
function queueEnd() external view returns (bytes32) {
return queue.lastItem();
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IUpdaterManager {
function slashUpdater(address payable _reporter) external;
function updater() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.5.10;
import {SafeMath} from "./SafeMath.sol";
library TypedMemView {
using SafeMath for uint256;
// Why does this exist?
// the solidity `bytes memory` type has a few weaknesses.
// 1. You can't index ranges effectively
// 2. You can't slice without copying
// 3. The underlying data may represent any type
// 4. Solidity never deallocates memory, and memory costs grow
// superlinearly
// By using a memory view instead of a `bytes memory` we get the following
// advantages:
// 1. Slices are done on the stack, by manipulating the pointer
// 2. We can index arbitrary ranges and quickly convert them to stack types
// 3. We can insert type info into the pointer, and typecheck at runtime
// This makes `TypedMemView` a useful tool for efficient zero-copy
// algorithms.
// Why bytes29?
// We want to avoid confusion between views, digests, and other common
// types so we chose a large and uncommonly used odd number of bytes
//
// Note that while bytes are left-aligned in a word, integers and addresses
// are right-aligned. This means when working in assembly we have to
// account for the 3 unused bytes on the righthand side
//
// First 5 bytes are a type flag.
// - ff_ffff_fffe is reserved for unknown type.
// - ff_ffff_ffff is reserved for invalid types/errors.
// next 12 are memory address
// next 12 are len
// bottom 3 bytes are empty
// Assumptions:
// - non-modification of memory.
// - No Solidity updates
// - - wrt free mem point
// - - wrt bytes representation in memory
// - - wrt memory addressing in general
// Usage:
// - create type constants
// - use `assertType` for runtime type assertions
// - - unfortunately we can't do this at compile time yet :(
// - recommended: implement modifiers that perform type checking
// - - e.g.
// - - `uint40 constant MY_TYPE = 3;`
// - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }`
// - instantiate a typed view from a bytearray using `ref`
// - use `index` to inspect the contents of the view
// - use `slice` to create smaller views into the same memory
// - - `slice` can increase the offset
// - - `slice can decrease the length`
// - - must specify the output type of `slice`
// - - `slice` will return a null view if you try to overrun
// - - make sure to explicitly check for this with `notNull` or `assertType`
// - use `equal` for typed comparisons.
// The null view
bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff;
uint8 constant TWELVE_BYTES = 96;
/**
* @notice Returns the encoded hex character that represents the lower 4 bits of the argument.
* @param _b The byte
* @return char - The encoded hex character
*/
function nibbleHex(uint8 _b) internal pure returns (uint8 char) {
// This can probably be done more efficiently, but it's only in error
// paths, so we don't really care :)
uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4
if (_nibble == 0xf0) {return 0x30;} // 0
if (_nibble == 0xf1) {return 0x31;} // 1
if (_nibble == 0xf2) {return 0x32;} // 2
if (_nibble == 0xf3) {return 0x33;} // 3
if (_nibble == 0xf4) {return 0x34;} // 4
if (_nibble == 0xf5) {return 0x35;} // 5
if (_nibble == 0xf6) {return 0x36;} // 6
if (_nibble == 0xf7) {return 0x37;} // 7
if (_nibble == 0xf8) {return 0x38;} // 8
if (_nibble == 0xf9) {return 0x39;} // 9
if (_nibble == 0xfa) {return 0x61;} // a
if (_nibble == 0xfb) {return 0x62;} // b
if (_nibble == 0xfc) {return 0x63;} // c
if (_nibble == 0xfd) {return 0x64;} // d
if (_nibble == 0xfe) {return 0x65;} // e
if (_nibble == 0xff) {return 0x66;} // f
}
/**
* @notice Returns a uint16 containing the hex-encoded byte.
* @param _b The byte
* @return encoded - The hex-encoded byte
*/
function byteHex(uint8 _b) internal pure returns (uint16 encoded) {
encoded |= nibbleHex(_b >> 4); // top 4 bits
encoded <<= 8;
encoded |= nibbleHex(_b); // lower 4 bits
}
/**
* @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes.
* `second` contains the encoded lower 16 bytes.
*
* @param _b The 32 bytes as uint256
* @return first - The top 16 bytes
* @return second - The bottom 16 bytes
*/
function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) {
for (uint8 i = 31; i > 15; i -= 1) {
uint8 _byte = uint8(_b >> (i * 8));
first |= byteHex(_byte);
if (i != 16) {
first <<= 16;
}
}
// abusing underflow here =_=
for (uint8 i = 15; i < 255 ; i -= 1) {
uint8 _byte = uint8(_b >> (i * 8));
second |= byteHex(_byte);
if (i != 0) {
second <<= 16;
}
}
}
/**
* @notice Changes the endianness of a uint256.
* @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
* @param _b The unsigned integer to reverse
* @return v - The reversed value
*/
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
/**
* @notice Create a mask with the highest `_len` bits set.
* @param _len The length
* @return mask - The mask
*/
function leftMask(uint8 _len) private pure returns (uint256 mask) {
// ugly. redo without assembly?
assembly {
// solium-disable-previous-line security/no-inline-assembly
mask := sar(
sub(_len, 1),
0x8000000000000000000000000000000000000000000000000000000000000000
)
}
}
/**
* @notice Return the null view.
* @return bytes29 - The null view
*/
function nullView() internal pure returns (bytes29) {
return NULL;
}
/**
* @notice Check if the view is null.
* @return bool - True if the view is null
*/
function isNull(bytes29 memView) internal pure returns (bool) {
return memView == NULL;
}
/**
* @notice Check if the view is not null.
* @return bool - True if the view is not null
*/
function notNull(bytes29 memView) internal pure returns (bool) {
return !isNull(memView);
}
/**
* @notice Check if the view is of a valid type and points to a valid location
* in memory.
* @dev We perform this check by examining solidity's unallocated memory
* pointer and ensuring that the view's upper bound is less than that.
* @param memView The view
* @return ret - True if the view is valid
*/
function isValid(bytes29 memView) internal pure returns (bool ret) {
if (typeOf(memView) == 0xffffffffff) {return false;}
uint256 _end = end(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
ret := not(gt(_end, mload(0x40)))
}
}
/**
* @notice Require that a typed memory view be valid.
* @dev Returns the view for easy chaining.
* @param memView The view
* @return bytes29 - The validated view
*/
function assertValid(bytes29 memView) internal pure returns (bytes29) {
require(isValid(memView), "Validity assertion failed");
return memView;
}
/**
* @notice Return true if the memview is of the expected type. Otherwise false.
* @param memView The view
* @param _expected The expected type
* @return bool - True if the memview is of the expected type
*/
function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) {
return typeOf(memView) == _expected;
}
/**
* @notice Require that a typed memory view has a specific type.
* @dev Returns the view for easy chaining.
* @param memView The view
* @param _expected The expected type
* @return bytes29 - The view with validated type
*/
function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) {
if (!isType(memView, _expected)) {
(, uint256 g) = encodeHex(uint256(typeOf(memView)));
(, uint256 e) = encodeHex(uint256(_expected));
string memory err = string(
abi.encodePacked(
"Type assertion failed. Got 0x",
uint80(g),
". Expected 0x",
uint80(e)
)
);
revert(err);
}
return memView;
}
/**
* @notice Return an identical view with a different type.
* @param memView The view
* @param _newType The new type
* @return newView - The new view with the specified type
*/
function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) {
// then | in the new type
assembly {
// solium-disable-previous-line security/no-inline-assembly
// shift off the top 5 bytes
newView := or(newView, shr(40, shl(40, memView)))
newView := or(newView, shl(216, _newType))
}
}
/**
* @notice Unsafe raw pointer construction. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @dev Unsafe raw pointer construction. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @param _type The type
* @param _loc The memory address
* @param _len The length
* @return newView - The new view with the specified type, location and length
*/
function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) {
assembly {
// solium-disable-previous-line security/no-inline-assembly
newView := shl(96, or(newView, _type)) // insert type
newView := shl(96, or(newView, _loc)) // insert loc
newView := shl(24, or(newView, _len)) // empty bottom 3 bytes
}
}
/**
* @notice Instantiate a new memory view. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @dev Instantiate a new memory view. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @param _type The type
* @param _loc The memory address
* @param _len The length
* @return newView - The new view with the specified type, location and length
*/
function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) {
uint256 _end = _loc.add(_len);
assembly {
// solium-disable-previous-line security/no-inline-assembly
if gt(_end, mload(0x40)) {
_end := 0
}
}
if (_end == 0) {
return NULL;
}
newView = unsafeBuildUnchecked(_type, _loc, _len);
}
/**
* @notice Instantiate a memory view from a byte array.
* @dev Note that due to Solidity memory representation, it is not possible to
* implement a deref, as the `bytes` type stores its len in memory.
* @param arr The byte array
* @param newType The type
* @return bytes29 - The memory view
*/
function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) {
uint256 _len = arr.length;
uint256 _loc;
assembly {
// solium-disable-previous-line security/no-inline-assembly
_loc := add(arr, 0x20) // our view is of the data, not the struct
}
return build(newType, _loc, _len);
}
/**
* @notice Return the associated type information.
* @param memView The memory view
* @return _type - The type associated with the view
*/
function typeOf(bytes29 memView) internal pure returns (uint40 _type) {
assembly {
// solium-disable-previous-line security/no-inline-assembly
// 216 == 256 - 40
_type := shr(216, memView) // shift out lower 24 bytes
}
}
/**
* @notice Optimized type comparison. Checks that the 5-byte type flag is equal.
* @param left The first view
* @param right The second view
* @return bool - True if the 5-byte type flag is equal
*/
function sameType(bytes29 left, bytes29 right) internal pure returns (bool) {
return (left ^ right) >> (2 * TWELVE_BYTES) == 0;
}
/**
* @notice Return the memory address of the underlying bytes.
* @param memView The view
* @return _loc - The memory address
*/
function loc(bytes29 memView) internal pure returns (uint96 _loc) {
uint256 _mask = LOW_12_MASK; // assembly can't use globals
assembly {
// solium-disable-previous-line security/no-inline-assembly
// 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space)
_loc := and(shr(120, memView), _mask)
}
}
/**
* @notice The number of memory words this memory view occupies, rounded up.
* @param memView The view
* @return uint256 - The number of memory words
*/
function words(bytes29 memView) internal pure returns (uint256) {
return uint256(len(memView)).add(32) / 32;
}
/**
* @notice The in-memory footprint of a fresh copy of the view.
* @param memView The view
* @return uint256 - The in-memory footprint of a fresh copy of the view.
*/
function footprint(bytes29 memView) internal pure returns (uint256) {
return words(memView) * 32;
}
/**
* @notice The number of bytes of the view.
* @param memView The view
* @return _len - The length of the view
*/
function len(bytes29 memView) internal pure returns (uint96 _len) {
uint256 _mask = LOW_12_MASK; // assembly can't use globals
assembly {
// solium-disable-previous-line security/no-inline-assembly
_len := and(shr(24, memView), _mask)
}
}
/**
* @notice Returns the endpoint of `memView`.
* @param memView The view
* @return uint256 - The endpoint of `memView`
*/
function end(bytes29 memView) internal pure returns (uint256) {
return loc(memView) + len(memView);
}
/**
* @notice Safe slicing without memory modification.
* @param memView The view
* @param _index The start index
* @param _len The length
* @param newType The new type
* @return bytes29 - The new view
*/
function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) {
uint256 _loc = loc(memView);
// Ensure it doesn't overrun the view
if (_loc.add(_index).add(_len) > end(memView)) {
return NULL;
}
_loc = _loc.add(_index);
return build(newType, _loc, _len);
}
/**
* @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes.
* @param memView The view
* @param _len The length
* @param newType The new type
* @return bytes29 - The new view
*/
function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) {
return slice(memView, 0, _len, newType);
}
/**
* @notice Shortcut to `slice`. Gets a view representing the last `_len` byte.
* @param memView The view
* @param _len The length
* @param newType The new type
* @return bytes29 - The new view
*/
function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) {
return slice(memView, uint256(len(memView)).sub(_len), _len, newType);
}
/**
* @notice Construct an error message for an indexing overrun.
* @param _loc The memory address
* @param _len The length
* @param _index The index
* @param _slice The slice where the overrun occurred
* @return err - The err
*/
function indexErrOverrun(
uint256 _loc,
uint256 _len,
uint256 _index,
uint256 _slice
) internal pure returns (string memory err) {
(, uint256 a) = encodeHex(_loc);
(, uint256 b) = encodeHex(_len);
(, uint256 c) = encodeHex(_index);
(, uint256 d) = encodeHex(_slice);
err = string(
abi.encodePacked(
"TypedMemView/index - Overran the view. Slice is at 0x",
uint48(a),
" with length 0x",
uint48(b),
". Attempted to index at offset 0x",
uint48(c),
" with length 0x",
uint48(d),
"."
)
);
}
/**
* @notice Load up to 32 bytes from the view onto the stack.
* @dev Returns a bytes32 with only the `_bytes` highest bytes set.
* This can be immediately cast to a smaller fixed-length byte array.
* To automatically cast to an integer, use `indexUint`.
* @param memView The view
* @param _index The index
* @param _bytes The bytes
* @return result - The 32 byte result
*/
function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) {
if (_bytes == 0) {return bytes32(0);}
if (_index.add(_bytes) > len(memView)) {
revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes)));
}
require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes");
uint8 bitLength = _bytes * 8;
uint256 _loc = loc(memView);
uint256 _mask = leftMask(bitLength);
assembly {
// solium-disable-previous-line security/no-inline-assembly
result := and(mload(add(_loc, _index)), _mask)
}
}
/**
* @notice Parse an unsigned integer from the view at `_index`.
* @dev Requires that the view have >= `_bytes` bytes following that index.
* @param memView The view
* @param _index The index
* @param _bytes The bytes
* @return result - The unsigned integer
*/
function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) {
return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8);
}
/**
* @notice Parse an unsigned integer from LE bytes.
* @param memView The view
* @param _index The index
* @param _bytes The bytes
* @return result - The unsigned integer
*/
function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) {
return reverseUint256(uint256(index(memView, _index, _bytes)));
}
/**
* @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes
* following that index.
* @param memView The view
* @param _index The index
* @return address - The address
*/
function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) {
return address(uint160(indexUint(memView, _index, 20)));
}
/**
* @notice Return the keccak256 hash of the underlying memory
* @param memView The view
* @return digest - The keccak256 hash of the underlying memory
*/
function keccak(bytes29 memView) internal pure returns (bytes32 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
digest := keccak256(_loc, _len)
}
}
/**
* @notice Return the sha2 digest of the underlying memory.
* @dev We explicitly deallocate memory afterwards.
* @param memView The view
* @return digest - The sha2 hash of the underlying memory
*/
function sha2(bytes29 memView) internal view returns (bytes32 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1
digest := mload(ptr)
}
}
/**
* @notice Implements bitcoin's hash160 (rmd160(sha2()))
* @param memView The pre-image
* @return digest - the Digest
*/
function hash160(bytes29 memView) internal view returns (bytes20 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2
pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160
digest := mload(add(ptr, 0xc)) // return value is 0-prefixed.
}
}
/**
* @notice Implements bitcoin's hash256 (double sha2)
* @param memView A view of the preimage
* @return digest - the Digest
*/
function hash256(bytes29 memView) internal view returns (bytes32 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1
pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2
digest := mload(ptr)
}
}
/**
* @notice Return true if the underlying memory is equal. Else false.
* @param left The first view
* @param right The second view
* @return bool - True if the underlying memory is equal
*/
function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) {
return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right);
}
/**
* @notice Return false if the underlying memory is equal. Else true.
* @param left The first view
* @param right The second view
* @return bool - False if the underlying memory is equal
*/
function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) {
return !untypedEqual(left, right);
}
/**
* @notice Compares type equality.
* @dev Shortcuts if the pointers are identical, otherwise compares type and digest.
* @param left The first view
* @param right The second view
* @return bool - True if the types are the same
*/
function equal(bytes29 left, bytes29 right) internal pure returns (bool) {
return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right));
}
/**
* @notice Compares type inequality.
* @dev Shortcuts if the pointers are identical, otherwise compares type and digest.
* @param left The first view
* @param right The second view
* @return bool - True if the types are not the same
*/
function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) {
return !equal(left, right);
}
/**
* @notice Copy the view to a location, return an unsafe memory reference
* @dev Super Dangerous direct memory access.
*
* This reference can be overwritten if anything else modifies memory (!!!).
* As such it MUST be consumed IMMEDIATELY.
* This function is private to prevent unsafe usage by callers.
* @param memView The view
* @param _newLoc The new location
* @return written - the unsafe memory reference
*/
function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) {
require(notNull(memView), "TypedMemView/copyTo - Null pointer deref");
require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref");
uint256 _len = len(memView);
uint256 _oldLoc = loc(memView);
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40)
// revert if we're writing in occupied memory
if gt(ptr, _newLoc) {
revert(0x60, 0x20) // empty revert message
}
// use the identity precompile to copy
// guaranteed not to fail, so pop the success
pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len))
}
written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len);
}
/**
* @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to
* the new memory
* @dev Shortcuts if the pointers are identical, otherwise compares type and digest.
* @param memView The view
* @return ret - The view pointing to the new memory
*/
function clone(bytes29 memView) internal view returns (bytes memory ret) {
uint256 ptr;
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
ret := ptr
}
unsafeCopyTo(memView, ptr + 0x20);
assembly {
// solium-disable-previous-line security/no-inline-assembly
mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer
mstore(ptr, _len) // write len of new array (in bytes)
}
}
/**
* @notice Join the views in memory, return an unsafe reference to the memory.
* @dev Super Dangerous direct memory access.
*
* This reference can be overwritten if anything else modifies memory (!!!).
* As such it MUST be consumed IMMEDIATELY.
* This function is private to prevent unsafe usage by callers.
* @param memViews The views
* @return unsafeView - The conjoined view pointing to the new memory
*/
function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) {
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
// revert if we're writing in occupied memory
if gt(ptr, _location) {
revert(0x60, 0x20) // empty revert message
}
}
uint256 _offset = 0;
for (uint256 i = 0; i < memViews.length; i ++) {
bytes29 memView = memViews[i];
unsafeCopyTo(memView, _location + _offset);
_offset += len(memView);
}
unsafeView = unsafeBuildUnchecked(0, _location, _offset);
}
/**
* @notice Produce the keccak256 digest of the concatenated contents of multiple views.
* @param memViews The views
* @return bytes32 - The keccak256 digest
*/
function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) {
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
}
return keccak(unsafeJoin(memViews, ptr));
}
/**
* @notice Produce the sha256 digest of the concatenated contents of multiple views.
* @param memViews The views
* @return bytes32 - The sha256 digest
*/
function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) {
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
}
return sha2(unsafeJoin(memViews, ptr));
}
/**
* @notice copies all views, joins them into a new bytearray.
* @param memViews The views
* @return ret - The new byte array
*/
function join(bytes29[] memory memViews) internal view returns (bytes memory ret) {
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
}
bytes29 _newView = unsafeJoin(memViews, ptr + 0x20);
uint256 _written = len(_newView);
uint256 _footprint = footprint(_newView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
// store the legnth
mstore(ptr, _written)
// new pointer is old + 0x20 + the footprint of the body
mstore(0x40, add(add(ptr, _footprint), 0x20))
ret := ptr
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.10;
/*
The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, 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 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;
require(c / _a == _b, "Overflow during multiplication.");
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) {
require(_b <= _a, "Underflow during subtraction.");
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
require(c >= _a, "Overflow during addition.");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IMessageRecipient {
function handle(
uint32 _origin,
bytes32 _sender,
bytes memory _message
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
| 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 {
token.decimals = decimals_;
}
| 1,230,214 |
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
contract FlightSuretyData is Ownable {
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
struct InsuranceAgreement {
address insuredPassenger;
uint256 insuredAmount;
}
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => bool) private authorizedContracts;
mapping(address => uint8) private registeredAirlines; // 0: not registered, 1: registered but have not paid
// 2: registered and paid
mapping(bytes32 => InsuranceAgreement[]) private insurances;
mapping(address => uint256) private insurancePayouts;
uint256 private constant airlineFee = 10 ether;
uint256 private constant maxInsuranceFee = 1 ether;
event AirlineRegistered(address airline);
event AirlineFunded(address airline);
event InsureeCredited(address insuree, uint256 amount);
event InsuracePayoutWithdrawn(address insured, uint256 insuranceValue);
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(address firstAirline) {
_registerAirline(firstAirline);
}
/********************************************************************************************/
/* 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 Modifiers that requires the caller to be authorised
*/
modifier requireAuthorised() {
require(authorizedContracts[msg.sender], "Not authorised to call the 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 Authorise the calling address
*/
function authorizeCaller(address _address) public onlyOwner {
authorizedContracts[_address] = true;
}
/**
* @dev Removes the authorisation for the address
*/
function revokeAuthorisation(address _address) public onlyOwner {
authorizedContracts[_address] = false;
}
/**
* @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 onlyOwner {
operational = mode;
}
/**
* @dev Checks if the airline is registered and paid already
*/
function isAirline(address _address) public view returns(bool) {
return registeredAirlines[_address] == 2;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address _address) external requireAuthorised requireIsOperational {
_registerAirline(_address);
emit AirlineRegistered(_address);
}
function _registerAirline(address _address) private {
registeredAirlines[_address] = 1;
}
/**
* @dev purely for testing purposes
*/
function testOperational() public requireIsOperational {}
/**
* @dev Buy insurance for a flight
*
* @param passenger address of the passenger buying the insurance
* @param flight name of the flight to be insured
*
*/
function buy(address passenger, bytes32 flight) external payable requireAuthorised requireIsOperational {
require(msg.value <= maxInsuranceFee, "Maximum insurance fee of 1 ether");
InsuranceAgreement memory agreement = InsuranceAgreement({
insuredPassenger: passenger,
insuredAmount: msg.value
});
insurances[flight].push(agreement);
}
/**
* @dev Credits payouts to insurees
*
* @param flight the flight key for which we are claiming insurance
*/
function creditInsurees(bytes32 flight) external requireIsOperational requireAuthorised {
uint arrayLength = insurances[flight].length;
for (uint i = 0; i < arrayLength; i++) {
InsuranceAgreement memory agreement = insurances[flight][i];
uint256 amount = agreement.insuredAmount * 3 / 2; //1.5 multiplier
address key = agreement.insuredPassenger;
insurancePayouts[key] = amount;
emit InsureeCredited(key, amount);
}
// Clean up the insurance
delete(insurances[flight]);
}
/**
* @dev Transfers eligible payout funds to insuree
*
* @param insured the insured passenger to be paid
*/
function pay(address payable insured) external requireIsOperational requireAuthorised {
uint256 insuranceValue = insurancePayouts[insured];
require(insuranceValue > 0, "No funds to pay");
delete insurancePayouts[insured];
insured.transfer(insuranceValue);
emit InsuracePayoutWithdrawn(insured, insuranceValue);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(address airline) public payable requireIsOperational requireAuthorised {
if (registeredAirlines[airline] == 0){
revert("Airline not registered yet");
}
require(registeredAirlines[airline] == 1, "You have paid already");
require(msg.value >= airlineFee, "Need to pay at least 10 ether");
registeredAirlines[airline] = 2;
emit AirlineFunded(airline);
}
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.
*
* No need to add requireIsOperational given it calls fund which requires it
*/
receive() external payable requireIsOperational {
fund(msg.sender);
}
}
| Authorise the calling address/ | function authorizeCaller(address _address) public onlyOwner {
authorizedContracts[_address] = true;
}
| 5,543,082 |
./full_match/44787/0xBef2f0EdaBD0fE1cb42994f7BD6e15C5d3364aAf/sources/newburn.sol | Define the conversion rate: 1000 staked tokens => 1 new token Calculate the amount of new tokens to send | function calculateNewTokenAmount(uint256 burnedAmount) internal pure returns (uint256) {
uint256 conversionRate = 1000;
uint256 newTokenAmount = burnedAmount / conversionRate;
return newTokenAmount;
}
| 13,276,576 |
./full_match/42/0xba39d530016f5b50932faCfFAff16A391f1AFf14/sources/contracts/connector.sol | proof is currently a placeholder for when associated proof for addressType is added | function addCbAddress(
address newCbAddress,
bytes1 addressType,
bytes memory proof
) public onlyadmin {
cbAddresses[newCbAddress] = addressType;
}
| 16,230,346 |
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ERC20Helpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-pool-utils/contracts/LegacyBasePool.sol";
import "@balancer-labs/v2-pool-utils/contracts/interfaces/IRateProvider.sol";
import "@balancer-labs/v2-pool-utils/contracts/rates/PriceRateCache.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IGeneralPool.sol";
import "./LinearMath.sol";
import "./LinearPoolUserData.sol";
/**
* @dev Linear Pools are designed to hold two assets: "main" and "wrapped" tokens that have an equal value underlying
* token (e.g., DAI and waDAI). There must be an external feed available to provide an exact, non-manipulable exchange
* rate between the tokens. In particular, any reversible manipulation (e.g. causing the rate to increase and then
* decrease) can lead to severe issues and loss of funds.
*
* The Pool will register three tokens in the Vault however: the two assets and the BPT itself,
* so that BPT can be exchanged (effectively joining and exiting) via swaps.
*
* Despite inheriting from BasePool, much of the basic behavior changes. This Pool does not support regular joins and
* exits, as the entire BPT supply is 'preminted' during initialization.
*
* Unlike most other Pools, this one does not attempt to create revenue by charging fees: value is derived by holding
* the wrapped, yield-bearing asset. However, the 'swap fee percentage' value is still used, albeit with a different
* meaning. This Pool attempts to hold a certain amount of "main" tokens, between a lower and upper target value.
* The pool charges fees on trades that move the balance outside that range, which are then paid back as incentives to
* traders whose swaps return the balance to the desired region.
* The net revenue via fees is expected to be zero: all collected fees are used to pay for this 'rebalancing'.
*/
abstract contract LinearPool is LegacyBasePool, IGeneralPool, IRateProvider {
using WordCodec for bytes32;
using FixedPoint for uint256;
using PriceRateCache for bytes32;
using LinearPoolUserData for bytes;
uint256 private constant _TOTAL_TOKENS = 3; // Main token, wrapped token, BPT
// This is the maximum token amount the Vault can hold. In regular operation, the total BPT supply remains constant
// and equal to _INITIAL_BPT_SUPPLY, but most of it remains in the Pool, waiting to be exchanged for tokens. The
// actual amount of BPT in circulation is the total supply minus the amount held by the Pool, and is known as the
// 'virtual supply'.
// The total supply can only change if the emergency pause is activated by governance, enabling an
// alternative proportional exit that burns BPT. As this is not expected to happen, we optimize for
// success by using _INITIAL_BPT_SUPPLY instead of totalSupply(), saving a storage read. This optimization is only
// valid if the Pool is never paused: in case of an emergency that leads to burned tokens, the Pool should not
// be used after the buffer period expires and it automatically 'unpauses'.
uint256 private constant _INITIAL_BPT_SUPPLY = 2**(112) - 1;
IERC20 private immutable _mainToken;
IERC20 private immutable _wrappedToken;
// The indices of each token when registered, which can then be used to access the balances array.
uint256 private immutable _bptIndex;
uint256 private immutable _mainIndex;
uint256 private immutable _wrappedIndex;
// Both BPT and the main token have a regular, constant scaling factor (equal to FixedPoint.ONE for BPT, and
// dependent on the number of decimals for the main token). However, the wrapped token's scaling factor has two
// components: the usual token decimal scaling factor, and an externally provided rate used to convert wrapped
// tokens to an equivalent main token amount. This external rate is expected to be ever increasing, reflecting the
// fact that the wrapped token appreciates in value over time (e.g. because it is accruing interest).
uint256 private immutable _scalingFactorMainToken;
uint256 private immutable _scalingFactorWrappedToken;
// The lower and upper target are in BasePool's misc data field, which has 192 bits available (as it shares the same
// storage slot as the swap fee percentage, which is 64 bits). These are already scaled by the main token's scaling
// factor, which means that the maximum upper target is ~80 billion in the main token units if the token were to
// have 18 decimals (2^(192/2) / 10^18), which is more than enough.
// [ 64 bits | 96 bits | 96 bits ]
// [ reserved | upper target | lower target ]
// [ base pool swap fee | misc data ]
// [ MSB LSB ]
uint256 private constant _LOWER_TARGET_OFFSET = 0;
uint256 private constant _UPPER_TARGET_OFFSET = 96;
uint256 private constant _MAX_UPPER_TARGET = 2**(96) - 1;
event TargetsSet(IERC20 indexed token, uint256 lowerTarget, uint256 upperTarget);
constructor(
IVault vault,
string memory name,
string memory symbol,
IERC20 mainToken,
IERC20 wrappedToken,
uint256 upperTarget,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
LegacyBasePool(
vault,
IVault.PoolSpecialization.GENERAL,
name,
symbol,
_sortTokens(mainToken, wrappedToken, this),
new address[](_TOTAL_TOKENS),
swapFeePercentage,
pauseWindowDuration,
bufferPeriodDuration,
owner
)
{
// Set tokens
_mainToken = mainToken;
_wrappedToken = wrappedToken;
// Set token indexes
(uint256 mainIndex, uint256 wrappedIndex, uint256 bptIndex) = _getSortedTokenIndexes(
mainToken,
wrappedToken,
this
);
_bptIndex = bptIndex;
_mainIndex = mainIndex;
_wrappedIndex = wrappedIndex;
// Set scaling factors
_scalingFactorMainToken = _computeScalingFactor(mainToken);
_scalingFactorWrappedToken = _computeScalingFactor(wrappedToken);
// Set initial targets. Lower target must be set to zero because initially there are no fees accumulated.
// Otherwise the pool will owe fees at start which results in a manipulable rate.
uint256 lowerTarget = 0;
_setTargets(mainToken, lowerTarget, upperTarget);
}
function getMainToken() public view returns (address) {
return address(_mainToken);
}
function getWrappedToken() public view returns (address) {
return address(_wrappedToken);
}
function getBptIndex() external view returns (uint256) {
return _bptIndex;
}
function getMainIndex() external view returns (uint256) {
return _mainIndex;
}
function getWrappedIndex() external view returns (uint256) {
return _wrappedIndex;
}
/**
* @dev Finishes initialization of the Linear Pool: it is unusable before calling this function as no BPT will have
* been minted.
*
* Since Linear Pools have preminted BPT stored in the Vault, they require an initial join to deposit said BPT as
* their balance. Unfortunately, this cannot be performed during construction, as a join involves calling the
* `onJoinPool` function on the Pool, and the Pool will not have any code until construction finishes. Therefore,
* this must happen in a separate call.
*
* It is highly recommended to create Linear pools using the LinearPoolFactory, which calls `initialize`
* automatically.
*/
function initialize() external {
bytes32 poolId = getPoolId();
(IERC20[] memory tokens, , ) = getVault().getPoolTokens(poolId);
// Joins typically involve the Pool receiving tokens in exchange for newly-minted BPT. In this case however, the
// Pool will mint the entire BPT supply to itself, and join itself with it.
uint256[] memory maxAmountsIn = new uint256[](_TOTAL_TOKENS);
maxAmountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY;
// The first time this executes, it will call `_onInitializePool` (as the BPT supply will be zero). Future calls
// will be routed to `_onJoinPool`, which always reverts, meaning `initialize` will only execute once.
IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({
assets: _asIAsset(tokens),
maxAmountsIn: maxAmountsIn,
userData: "",
fromInternalBalance: false
});
getVault().joinPool(poolId, address(this), address(this), request);
}
/**
* @dev Implementation of onSwap, from IGeneralPool.
*/
function onSwap(
SwapRequest memory request,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) public view override onlyVault(request.poolId) whenNotPaused returns (uint256) {
// In most Pools, swaps involve exchanging one token held by the Pool for another. In this case however, since
// one of the three tokens is the BPT itself, a swap might also be a join (main/wrapped for BPT) or an exit
// (BPT for main/wrapped).
// All three swap types (swaps, joins and exits) are fully disabled if the emergency pause is enabled. Under
// these circumstances, the Pool should be exited using the regular Vault.exitPool function.
// Sanity check: this is not entirely necessary as the Vault's interface enforces the indices to be valid, but
// the check is cheap to perform.
_require(indexIn < _TOTAL_TOKENS && indexOut < _TOTAL_TOKENS, Errors.OUT_OF_BOUNDS);
// Note that we already know the indices of the main token, wrapped token and BPT, so there is no need to pass
// these indices to the inner functions.
// Upscale balances by the scaling factors (taking into account the wrapped token rate)
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 lowerTarget, uint256 upperTarget) = getTargets();
LinearMath.Params memory params = LinearMath.Params({
fee: getSwapFeePercentage(),
lowerTarget: lowerTarget,
upperTarget: upperTarget
});
if (request.kind == IVault.SwapKind.GIVEN_IN) {
// The amount given is for token in, the amount calculated is for token out
request.amount = _upscale(request.amount, scalingFactors[indexIn]);
uint256 amountOut = _onSwapGivenIn(request, balances, params);
// amountOut tokens are exiting the Pool, so we round down.
return _downscaleDown(amountOut, scalingFactors[indexOut]);
} else {
// The amount given is for token out, the amount calculated is for token in
request.amount = _upscale(request.amount, scalingFactors[indexOut]);
uint256 amountIn = _onSwapGivenOut(request, balances, params);
// amountIn tokens are entering the Pool, so we round up.
return _downscaleUp(amountIn, scalingFactors[indexIn]);
}
}
function _onSwapGivenIn(
SwapRequest memory request,
uint256[] memory balances,
LinearMath.Params memory params
) internal view returns (uint256) {
if (request.tokenIn == this) {
return _swapGivenBptIn(request, balances, params);
} else if (request.tokenIn == _mainToken) {
return _swapGivenMainIn(request, balances, params);
} else if (request.tokenIn == _wrappedToken) {
return _swapGivenWrappedIn(request, balances, params);
} else {
_revert(Errors.INVALID_TOKEN);
}
}
function _swapGivenBptIn(
SwapRequest memory request,
uint256[] memory balances,
LinearMath.Params memory params
) internal view returns (uint256) {
_require(request.tokenOut == _mainToken || request.tokenOut == _wrappedToken, Errors.INVALID_TOKEN);
return
(request.tokenOut == _mainToken ? LinearMath._calcMainOutPerBptIn : LinearMath._calcWrappedOutPerBptIn)(
request.amount,
balances[_mainIndex],
balances[_wrappedIndex],
_getApproximateVirtualSupply(balances[_bptIndex]),
params
);
}
function _swapGivenMainIn(
SwapRequest memory request,
uint256[] memory balances,
LinearMath.Params memory params
) internal view returns (uint256) {
_require(request.tokenOut == _wrappedToken || request.tokenOut == this, Errors.INVALID_TOKEN);
return
request.tokenOut == this
? LinearMath._calcBptOutPerMainIn(
request.amount,
balances[_mainIndex],
balances[_wrappedIndex],
_getApproximateVirtualSupply(balances[_bptIndex]),
params
)
: LinearMath._calcWrappedOutPerMainIn(request.amount, balances[_mainIndex], params);
}
function _swapGivenWrappedIn(
SwapRequest memory request,
uint256[] memory balances,
LinearMath.Params memory params
) internal view returns (uint256) {
_require(request.tokenOut == _mainToken || request.tokenOut == this, Errors.INVALID_TOKEN);
return
request.tokenOut == this
? LinearMath._calcBptOutPerWrappedIn(
request.amount,
balances[_mainIndex],
balances[_wrappedIndex],
_getApproximateVirtualSupply(balances[_bptIndex]),
params
)
: LinearMath._calcMainOutPerWrappedIn(request.amount, balances[_mainIndex], params);
}
function _onSwapGivenOut(
SwapRequest memory request,
uint256[] memory balances,
LinearMath.Params memory params
) internal view returns (uint256) {
if (request.tokenOut == this) {
return _swapGivenBptOut(request, balances, params);
} else if (request.tokenOut == _mainToken) {
return _swapGivenMainOut(request, balances, params);
} else if (request.tokenOut == _wrappedToken) {
return _swapGivenWrappedOut(request, balances, params);
} else {
_revert(Errors.INVALID_TOKEN);
}
}
function _swapGivenBptOut(
SwapRequest memory request,
uint256[] memory balances,
LinearMath.Params memory params
) internal view returns (uint256) {
_require(request.tokenIn == _mainToken || request.tokenIn == _wrappedToken, Errors.INVALID_TOKEN);
return
(request.tokenIn == _mainToken ? LinearMath._calcMainInPerBptOut : LinearMath._calcWrappedInPerBptOut)(
request.amount,
balances[_mainIndex],
balances[_wrappedIndex],
_getApproximateVirtualSupply(balances[_bptIndex]),
params
);
}
function _swapGivenMainOut(
SwapRequest memory request,
uint256[] memory balances,
LinearMath.Params memory params
) internal view returns (uint256) {
_require(request.tokenIn == _wrappedToken || request.tokenIn == this, Errors.INVALID_TOKEN);
return
request.tokenIn == this
? LinearMath._calcBptInPerMainOut(
request.amount,
balances[_mainIndex],
balances[_wrappedIndex],
_getApproximateVirtualSupply(balances[_bptIndex]),
params
)
: LinearMath._calcWrappedInPerMainOut(request.amount, balances[_mainIndex], params);
}
function _swapGivenWrappedOut(
SwapRequest memory request,
uint256[] memory balances,
LinearMath.Params memory params
) internal view returns (uint256) {
_require(request.tokenIn == _mainToken || request.tokenIn == this, Errors.INVALID_TOKEN);
return
request.tokenIn == this
? LinearMath._calcBptInPerWrappedOut(
request.amount,
balances[_mainIndex],
balances[_wrappedIndex],
_getApproximateVirtualSupply(balances[_bptIndex]),
params
)
: LinearMath._calcMainInPerWrappedOut(request.amount, balances[_mainIndex], params);
}
function _onInitializePool(
bytes32,
address sender,
address recipient,
uint256[] memory,
bytes memory
) internal view override whenNotPaused returns (uint256, uint256[] memory) {
// Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function.
_require(sender == address(this), Errors.INVALID_INITIALIZATION);
_require(recipient == address(this), Errors.INVALID_INITIALIZATION);
// The full BPT supply will be minted and deposited in the Pool. Note that there is no need to approve the Vault
// as it already has infinite BPT allowance.
uint256 bptAmountOut = _INITIAL_BPT_SUPPLY;
uint256[] memory amountsIn = new uint256[](_TOTAL_TOKENS);
amountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY;
return (bptAmountOut, amountsIn);
}
function _onJoinPool(
bytes32,
address,
address,
uint256[] memory,
uint256,
uint256,
uint256[] memory,
bytes memory
)
internal
pure
override
returns (
uint256,
uint256[] memory,
uint256[] memory
)
{
_revert(Errors.UNHANDLED_BY_LINEAR_POOL);
}
function _onExitPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256,
uint256[] memory,
bytes memory userData
)
internal
view
override
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
)
{
// Exits typically revert, except for the proportional exit when the emergency pause mechanism has been
// triggered. This allows for a simple and safe way to exit the Pool.
// Note that the rate cache will not be automatically updated in such a scenario (though this can be still done
// manually). This however should not lead to any issues as the rate is not important during the emergency exit.
// On the contrary, decoupling the rate provider from the emergency exit might be useful under these
// circumstances.
LinearPoolUserData.ExitKind kind = userData.exitKind();
if (kind != LinearPoolUserData.ExitKind.EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT) {
_revert(Errors.UNHANDLED_BY_LINEAR_POOL);
} else {
_ensurePaused();
// Note that this will cause the user's BPT to be burned, which is not something that happens during
// regular operation of this Pool, and may lead to accounting errors. Because of this, it is highly
// advisable to stop using a Pool after it is paused and the pause window expires.
(bptAmountIn, amountsOut) = _emergencyProportionalExit(balances, userData);
// Due protocol fees are set to zero as this Pool accrues no fees and pays no protocol fees.
dueProtocolFeeAmounts = new uint256[](_getTotalTokens());
}
}
function _emergencyProportionalExit(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
// This proportional exit function is only enabled if the contract is paused, to provide users a way to
// retrieve their tokens in case of an emergency.
//
// This particular exit function is the only one available because it is the simplest, and therefore least
// likely to be incorrect, or revert and lock funds.
uint256 bptAmountIn = userData.exactBptInForTokensOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
// This process burns BPT, rendering `_getApproximateVirtualSupply` inaccurate, so we use the real method here
uint256[] memory amountsOut = LinearMath._calcTokensOutGivenExactBptIn(
balances,
bptAmountIn,
_getVirtualSupply(balances[_bptIndex]),
_bptIndex
);
return (bptAmountIn, amountsOut);
}
function _getMaxTokens() internal pure override returns (uint256) {
return _TOTAL_TOKENS;
}
function _getMinimumBpt() internal pure override returns (uint256) {
// Linear Pools don't lock any BPT, as the total supply will already be forever non-zero due to the preminting
// mechanism, ensuring initialization only occurs once.
return 0;
}
function _getTotalTokens() internal view virtual override returns (uint256) {
return _TOTAL_TOKENS;
}
function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) {
if (token == _mainToken) {
return _scalingFactorMainToken;
} else if (token == _wrappedToken) {
// The wrapped token's scaling factor is not constant, but increases over time as the wrapped token
// increases in value.
return _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate());
} else if (token == this) {
return FixedPoint.ONE;
} else {
_revert(Errors.INVALID_TOKEN);
}
}
function _scalingFactors() internal view virtual override returns (uint256[] memory) {
uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS);
// The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in
// value.
scalingFactors[_mainIndex] = _scalingFactorMainToken;
scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate());
scalingFactors[_bptIndex] = FixedPoint.ONE;
return scalingFactors;
}
// Price rates
/**
* @dev For a Linear Pool, the rate represents the appreciation of BPT with respect to the underlying tokens. This
* rate increases slowly as the wrapped token appreciates in value.
*/
function getRate() external view override returns (uint256) {
bytes32 poolId = getPoolId();
(, uint256[] memory balances, ) = getVault().getPoolTokens(poolId);
_upscaleArray(balances, _scalingFactors());
(uint256 lowerTarget, uint256 upperTarget) = getTargets();
LinearMath.Params memory params = LinearMath.Params({
fee: getSwapFeePercentage(),
lowerTarget: lowerTarget,
upperTarget: upperTarget
});
uint256 totalBalance = LinearMath._calcInvariant(
LinearMath._toNominal(balances[_mainIndex], params),
balances[_wrappedIndex]
);
// Note that we're dividing by the virtual supply, which may be zero (causing this call to revert). However, the
// only way for that to happen would be for all LPs to exit the Pool, and nothing prevents new LPs from
// joining it later on.
return totalBalance.divUp(_getApproximateVirtualSupply(balances[_bptIndex]));
}
function getWrappedTokenRate() external view returns (uint256) {
return _getWrappedTokenRate();
}
/**
* @dev Should be 1e18 for the subsequent calculation of the wrapper token scaling factor.
*/
function _getWrappedTokenRate() internal view virtual returns (uint256);
function getTargets() public view returns (uint256 lowerTarget, uint256 upperTarget) {
bytes32 miscData = _getMiscData();
lowerTarget = miscData.decodeUint96(_LOWER_TARGET_OFFSET);
upperTarget = miscData.decodeUint96(_UPPER_TARGET_OFFSET);
}
function _setTargets(
IERC20 mainToken,
uint256 lowerTarget,
uint256 upperTarget
) private {
_require(lowerTarget <= upperTarget, Errors.LOWER_GREATER_THAN_UPPER_TARGET);
_require(upperTarget <= _MAX_UPPER_TARGET, Errors.UPPER_TARGET_TOO_HIGH);
// Pack targets as two uint96 values into a single storage slot. This results in targets being capped to 96
// bits, but that should be more than enough.
_setMiscData(
WordCodec.encodeUint(lowerTarget, _LOWER_TARGET_OFFSET) |
WordCodec.encodeUint(upperTarget, _UPPER_TARGET_OFFSET)
);
emit TargetsSet(mainToken, lowerTarget, upperTarget);
}
function setTargets(uint256 newLowerTarget, uint256 newUpperTarget) external authenticate {
// For a new target range to be valid:
// - the pool must currently be between the current targets (meaning no fees are currently pending)
// - the pool must currently be between the new targets (meaning setting them does not cause for fees to be
// pending)
//
// The first requirement could be relaxed, as the LPs actually benefit from the pending fees not being paid out,
// but being stricter makes analysis easier at little expense.
(uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets();
_require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE);
_require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE);
_setTargets(_mainToken, newLowerTarget, newUpperTarget);
}
function setSwapFeePercentage(uint256 swapFeePercentage) public override {
// For the swap fee percentage to be changeable:
// - the pool must currently be between the current targets (meaning no fees are currently pending)
//
// As the amount of accrued fees is not explicitly stored but rather derived from the main token balance and the
// current swap fee percentage, requiring for no fees to be pending prevents the fee setter from changing the
// amount of pending fees, which they could use to e.g. drain Pool funds in the form of inflated fees.
(uint256 lowerTarget, uint256 upperTarget) = getTargets();
_require(_isMainBalanceWithinTargets(lowerTarget, upperTarget), Errors.OUT_OF_TARGET_RANGE);
super.setSwapFeePercentage(swapFeePercentage);
}
function _isMainBalanceWithinTargets(uint256 lowerTarget, uint256 upperTarget) private view returns (bool) {
bytes32 poolId = getPoolId();
(, uint256[] memory balances, ) = getVault().getPoolTokens(poolId);
uint256 mainTokenBalance = _upscale(balances[_mainIndex], _scalingFactor(_mainToken));
return mainTokenBalance >= lowerTarget && mainTokenBalance <= upperTarget;
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) {
return actionId == getActionId(this.setTargets.selector) || super._isOwnerOnlyAction(actionId);
}
/**
* @dev Returns the number of tokens in circulation.
*
* In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply`
* remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it.
*/
function getVirtualSupply() external view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
// We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has
// 18 decimals), but we do it for completeness.
uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this));
return _getVirtualSupply(bptBalance);
}
function _getVirtualSupply(uint256 bptBalance) internal view returns (uint256) {
return totalSupply().sub(bptBalance);
}
/**
* @dev Computes an approximation of virtual supply, which costs less gas than `_getVirtualSupply` and returns the
* same value in all cases except when the emergency pause has been enabled and BPT burned as part of the emergency
* exit process.
*/
function _getApproximateVirtualSupply(uint256 bptBalance) internal pure returns (uint256) {
// No need for checked arithmetic as _INITIAL_BPT_SUPPLY is always greater than any valid Vault BPT balance.
return _INITIAL_BPT_SUPPLY - bptBalance;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
uint256 internal constant NOT_TWO_TOKENS = 210;
uint256 internal constant DISABLED = 211;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;
uint256 internal constant ORACLE_NOT_INITIALIZED = 313;
uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;
uint256 internal constant ORACLE_INVALID_INDEX = 315;
uint256 internal constant ORACLE_BAD_SECS = 316;
uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317;
uint256 internal constant AMP_ONGOING_UPDATE = 318;
uint256 internal constant AMP_RATE_TOO_HIGH = 319;
uint256 internal constant AMP_NO_ONGOING_UPDATE = 320;
uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321;
uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322;
uint256 internal constant RELAYER_NOT_CONTRACT = 323;
uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324;
uint256 internal constant REBALANCING_RELAYER_REENTERED = 325;
uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326;
uint256 internal constant SWAPS_DISABLED = 327;
uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328;
uint256 internal constant PRICE_RATE_OVERFLOW = 329;
uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330;
uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331;
uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332;
uint256 internal constant UPPER_TARGET_TOO_HIGH = 333;
uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334;
uint256 internal constant OUT_OF_TARGET_RANGE = 335;
uint256 internal constant UNHANDLED_EXIT_KIND = 336;
uint256 internal constant UNAUTHORIZED_EXIT = 337;
uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338;
uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339;
uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340;
uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341;
uint256 internal constant INVALID_INITIALIZATION = 342;
uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343;
uint256 internal constant UNAUTHORIZED_OPERATION = 344;
uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
uint256 internal constant CALLER_IS_NOT_OWNER = 426;
uint256 internal constant NEW_OWNER_IS_ZERO = 427;
uint256 internal constant CODE_DEPLOYMENT_FAILED = 428;
uint256 internal constant CALL_TO_NON_CONTRACT = 429;
uint256 internal constant LOW_LEVEL_CALL_FAILED = 430;
uint256 internal constant NOT_PAUSED = 431;
uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432;
uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433;
uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol";
import "../openzeppelin/IERC20.sol";
// solhint-disable
function _asIAsset(IERC20[] memory tokens) pure returns (IAsset[] memory assets) {
// solhint-disable-next-line no-inline-assembly
assembly {
assets := tokens
}
}
function _sortTokens(
IERC20 tokenA,
IERC20 tokenB,
IERC20 tokenC
) pure returns (IERC20[] memory tokens) {
(uint256 indexTokenA, uint256 indexTokenB, uint256 indexTokenC) = _getSortedTokenIndexes(tokenA, tokenB, tokenC);
tokens = new IERC20[](3);
tokens[indexTokenA] = tokenA;
tokens[indexTokenB] = tokenB;
tokens[indexTokenC] = tokenC;
}
function _insertSorted(IERC20[] memory tokens, IERC20 token) pure returns (IERC20[] memory sorted) {
sorted = new IERC20[](tokens.length + 1);
if (tokens.length == 0) {
sorted[0] = token;
return sorted;
}
uint256 i;
for (i = tokens.length; i > 0 && tokens[i - 1] > token; i--) sorted[i] = tokens[i - 1];
for (uint256 j = 0; j < i; j++) sorted[j] = tokens[j];
sorted[i] = token;
}
function _getSortedTokenIndexes(
IERC20 tokenA,
IERC20 tokenB,
IERC20 tokenC
)
pure
returns (
uint256 indexTokenA,
uint256 indexTokenB,
uint256 indexTokenC
)
{
if (tokenA < tokenB) {
if (tokenB < tokenC) {
// (tokenA, tokenB, tokenC)
return (0, 1, 2);
} else if (tokenA < tokenC) {
// (tokenA, tokenC, tokenB)
return (0, 2, 1);
} else {
// (tokenC, tokenA, tokenB)
return (1, 2, 0);
}
} else {
// tokenB < tokenA
if (tokenC < tokenB) {
// (tokenC, tokenB, tokenA)
return (2, 1, 0);
} else if (tokenC < tokenA) {
// (tokenB, tokenC, tokenA)
return (2, 0, 1);
} else {
// (tokenB, tokenA, tokenC)
return (1, 0, 2);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant TWO = 2 * ONE;
uint256 internal constant FOUR = 4 * ONE;
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
// Optimize for when y equals 1.0, 2.0 or 4.0, as those are very simple to implement and occur often in 50/50
// and 80/20 Weighted Pools
if (y == ONE) {
return x;
} else if (y == TWO) {
return mulDown(x, x);
} else if (y == FOUR) {
uint256 square = mulDown(x, x);
return mulDown(square, square);
} else {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
// Optimize for when y equals 1.0, 2.0 or 4.0, as those are very simple to implement and occur often in 50/50
// and 80/20 Weighted Pools
if (y == ONE) {
return x;
} else if (y == TWO) {
return mulUp(x, x);
} else if (y == FOUR) {
uint256 square = mulUp(x, x);
return mulUp(square, square);
} else {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol";
import "@balancer-labs/v2-asset-manager-utils/contracts/IAssetManager.sol";
import "./BalancerPoolToken.sol";
import "./BasePoolAuthorization.sol";
// solhint-disable max-states-count
/**
* @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with optional
* Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism.
*
* Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that
* derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the
* `whenNotPaused` modifier.
*
* No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer.
*
* Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from
* BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces
* and implement the swap callbacks themselves.
*/
abstract contract LegacyBasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable {
using WordCodec for bytes32;
using FixedPoint for uint256;
uint256 private constant _MIN_TOKENS = 2;
uint256 private constant _DEFAULT_MINIMUM_BPT = 1e6;
// 1e18 corresponds to 1.0, or a 100% fee
uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001%
uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% - this fits in 64 bits
// Storage slot that can be used to store unrelated pieces of information. In particular, by default is used
// to store only the swap fee percentage of a pool. But it can be extended to store some more pieces of information.
// The swap fee percentage is stored in the most-significant 64 bits, therefore the remaining 192 bits can be
// used to store any other piece of information.
bytes32 private _miscData;
uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 192;
bytes32 private immutable _poolId;
event SwapFeePercentageChanged(uint256 swapFeePercentage);
constructor(
IVault vault,
IVault.PoolSpecialization specialization,
string memory name,
string memory symbol,
IERC20[] memory tokens,
address[] memory assetManagers,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
// Base Pools are expected to be deployed using factories. By using the factory address as the action
// disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for
// simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in
// any Pool created by the same factory), while still making action identifiers unique among different factories
// if the selectors match, preventing accidental errors.
Authentication(bytes32(uint256(msg.sender)))
BalancerPoolToken(name, symbol, vault)
BasePoolAuthorization(owner)
TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration)
{
_require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS);
_require(tokens.length <= _getMaxTokens(), Errors.MAX_TOKENS);
// The Vault only requires the token list to be ordered for the Two Token Pools specialization. However,
// to make the developer experience consistent, we are requiring this condition for all the native pools.
// Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same
// order. We rely on this property to make Pools simpler to write, as it lets us assume that the
// order of token-specific parameters (such as token weights) will not change.
InputHelpers.ensureArrayIsSorted(tokens);
_setSwapFeePercentage(swapFeePercentage);
bytes32 poolId = vault.registerPool(specialization);
vault.registerTokens(poolId, tokens, assetManagers);
// Set immutable state variables - these cannot be read from during construction
_poolId = poolId;
}
// Getters / Setters
function getPoolId() public view override returns (bytes32) {
return _poolId;
}
function _getTotalTokens() internal view virtual returns (uint256);
function _getMaxTokens() internal pure virtual returns (uint256);
/**
* @dev Returns the minimum BPT supply. This amount is minted to the zero address during initialization, effectively
* locking it.
*
* This is useful to make sure Pool initialization happens only once, but derived Pools can change this value (even
* to zero) by overriding this function.
*/
function _getMinimumBpt() internal pure virtual returns (uint256) {
return _DEFAULT_MINIMUM_BPT;
}
function getSwapFeePercentage() public view returns (uint256) {
return _miscData.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET);
}
function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused {
_setSwapFeePercentage(swapFeePercentage);
}
function _setSwapFeePercentage(uint256 swapFeePercentage) private {
_require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE);
_require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE);
_miscData = _miscData.insertUint64(swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET);
emit SwapFeePercentageChanged(swapFeePercentage);
}
function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig)
public
virtual
authenticate
whenNotPaused
{
_setAssetManagerPoolConfig(token, poolConfig);
}
function _setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) private {
bytes32 poolId = getPoolId();
(, , , address assetManager) = getVault().getPoolTokenInfo(poolId, token);
IAssetManager(assetManager).setConfig(poolId, poolConfig);
}
function setPaused(bool paused) external authenticate {
_setPaused(paused);
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) {
return
(actionId == getActionId(this.setSwapFeePercentage.selector)) ||
(actionId == getActionId(this.setAssetManagerPoolConfig.selector));
}
function _getMiscData() internal view returns (bytes32) {
return _miscData;
}
/**
* Inserts data into the least-significant 192 bits of the misc data storage slot.
* Note that the remaining 64 bits are used for the swap fee percentage and cannot be overloaded.
*/
function _setMiscData(bytes32 newData) internal {
_miscData = _miscData.insertBits192(newData, 0);
}
// Join / Exit Hooks
modifier onlyVault(bytes32 poolId) {
_require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT);
_require(poolId == getPoolId(), Errors.INVALID_POOL_ID);
_;
}
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
uint256[] memory scalingFactors = _scalingFactors();
if (totalSupply() == 0) {
(uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool(
poolId,
sender,
recipient,
scalingFactors,
userData
);
// On initialization, we lock _getMinimumBpt() by minting it for the zero address. This BPT acts as a
// minimum as it will never be burned, which reduces potential issues with rounding, and also prevents the
// Pool from ever being fully drained.
_require(bptAmountOut >= _getMinimumBpt(), Errors.MINIMUM_BPT);
_mintPoolTokens(address(0), _getMinimumBpt());
_mintPoolTokens(recipient, bptAmountOut - _getMinimumBpt());
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn, scalingFactors);
return (amountsIn, new uint256[](_getTotalTokens()));
} else {
_upscaleArray(balances, scalingFactors);
(uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
// Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it.
_mintPoolTokens(recipient, bptAmountOut);
// amountsIn are amounts entering the Pool, so we round up.
_downscaleUpArray(amountsIn, scalingFactors);
// dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(dueProtocolFeeAmounts, scalingFactors);
return (amountsIn, dueProtocolFeeAmounts);
}
}
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
// Note we no longer use `balances` after calling `_onExitPool`, which may mutate it.
_burnPoolTokens(sender, bptAmountIn);
// Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down.
_downscaleDownArray(amountsOut, scalingFactors);
_downscaleDownArray(dueProtocolFeeAmounts, scalingFactors);
return (amountsOut, dueProtocolFeeAmounts);
}
// Query functions
/**
* @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `sender` would have to supply.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryJoin(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptOut, uint256[] memory amountsIn) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onJoinPool,
_downscaleUpArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptOut, amountsIn);
}
/**
* @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `recipient` would receive.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryExit(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptIn, uint256[] memory amountsOut) {
InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens());
_queryAction(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
userData,
_onExitPool,
_downscaleDownArray
);
// The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement,
// and we don't need to return anything here - it just silences compiler warnings.
return (bptIn, amountsOut);
}
// Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are
// upscaled.
/**
* @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero.
*
* Returns the amount of BPT to mint, and the token amounts the Pool will receive in return.
*
* Minted BPT will be sent to `recipient`, except for _getMinimumBpt(), which will be deducted from this amount and
* sent to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP
* from ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire
* Pool's lifetime.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*/
function _onInitializePool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory scalingFactors,
bytes memory userData
) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn);
/**
* @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`).
*
* Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of
* tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* Minted BPT will be sent to `recipient`.
*
* The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will
* be downscaled (rounding up) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
returns (
uint256 bptAmountOut,
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
);
/**
* @dev Called whenever the Pool is exited.
*
* Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and
* the number of tokens to pay in protocol swap fees.
*
* Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when
* performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely.
*
* BPT will be burnt from `sender`.
*
* The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled
* (rounding down) before being returned to the Vault.
*
* Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These
* amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault.
*/
function _onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
);
// Internal functions
/**
* @dev Adds swap fee amount to `amount`, returning a higher value.
*/
function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount + fee amount, so we round up (favoring a higher fee amount).
return amount.divUp(FixedPoint.ONE.sub(getSwapFeePercentage()));
}
/**
* @dev Subtracts swap fee amount from `amount`, returning a lower value.
*/
function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) {
// This returns amount - fee amount, so we round up (favoring a higher fee amount).
uint256 feeAmount = amount.mulUp(getSwapFeePercentage());
return amount.sub(feeAmount);
}
// Scaling
/**
* @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if
* it had 18 decimals.
*/
function _computeScalingFactor(IERC20 token) internal view returns (uint256) {
if (address(token) == address(this)) {
return FixedPoint.ONE;
}
// Tokens that don't implement the `decimals` method are not supported.
uint256 tokenDecimals = ERC20(address(token)).decimals();
// Tokens with more than 18 decimals are not supported.
uint256 decimalsDifference = Math.sub(18, tokenDecimals);
return FixedPoint.ONE * 10**decimalsDifference;
}
/**
* @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the
* Pool.
*
* All scaling factors are fixed-point values with 18 decimals, to allow for this function to be overridden by
* derived contracts that need to apply further scaling, making these factors potentially non-integer.
*
* The largest 'base' scaling factor (i.e. in tokens with less than 18 decimals) is 10**18, which in fixed-point is
* 10**36. This value can be multiplied with a 112 bit Vault balance with no overflow by a factor of ~1e7, making
* even relatively 'large' factors safe to use.
*
* The 1e7 figure is the result of 2**256 / (1e18 * 1e18 * 2**112).
*/
function _scalingFactor(IERC20 token) internal view virtual returns (uint256);
/**
* @dev Same as `_scalingFactor()`, except for all registered tokens (in the same order as registered). The Vault
* will always pass balances in this order when calling any of the Pool hooks.
*/
function _scalingFactors() internal view virtual returns (uint256[] memory);
function getScalingFactors() external view returns (uint256[] memory) {
return _scalingFactors();
}
/**
* @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed
* scaling or not.
*/
function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
// Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of
// token in should be rounded up, and that of token out rounded down. This is the only place where we round in
// the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no
// rounding error unless `_scalingFactor()` is overriden).
return FixedPoint.mulDown(amount, scalingFactor);
}
/**
* @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates*
* the `amounts` array.
*/
function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = FixedPoint.mulDown(amounts[i], scalingFactors[i]);
}
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded down.
*/
function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return FixedPoint.divDown(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead
* *mutates* the `amounts` array.
*/
function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = FixedPoint.divDown(amounts[i], scalingFactors[i]);
}
}
/**
* @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on
* whether it needed scaling or not. The result is rounded up.
*/
function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
return FixedPoint.divUp(amount, scalingFactor);
}
/**
* @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead
* *mutates* the `amounts` array.
*/
function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = FixedPoint.divUp(amounts[i], scalingFactors[i]);
}
}
function _getAuthorizer() internal view override returns (IAuthorizer) {
// Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which
// accounts can call permissioned functions: for example, to perform emergency pauses.
// If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under
// Governance control.
return getVault().getAuthorizer();
}
function _queryAction(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData,
function(bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory)
internal
returns (uint256, uint256[] memory, uint256[] memory) _action,
function(uint256[] memory, uint256[] memory) internal view _downscaleArray
) private {
// This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed
// explanation.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the bpt and token amounts from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of the
// `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded
// representation of these.
// An ABI-encoded response will include one additional field to indicate the starting offset of
// the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the
// returndata.
//
// In returndata:
// [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ]
// [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
//
// We now need to return (ABI-encoded values):
// [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ]
// [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ]
// We copy 32 bytes for the `bptAmount` from returndata into memory.
// Note that we skip the first 4 bytes for the error signature
returndatacopy(0, 0x04, 32)
// The offsets are 32-bytes long, so the array of `tokenAmounts` will start after
// the initial 64 bytes.
mstore(0x20, 64)
// We now copy the raw memory array for the `tokenAmounts` from returndata into memory.
// Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also
// skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount.
returndatacopy(0x40, 0x24, sub(returndatasize(), 36))
// We finally return the ABI-encoded uint256 and the array, which has a total length equal to
// the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the
// error signature.
return(0, add(returndatasize(), 28))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
uint256[] memory scalingFactors = _scalingFactors();
_upscaleArray(balances, scalingFactors);
(uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action(
poolId,
sender,
recipient,
balances,
lastChangeBlock,
protocolSwapFeePercentage,
scalingFactors,
userData
);
_downscaleArray(tokenAmounts, scalingFactors);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of
// a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values
// Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32
let size := mul(mload(tokenAmounts), 32)
// We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there
// will be at least one available slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
let start := sub(tokenAmounts, 0x20)
mstore(start, bptAmount)
// We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb
// We use the previous slot to `bptAmount`.
mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb)
start := sub(start, 0x04)
// When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return
// the `bptAmount`, the array 's length, and the error signature.
revert(start, add(size, 68))
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
interface IRateProvider {
/**
* @dev Returns an 18 decimal fixed point number that is the exchange rate of the token to some other underlying
* token. The meaning of this rate depends on the context.
*/
function getRate() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol";
/**
* Price rate caches are used to avoid querying the price rate for a token every time we need to work with it. It is
* useful for slow changing rates, such as those that arise from interest-bearing tokens (e.g. waDAI into DAI).
*
* The cache data is packed into a single bytes32 value with the following structure:
* [ expires | duration | price rate value ]
* [ uint64 | uint64 | uint128 ]
* [ MSB LSB ]
*
*
* 'rate' is an 18 decimal fixed point number, supporting rates of up to ~3e20. 'expires' is a Unix timestamp, and
* 'duration' is expressed in seconds.
*/
library PriceRateCache {
using WordCodec for bytes32;
uint256 private constant _PRICE_RATE_CACHE_VALUE_OFFSET = 0;
uint256 private constant _PRICE_RATE_CACHE_DURATION_OFFSET = 128;
uint256 private constant _PRICE_RATE_CACHE_EXPIRES_OFFSET = 128 + 64;
/**
* @dev Returns the rate of a price rate cache.
*/
function getRate(bytes32 cache) internal pure returns (uint256) {
return cache.decodeUint128(_PRICE_RATE_CACHE_VALUE_OFFSET);
}
/**
* @dev Returns the duration of a price rate cache.
*/
function getDuration(bytes32 cache) internal pure returns (uint256) {
return cache.decodeUint64(_PRICE_RATE_CACHE_DURATION_OFFSET);
}
/**
* @dev Returns the duration and expiration time of a price rate cache.
*/
function getTimestamps(bytes32 cache) internal pure returns (uint256 duration, uint256 expires) {
duration = getDuration(cache);
expires = cache.decodeUint64(_PRICE_RATE_CACHE_EXPIRES_OFFSET);
}
/**
* @dev Encodes rate and duration into a price rate cache. The expiration time is computed automatically, counting
* from the current time.
*/
function encode(uint256 rate, uint256 duration) internal view returns (bytes32) {
_require(rate < 2**128, Errors.PRICE_RATE_OVERFLOW);
// solhint-disable not-rely-on-time
return
WordCodec.encodeUint(uint128(rate), _PRICE_RATE_CACHE_VALUE_OFFSET) |
WordCodec.encodeUint(uint64(duration), _PRICE_RATE_CACHE_DURATION_OFFSET) |
WordCodec.encodeUint(uint64(block.timestamp + duration), _PRICE_RATE_CACHE_EXPIRES_OFFSET);
}
/**
* @dev Returns rate, duration and expiration time of a price rate cache.
*/
function decode(bytes32 cache)
internal
pure
returns (
uint256 rate,
uint256 duration,
uint256 expires
)
{
rate = getRate(cache);
(duration, expires) = getTimestamps(cache);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev IPools with the General specialization setting should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will
* grant to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IGeneralPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
// These functions start with an underscore, as if they were part of a contract and not a library. At some point this
// should be fixed.
// solhint-disable private-vars-leading-underscore
library LinearMath {
using FixedPoint for uint256;
// A thorough derivation of the formulas and derivations found here exceeds the scope of this file, so only
// introductory notions will be presented.
// A Linear Pool holds three tokens: the main token, the wrapped token, and the Pool share token (BPT). It is
// possible to exchange any of these tokens for any of the other two (so we have three trading pairs) in both
// directions (the first token of each pair can be bought or sold for the second) and by specifying either the input
// or output amount (typically referred to as 'given in' or 'given out'). A full description thus requires
// 3*2*2 = 12 functions.
// Wrapped tokens have a known, trusted exchange rate to main tokens. All functions here assume such a rate has
// already been applied, meaning main and wrapped balances can be compared as they are both expressed in the same
// units (those of main token).
// Additionally, Linear Pools feature a lower and upper target that represent the desired range of values for the
// main token balance. Any action that moves the main balance away from this range is charged a proportional fee,
// and any action that moves it towards this range is incentivized by paying the actor using these collected fees.
// The collected fees are not stored in a separate data structure: they are a function of the current main balance,
// targets and fee percentage. The main balance sans fees is known as the 'nominal balance', which is always smaller
// than the real balance except when the real balance is within the targets.
// The rule under which Linear Pools conduct trades between main and wrapped tokens is by keeping the sum of nominal
// main balance and wrapped balance constant: this value is known as the 'invariant'. BPT is backed by nominal
// reserves, meaning its supply is proportional to the invariant. As the wrapped token appreciates in value and its
// exchange rate to the main token increases, so does the invariant and thus the value of BPT (in main token units).
struct Params {
uint256 fee;
uint256 lowerTarget;
uint256 upperTarget;
}
function _calcBptOutPerMainIn(
uint256 mainIn,
uint256 mainBalance,
uint256 wrappedBalance,
uint256 bptSupply,
Params memory params
) internal pure returns (uint256) {
// Amount out, so we round down overall.
if (bptSupply == 0) {
// BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the
// BPT supply is initialized to equal the invariant (which in this case is just the nominal main balance as
// there is no wrapped balance).
return _toNominal(mainIn, params);
}
uint256 previousNominalMain = _toNominal(mainBalance, params);
uint256 afterNominalMain = _toNominal(mainBalance.add(mainIn), params);
uint256 deltaNominalMain = afterNominalMain.sub(previousNominalMain);
uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance);
return Math.divDown(Math.mul(bptSupply, deltaNominalMain), invariant);
}
function _calcBptInPerMainOut(
uint256 mainOut,
uint256 mainBalance,
uint256 wrappedBalance,
uint256 bptSupply,
Params memory params
) internal pure returns (uint256) {
// Amount in, so we round up overall.
uint256 previousNominalMain = _toNominal(mainBalance, params);
uint256 afterNominalMain = _toNominal(mainBalance.sub(mainOut), params);
uint256 deltaNominalMain = previousNominalMain.sub(afterNominalMain);
uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance);
return Math.divUp(Math.mul(bptSupply, deltaNominalMain), invariant);
}
function _calcWrappedOutPerMainIn(
uint256 mainIn,
uint256 mainBalance,
Params memory params
) internal pure returns (uint256) {
// Amount out, so we round down overall.
uint256 previousNominalMain = _toNominal(mainBalance, params);
uint256 afterNominalMain = _toNominal(mainBalance.add(mainIn), params);
return afterNominalMain.sub(previousNominalMain);
}
function _calcWrappedInPerMainOut(
uint256 mainOut,
uint256 mainBalance,
Params memory params
) internal pure returns (uint256) {
// Amount in, so we round up overall.
uint256 previousNominalMain = _toNominal(mainBalance, params);
uint256 afterNominalMain = _toNominal(mainBalance.sub(mainOut), params);
return previousNominalMain.sub(afterNominalMain);
}
function _calcMainInPerBptOut(
uint256 bptOut,
uint256 mainBalance,
uint256 wrappedBalance,
uint256 bptSupply,
Params memory params
) internal pure returns (uint256) {
// Amount in, so we round up overall.
if (bptSupply == 0) {
// BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the
// BPT supply is initialized to equal the invariant (which in this case is just the nominal main balance as
// there is no wrapped balance).
return _fromNominal(bptOut, params);
}
uint256 previousNominalMain = _toNominal(mainBalance, params);
uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance);
uint256 deltaNominalMain = Math.divUp(Math.mul(invariant, bptOut), bptSupply);
uint256 afterNominalMain = previousNominalMain.add(deltaNominalMain);
uint256 newMainBalance = _fromNominal(afterNominalMain, params);
return newMainBalance.sub(mainBalance);
}
function _calcMainOutPerBptIn(
uint256 bptIn,
uint256 mainBalance,
uint256 wrappedBalance,
uint256 bptSupply,
Params memory params
) internal pure returns (uint256) {
// Amount out, so we round down overall.
uint256 previousNominalMain = _toNominal(mainBalance, params);
uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance);
uint256 deltaNominalMain = Math.divDown(Math.mul(invariant, bptIn), bptSupply);
uint256 afterNominalMain = previousNominalMain.sub(deltaNominalMain);
uint256 newMainBalance = _fromNominal(afterNominalMain, params);
return mainBalance.sub(newMainBalance);
}
function _calcMainOutPerWrappedIn(
uint256 wrappedIn,
uint256 mainBalance,
Params memory params
) internal pure returns (uint256) {
// Amount out, so we round down overall.
uint256 previousNominalMain = _toNominal(mainBalance, params);
uint256 afterNominalMain = previousNominalMain.sub(wrappedIn);
uint256 newMainBalance = _fromNominal(afterNominalMain, params);
return mainBalance.sub(newMainBalance);
}
function _calcMainInPerWrappedOut(
uint256 wrappedOut,
uint256 mainBalance,
Params memory params
) internal pure returns (uint256) {
// Amount in, so we round up overall.
uint256 previousNominalMain = _toNominal(mainBalance, params);
uint256 afterNominalMain = previousNominalMain.add(wrappedOut);
uint256 newMainBalance = _fromNominal(afterNominalMain, params);
return newMainBalance.sub(mainBalance);
}
function _calcBptOutPerWrappedIn(
uint256 wrappedIn,
uint256 mainBalance,
uint256 wrappedBalance,
uint256 bptSupply,
Params memory params
) internal pure returns (uint256) {
// Amount out, so we round down overall.
if (bptSupply == 0) {
// BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the
// BPT supply is initialized to equal the invariant (which in this case is just the wrapped balance as
// there is no main balance).
return wrappedIn;
}
uint256 nominalMain = _toNominal(mainBalance, params);
uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance);
uint256 newWrappedBalance = wrappedBalance.add(wrappedIn);
uint256 newInvariant = _calcInvariant(nominalMain, newWrappedBalance);
uint256 newBptBalance = Math.divDown(Math.mul(bptSupply, newInvariant), previousInvariant);
return newBptBalance.sub(bptSupply);
}
function _calcBptInPerWrappedOut(
uint256 wrappedOut,
uint256 mainBalance,
uint256 wrappedBalance,
uint256 bptSupply,
Params memory params
) internal pure returns (uint256) {
// Amount in, so we round up overall.
uint256 nominalMain = _toNominal(mainBalance, params);
uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance);
uint256 newWrappedBalance = wrappedBalance.sub(wrappedOut);
uint256 newInvariant = _calcInvariant(nominalMain, newWrappedBalance);
uint256 newBptBalance = Math.divDown(Math.mul(bptSupply, newInvariant), previousInvariant);
return bptSupply.sub(newBptBalance);
}
function _calcWrappedInPerBptOut(
uint256 bptOut,
uint256 mainBalance,
uint256 wrappedBalance,
uint256 bptSupply,
Params memory params
) internal pure returns (uint256) {
// Amount in, so we round up overall.
if (bptSupply == 0) {
// BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the
// BPT supply is initialized to equal the invariant (which in this case is just the wrapped balance as
// there is no main balance).
return bptOut;
}
uint256 nominalMain = _toNominal(mainBalance, params);
uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance);
uint256 newBptBalance = bptSupply.add(bptOut);
uint256 newWrappedBalance = Math.divUp(Math.mul(newBptBalance, previousInvariant), bptSupply).sub(nominalMain);
return newWrappedBalance.sub(wrappedBalance);
}
function _calcWrappedOutPerBptIn(
uint256 bptIn,
uint256 mainBalance,
uint256 wrappedBalance,
uint256 bptSupply,
Params memory params
) internal pure returns (uint256) {
// Amount out, so we round down overall.
uint256 nominalMain = _toNominal(mainBalance, params);
uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance);
uint256 newBptBalance = bptSupply.sub(bptIn);
uint256 newWrappedBalance = Math.divUp(Math.mul(newBptBalance, previousInvariant), bptSupply).sub(nominalMain);
return wrappedBalance.sub(newWrappedBalance);
}
function _calcInvariant(uint256 nominalMainBalance, uint256 wrappedBalance) internal pure returns (uint256) {
return nominalMainBalance.add(wrappedBalance);
}
function _toNominal(uint256 real, Params memory params) internal pure returns (uint256) {
// Fees are always rounded down: either direction would work but we need to be consistent, and rounding down
// uses less gas.
if (real < params.lowerTarget) {
uint256 fees = (params.lowerTarget - real).mulDown(params.fee);
return real.sub(fees);
} else if (real <= params.upperTarget) {
return real;
} else {
uint256 fees = (real - params.upperTarget).mulDown(params.fee);
return real.sub(fees);
}
}
function _fromNominal(uint256 nominal, Params memory params) internal pure returns (uint256) {
// Since real = nominal + fees, rounding down fees is equivalent to rounding down real.
if (nominal < params.lowerTarget) {
return (nominal.add(params.fee.mulDown(params.lowerTarget))).divDown(FixedPoint.ONE.add(params.fee));
} else if (nominal <= params.upperTarget) {
return nominal;
} else {
return (nominal.sub(params.fee.mulDown(params.upperTarget)).divDown(FixedPoint.ONE.sub(params.fee)));
}
}
function _calcTokensOutGivenExactBptIn(
uint256[] memory balances,
uint256 bptAmountIn,
uint256 bptTotalSupply,
uint256 bptIndex
) internal pure returns (uint256[] memory) {
/**********************************************************************************************
// exactBPTInForTokensOut //
// (per token) //
// aO = tokenAmountOut / bptIn \ //
// b = tokenBalance a0 = b * | --------------------- | //
// bptIn = bptAmountIn \ bptTotalSupply / //
// bpt = bptTotalSupply //
**********************************************************************************************/
// Since we're computing an amount out, we round down overall. This means rounding down on both the
// multiplication and division.
uint256 bptRatio = bptAmountIn.divDown(bptTotalSupply);
uint256[] memory amountsOut = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
// BPT is skipped as those tokens are not the LPs, but rather the preminted and undistributed amount.
if (i != bptIndex) {
amountsOut[i] = balances[i].mulDown(bptRatio);
}
}
return amountsOut;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "./LinearPool.sol";
library LinearPoolUserData {
enum ExitKind { EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT }
function exitKind(bytes memory self) internal pure returns (ExitKind) {
return abi.decode(self, (ExitKind));
}
function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) {
(, bptAmountIn) = abi.decode(self, (ExitKind, uint256));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library.
*/
library Math {
/**
* @dev Returns the absolute value of a signed integer.
*/
function abs(int256 a) internal pure returns (uint256) {
return a > 0 ? uint256(a) : uint256(-a);
}
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting 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), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting 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), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function div(
uint256 a,
uint256 b,
bool roundUp
) internal pure returns (uint256) {
return roundUp ? divUp(a, b) : divDown(a, b);
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "./BalancerErrors.sol";
import "./ITemporarilyPausable.sol";
/**
* @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be
* used as an emergency switch in case a security vulnerability or threat is identified.
*
* The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be
* unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets
* system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful
* analysis later determines there was a false alarm.
*
* If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional
* Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time
* to react to an emergency, even if the threat is discovered shortly before the Pause Window expires.
*
* Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is
* irreversible.
*/
abstract contract TemporarilyPausable is ITemporarilyPausable {
// The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days;
uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days;
uint256 private immutable _pauseWindowEndTime;
uint256 private immutable _bufferPeriodEndTime;
bool private _paused;
constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) {
_require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION);
_require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION);
uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration;
_pauseWindowEndTime = pauseWindowEndTime;
_bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration;
}
/**
* @dev Reverts if the contract is paused.
*/
modifier whenNotPaused() {
_ensureNotPaused();
_;
}
/**
* @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer
* Period.
*/
function getPausedState()
external
view
override
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
)
{
paused = !_isNotPaused();
pauseWindowEndTime = _getPauseWindowEndTime();
bufferPeriodEndTime = _getBufferPeriodEndTime();
}
/**
* @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and
* unpaused until the end of the Buffer Period.
*
* Once the Buffer Period expires, this function reverts unconditionally.
*/
function _setPaused(bool paused) internal {
if (paused) {
_require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED);
} else {
_require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED);
}
_paused = paused;
emit PausedStateChanged(paused);
}
/**
* @dev Reverts if the contract is paused.
*/
function _ensureNotPaused() internal view {
_require(_isNotPaused(), Errors.PAUSED);
}
/**
* @dev Reverts if the contract is not paused.
*/
function _ensurePaused() internal view {
_require(!_isNotPaused(), Errors.NOT_PAUSED);
}
/**
* @dev Returns true if the contract is unpaused.
*
* Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no
* longer accessed.
*/
function _isNotPaused() internal view returns (bool) {
// After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access.
return block.timestamp > _getBufferPeriodEndTime() || !_paused;
}
// These getters lead to reduced bytecode size by inlining the immutable variables in a single place.
function _getPauseWindowEndTime() private view returns (uint256) {
return _pauseWindowEndTime;
}
function _getBufferPeriodEndTime() private view returns (uint256) {
return _bufferPeriodEndTime;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in
* a single storage slot, saving gas by performing less storage accesses.
*
* Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two
* 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128.
*
* We could use Solidity structs to pack values together in a single storage slot instead of relying on a custom and
* error-prone library, but unfortunately Solidity only allows for structs to live in either storage, calldata or
* memory. Because a memory struct uses not just memory but also a slot in the stack (to store its memory location),
* using memory for word-sized values (i.e. of 256 bits or less) is strictly less gas performant, and doesn't even
* prevent stack-too-deep issues. This is compounded by the fact that Balancer contracts typically are memory-intensive,
* and the cost of accesing memory increases quadratically with the number of allocated words. Manual packing and
* unpacking is therefore the preferred approach.
*/
library WordCodec {
// Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word,
// or to insert a new one replacing the old.
uint256 private constant _MASK_1 = 2**(1) - 1;
uint256 private constant _MASK_5 = 2**(5) - 1;
uint256 private constant _MASK_7 = 2**(7) - 1;
uint256 private constant _MASK_10 = 2**(10) - 1;
uint256 private constant _MASK_16 = 2**(16) - 1;
uint256 private constant _MASK_22 = 2**(22) - 1;
uint256 private constant _MASK_31 = 2**(31) - 1;
uint256 private constant _MASK_32 = 2**(32) - 1;
uint256 private constant _MASK_53 = 2**(53) - 1;
uint256 private constant _MASK_64 = 2**(64) - 1;
uint256 private constant _MASK_96 = 2**(96) - 1;
uint256 private constant _MASK_128 = 2**(128) - 1;
uint256 private constant _MASK_192 = 2**(192) - 1;
// Largest positive values that can be represented as N bits signed integers.
int256 private constant _MAX_INT_22 = 2**(21) - 1;
int256 private constant _MAX_INT_53 = 2**(52) - 1;
// In-place insertion
/**
* @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new
* word.
*/
function insertBool(
bytes32 word,
bool value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset));
return clearedWord | bytes32(uint256(value ? 1 : 0) << offset);
}
// Unsigned
/**
* @dev Inserts a 5 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 5 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint5(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_5 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 7 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 7 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint7(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_7 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 10 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint10(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 16 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value.
* Returns the new word.
*
* Assumes `value` only uses its least significant 16 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint16(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_16 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 31 bits.
*/
function insertUint31(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 32 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 32 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint32(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_32 << offset));
return clearedWord | bytes32(value << offset);
}
/**
* @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` only uses its least significant 64 bits, otherwise it may overwrite sibling bytes.
*/
function insertUint64(
bytes32 word,
uint256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset));
return clearedWord | bytes32(value << offset);
}
// Signed
/**
* @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns
* the new word.
*
* Assumes `value` can be represented using 22 bits.
*/
function insertInt22(
bytes32 word,
int256 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset));
// Integer values need masking to remove the upper bits of negative values.
return clearedWord | bytes32((uint256(value) & _MASK_22) << offset);
}
// Bytes
/**
* @dev Inserts 192 bit shifted by an offset into a 256 bit word, replacing the old value. Returns the new word.
*
* Assumes `value` can be represented using 192 bits.
*/
function insertBits192(
bytes32 word,
bytes32 value,
uint256 offset
) internal pure returns (bytes32) {
bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_192 << offset));
return clearedWord | bytes32((uint256(value) & _MASK_192) << offset);
}
// Encoding
// Unsigned
/**
* @dev Encodes an unsigned integer shifted by an offset. This performs no size checks: it is up to the caller to
* ensure that the values are bounded.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeUint(uint256 value, uint256 offset) internal pure returns (bytes32) {
return bytes32(value << offset);
}
// Signed
/**
* @dev Encodes a 22 bits signed integer shifted by an offset.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_22) << offset);
}
/**
* @dev Encodes a 53 bits signed integer shifted by an offset.
*
* The return value can be logically ORed with other encoded values to form a 256 bit word.
*/
function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_53) << offset);
}
// Decoding
/**
* @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.
*/
function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) {
return (uint256(word >> offset) & _MASK_1) == 1;
}
// Unsigned
/**
* @dev Decodes and returns a 5 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint5(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_5;
}
/**
* @dev Decodes and returns a 7 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint7(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_7;
}
/**
* @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_10;
}
/**
* @dev Decodes and returns a 16 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint16(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_16;
}
/**
* @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_31;
}
/**
* @dev Decodes and returns a 32 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint32(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_32;
}
/**
* @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_64;
}
/**
* @dev Decodes and returns a 96 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint96(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_96;
}
/**
* @dev Decodes and returns a 128 bit unsigned integer shifted by an offset from a 256 bit word.
*/
function decodeUint128(bytes32 word, uint256 offset) internal pure returns (uint256) {
return uint256(word >> offset) & _MASK_128;
}
// Signed
/**
* @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word.
*/
function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) {
int256 value = int256(uint256(word >> offset) & _MASK_22);
// In case the decoded value is greater than the max positive integer that can be represented with 22 bits,
// we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
// representation.
return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value;
}
/**
* @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word.
*/
function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) {
int256 value = int256(uint256(word >> offset) & _MASK_53);
// In case the decoded value is greater than the max positive integer that can be represented with 53 bits,
// we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
// representation.
return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.sol";
import "./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 IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, 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(msg.sender, 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,
msg.sender,
_allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_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(msg.sender, spender, _allowances[msg.sender][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(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(subtractedValue, Errors.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), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS);
_require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_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 {
_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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS);
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_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 {
_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: GPL-3.0-or-later
// 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 experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "./IProtocolFeesCollector.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (IProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `balances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `balances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
function getPoolId() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
interface IAssetManager {
/**
* @notice Emitted when asset manager is rebalanced
*/
event Rebalance(bytes32 poolId);
/**
* @notice Sets the config
*/
function setConfig(bytes32 poolId, bytes calldata config) external;
/**
* Note: No function to read the asset manager config is included in IAssetManager
* as the signature is expected to vary between asset manager implementations
*/
/**
* @notice Returns the asset manager's token
*/
function getToken() external view returns (IERC20);
/**
* @return the current assets under management of this asset manager
*/
function getAUM(bytes32 poolId) external view returns (uint256);
/**
* @return poolCash - The up-to-date cash balance of the pool
* @return poolManaged - The up-to-date managed balance of the pool
*/
function getPoolBalances(bytes32 poolId) external view returns (uint256 poolCash, uint256 poolManaged);
/**
* @return The difference in tokens between the target investment
* and the currently invested amount (i.e. the amount that can be invested)
*/
function maxInvestableBalance(bytes32 poolId) external view returns (int256);
/**
* @notice Updates the Vault on the value of the pool's investment returns
*/
function updateBalanceOfPool(bytes32 poolId) external;
/**
* @notice Determines whether the pool should rebalance given the provided balances
*/
function shouldRebalance(uint256 cash, uint256 managed) external view returns (bool);
/**
* @notice Rebalances funds between the pool and the asset manager to maintain target investment percentage.
* @param poolId - the poolId of the pool to be rebalanced
* @param force - a boolean representing whether a rebalance should be forced even when the pool is near balance
*/
function rebalance(bytes32 poolId, bool force) external;
/**
* @notice allows an authorized rebalancer to remove capital to facilitate large withdrawals
* @param poolId - the poolId of the pool to withdraw funds back to
* @param amount - the amount of tokens to withdraw back to the pool
*/
function capitalOut(bytes32 poolId, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20Permit.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
/**
* @title Highly opinionated token implementation
* @author Balancer Labs
* @dev
* - Includes functions to increase and decrease allowance as a workaround
* for the well-known issue with `approve`:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* - Allows for 'infinite allowance', where an allowance of 0xff..ff is not
* decreased by calls to transferFrom
* - Lets a token holder use `transferFrom` to send their own tokens,
* without first setting allowance
* - Emits 'Approval' events whenever allowance is changed by `transferFrom`
* - Assigns infinite allowance for all token holders to the Vault
*/
contract BalancerPoolToken is ERC20Permit {
IVault private immutable _vault;
constructor(
string memory tokenName,
string memory tokenSymbol,
IVault vault
) ERC20(tokenName, tokenSymbol) ERC20Permit(tokenName) {
_vault = vault;
}
function getVault() public view returns (IVault) {
return _vault;
}
// Overrides
/**
* @dev Override to grant the Vault infinite allowance, causing for Pool Tokens to not require approval.
*
* This is sound as the Vault already provides authorization mechanisms when initiation token transfers, which this
* contract inherits.
*/
function allowance(address owner, address spender) public view override returns (uint256) {
if (spender == address(getVault())) {
return uint256(-1);
} else {
return super.allowance(owner, spender);
}
}
/**
* @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
uint256 currentAllowance = allowance(sender, msg.sender);
_require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE);
_transfer(sender, recipient, amount);
if (msg.sender != sender && currentAllowance != uint256(-1)) {
// Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* @dev Override to allow decreasing allowance by more than the current amount (setting it to zero)
*/
function decreaseAllowance(address spender, uint256 amount) public override returns (bool) {
uint256 currentAllowance = allowance(msg.sender, spender);
if (amount >= currentAllowance) {
_approve(msg.sender, spender, 0);
} else {
// No risk of underflow due to if condition
_approve(msg.sender, spender, currentAllowance - amount);
}
return true;
}
// Internal functions
function _mintPoolTokens(address recipient, uint256 amount) internal {
_mint(recipient, amount);
}
function _burnPoolTokens(address sender, uint256 amount) internal {
_burn(sender, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IAuthorizer.sol";
/**
* @dev Base authorization layer implementation for Pools.
*
* The owner account can call some of the permissioned functions - access control of the rest is delegated to the
* Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership,
* granular roles, etc., could be built on top of this by making the owner a smart contract.
*
* Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate
* control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`.
*/
abstract contract BasePoolAuthorization is Authentication {
address private immutable _owner;
address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B;
constructor(address owner) {
_owner = owner;
}
function getOwner() public view returns (address) {
return _owner;
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) {
// Only the owner can perform "owner only" actions, unless the owner is delegated.
return msg.sender == getOwner();
} else {
// Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated.
return _getAuthorizer().canPerform(actionId, account, address(this));
}
}
function _isOwnerOnlyAction(bytes32 actionId) internal view virtual returns (bool);
function _getAuthorizer() internal view virtual returns (IAuthorizer);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) {
_require(b <= a, errorCode);
uint256 c = a - b;
return c;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../openzeppelin/IERC20.sol";
/**
* @dev Interface for WETH9.
* See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "./IVault.sol";
import "./IAuthorizer.sol";
interface IProtocolFeesCollector {
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external;
function setSwapFeePercentage(uint256 newSwapFeePercentage) external;
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external;
function getSwapFeePercentage() external view returns (uint256);
function getFlashLoanFeePercentage() external view returns (uint256);
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts);
function getAuthorizer() external view returns (IAuthorizer);
function vault() external view returns (IVault);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ERC20.sol";
import "./IERC20Permit.sol";
import "./EIP712.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
mapping(address => uint256) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT);
uint256 nonce = _nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, nonce, deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ecrecover(hash, v, r, s);
_require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE);
_nonces[owner] = nonce + 1;
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner];
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/helpers/BaseSplitCodeFactory.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
/**
* @dev Same as `BasePoolFactory`, for Pools whose creation code is so large that the factory cannot hold it.
*/
abstract contract BasePoolSplitCodeFactory is BaseSplitCodeFactory {
IVault private immutable _vault;
mapping(address => bool) private _isPoolFromFactory;
event PoolCreated(address indexed pool);
constructor(IVault vault, bytes memory creationCode) BaseSplitCodeFactory(creationCode) {
_vault = vault;
}
/**
* @dev Returns the Vault's address.
*/
function getVault() public view returns (IVault) {
return _vault;
}
/**
* @dev Returns true if `pool` was created by this factory.
*/
function isPoolFromFactory(address pool) external view returns (bool) {
return _isPoolFromFactory[pool];
}
function _create(bytes memory constructorArgs) internal override returns (address) {
address pool = super._create(constructorArgs);
_isPoolFromFactory[pool] = true;
emit PoolCreated(pool);
return pool;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
/**
* @dev Utility to create Pool factories for Pools that use the `TemporarilyPausable` contract.
*
* By calling `TemporarilyPausable`'s constructor with the result of `getPauseConfiguration`, all Pools created by this
* factory will share the same Pause Window end time, after which both old and new Pools will not be pausable.
*/
contract FactoryWidePauseWindow {
// This contract relies on timestamps in a similar way as `TemporarilyPausable` does - the same caveats apply.
// solhint-disable not-rely-on-time
uint256 private constant _INITIAL_PAUSE_WINDOW_DURATION = 90 days;
uint256 private constant _BUFFER_PERIOD_DURATION = 30 days;
// Time when the pause window for all created Pools expires, and the pause window duration of new Pools becomes
// zero.
uint256 private immutable _poolsPauseWindowEndTime;
constructor() {
_poolsPauseWindowEndTime = block.timestamp + _INITIAL_PAUSE_WINDOW_DURATION;
}
/**
* @dev Returns the current `TemporarilyPausable` configuration that will be applied to Pools created by this
* factory.
*
* `pauseWindowDuration` will decrease over time until it reaches zero, at which point both it and
* `bufferPeriodDuration` will be zero forever, meaning deployed Pools will not be pausable.
*/
function getPauseConfiguration() public view returns (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) {
uint256 currentTime = block.timestamp;
if (currentTime < _poolsPauseWindowEndTime) {
// The buffer period is always the same since its duration is related to how much time is needed to respond
// to a potential emergency. The Pause Window duration however decreases as the end time approaches.
pauseWindowDuration = _poolsPauseWindowEndTime - currentTime; // No need for checked arithmetic.
bufferPeriodDuration = _BUFFER_PERIOD_DURATION;
} else {
// After the end time, newly created Pools have no Pause Window, nor Buffer Period (since they are not
// pausable in the first place).
pauseWindowDuration = 0;
bufferPeriodDuration = 0;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "./BalancerErrors.sol";
import "./CodeDeployer.sol";
/**
* @dev Base factory for contracts whose creation code is so large that the factory cannot hold it. This happens when
* the contract's creation code grows close to 24kB.
*
* Note that this factory cannot help with contracts that have a *runtime* (deployed) bytecode larger than 24kB.
*/
abstract contract BaseSplitCodeFactory {
// The contract's creation code is stored as code in two separate addresses, and retrieved via `extcodecopy`. This
// means this factory supports contracts with creation code of up to 48kB.
// We rely on inline-assembly to achieve this, both to make the entire operation highly gas efficient, and because
// `extcodecopy` is not available in Solidity.
// solhint-disable no-inline-assembly
address private immutable _creationCodeContractA;
uint256 private immutable _creationCodeSizeA;
address private immutable _creationCodeContractB;
uint256 private immutable _creationCodeSizeB;
/**
* @dev The creation code of a contract Foo can be obtained inside Solidity with `type(Foo).creationCode`.
*/
constructor(bytes memory creationCode) {
uint256 creationCodeSize = creationCode.length;
// We are going to deploy two contracts: one with approximately the first half of `creationCode`'s contents
// (A), and another with the remaining half (B).
// We store the lengths in both immutable and stack variables, since immutable variables cannot be read during
// construction.
uint256 creationCodeSizeA = creationCodeSize / 2;
_creationCodeSizeA = creationCodeSizeA;
uint256 creationCodeSizeB = creationCodeSize - creationCodeSizeA;
_creationCodeSizeB = creationCodeSizeB;
// To deploy the contracts, we're going to use `CodeDeployer.deploy()`, which expects a memory array with
// the code to deploy. Note that we cannot simply create arrays for A and B's code by copying or moving
// `creationCode`'s contents as they are expected to be very large (> 24kB), so we must operate in-place.
// Memory: [ code length ] [ A.data ] [ B.data ]
// Creating A's array is simple: we simply replace `creationCode`'s length with A's length. We'll later restore
// the original length.
bytes memory creationCodeA;
assembly {
creationCodeA := creationCode
mstore(creationCodeA, creationCodeSizeA)
}
// Memory: [ A.length ] [ A.data ] [ B.data ]
// ^ creationCodeA
_creationCodeContractA = CodeDeployer.deploy(creationCodeA);
// Creating B's array is a bit more involved: since we cannot move B's contents, we are going to create a 'new'
// memory array starting at A's last 32 bytes, which will be replaced with B's length. We'll back-up this last
// byte to later restore it.
bytes memory creationCodeB;
bytes32 lastByteA;
assembly {
// `creationCode` points to the array's length, not data, so by adding A's length to it we arrive at A's
// last 32 bytes.
creationCodeB := add(creationCode, creationCodeSizeA)
lastByteA := mload(creationCodeB)
mstore(creationCodeB, creationCodeSizeB)
}
// Memory: [ A.length ] [ A.data[ : -1] ] [ B.length ][ B.data ]
// ^ creationCodeA ^ creationCodeB
_creationCodeContractB = CodeDeployer.deploy(creationCodeB);
// We now restore the original contents of `creationCode` by writing back the original length and A's last byte.
assembly {
mstore(creationCodeA, creationCodeSize)
mstore(creationCodeB, lastByteA)
}
}
/**
* @dev Returns the two addresses where the creation code of the contract crated by this factory is stored.
*/
function getCreationCodeContracts() public view returns (address contractA, address contractB) {
return (_creationCodeContractA, _creationCodeContractB);
}
/**
* @dev Returns the creation code of the contract this factory creates.
*/
function getCreationCode() public view returns (bytes memory) {
return _getCreationCodeWithArgs("");
}
/**
* @dev Returns the creation code that will result in a contract being deployed with `constructorArgs`.
*/
function _getCreationCodeWithArgs(bytes memory constructorArgs) private view returns (bytes memory code) {
// This function exists because `abi.encode()` cannot be instructed to place its result at a specific address.
// We need for the ABI-encoded constructor arguments to be located immediately after the creation code, but
// cannot rely on `abi.encodePacked()` to perform concatenation as that would involve copying the creation code,
// which would be prohibitively expensive.
// Instead, we compute the creation code in a pre-allocated array that is large enough to hold *both* the
// creation code and the constructor arguments, and then copy the ABI-encoded arguments (which should not be
// overly long) right after the end of the creation code.
// Immutable variables cannot be used in assembly, so we store them in the stack first.
address creationCodeContractA = _creationCodeContractA;
uint256 creationCodeSizeA = _creationCodeSizeA;
address creationCodeContractB = _creationCodeContractB;
uint256 creationCodeSizeB = _creationCodeSizeB;
uint256 creationCodeSize = creationCodeSizeA + creationCodeSizeB;
uint256 constructorArgsSize = constructorArgs.length;
uint256 codeSize = creationCodeSize + constructorArgsSize;
assembly {
// First, we allocate memory for `code` by retrieving the free memory pointer and then moving it ahead of
// `code` by the size of the creation code plus constructor arguments, and 32 bytes for the array length.
code := mload(0x40)
mstore(0x40, add(code, add(codeSize, 32)))
// We now store the length of the code plus constructor arguments.
mstore(code, codeSize)
// Next, we concatenate the creation code stored in A and B.
let dataStart := add(code, 32)
extcodecopy(creationCodeContractA, dataStart, 0, creationCodeSizeA)
extcodecopy(creationCodeContractB, add(dataStart, creationCodeSizeA), 0, creationCodeSizeB)
}
// Finally, we copy the constructorArgs to the end of the array. Unfortunately there is no way to avoid this
// copy, as it is not possible to tell Solidity where to store the result of `abi.encode()`.
uint256 constructorArgsDataPtr;
uint256 constructorArgsCodeDataPtr;
assembly {
constructorArgsDataPtr := add(constructorArgs, 32)
constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize)
}
_memcpy(constructorArgsCodeDataPtr, constructorArgsDataPtr, constructorArgsSize);
}
/**
* @dev Deploys a contract with constructor arguments. To create `constructorArgs`, call `abi.encode()` with the
* contract's constructor arguments, in order.
*/
function _create(bytes memory constructorArgs) internal virtual returns (address) {
bytes memory creationCode = _getCreationCodeWithArgs(constructorArgs);
address destination;
assembly {
destination := create(0, add(creationCode, 32), mload(creationCode))
}
if (destination == address(0)) {
// Bubble up inner revert reason
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
return destination;
}
// From
// https://github.com/Arachnid/solidity-stringutils/blob/b9a6f6615cf18a87a823cbc461ce9e140a61c305/src/strings.sol
function _memcpy(
uint256 dest,
uint256 src,
uint256 len
) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint256 mask = 256**(32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "./BalancerErrors.sol";
/**
* @dev Library used to deploy contracts with specific code. This can be used for long-term storage of immutable data as
* contract code, which can be retrieved via the `extcodecopy` opcode.
*/
library CodeDeployer {
// During contract construction, the full code supplied exists as code, and can be accessed via `codesize` and
// `codecopy`. This is not the contract's final code however: whatever the constructor returns is what will be
// stored as its code.
//
// We use this mechanism to have a simple constructor that stores whatever is appended to it. The following opcode
// sequence corresponds to the creation code of the following equivalent Solidity contract, plus padding to make the
// full code 32 bytes long:
//
// contract CodeDeployer {
// constructor() payable {
// uint256 size;
// assembly {
// size := sub(codesize(), 32) // size of appended data, as constructor is 32 bytes long
// codecopy(0, 32, size) // copy all appended data to memory at position 0
// return(0, size) // return appended data for it to be stored as code
// }
// }
// }
//
// More specifically, it is composed of the following opcodes (plus padding):
//
// [1] PUSH1 0x20
// [2] CODESIZE
// [3] SUB
// [4] DUP1
// [6] PUSH1 0x20
// [8] PUSH1 0x00
// [9] CODECOPY
// [11] PUSH1 0x00
// [12] RETURN
//
// The padding is just the 0xfe sequence (invalid opcode). It is important as it lets us work in-place, avoiding
// memory allocation and copying.
bytes32
private constant _DEPLOYER_CREATION_CODE = 0x602038038060206000396000f3fefefefefefefefefefefefefefefefefefefe;
/**
* @dev Deploys a contract with `code` as its code, returning the destination address.
*
* Reverts if deployment fails.
*/
function deploy(bytes memory code) internal returns (address destination) {
bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE;
// We need to concatenate the deployer creation code and `code` in memory, but want to avoid copying all of
// `code` (which could be quite long) into a new memory location. Therefore, we operate in-place using
// assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
let codeLength := mload(code)
// `code` is composed of length and data. We've already stored its length in `codeLength`, so we simply
// replace it with the deployer creation code (which is exactly 32 bytes long).
mstore(code, deployerCreationCode)
// At this point, `code` now points to the deployer creation code immediately followed by `code`'s data
// contents. This is exactly what the deployer expects to receive when created.
destination := create(0, code, add(codeLength, 32))
// Finally, we restore the original length in order to not mutate `code`.
mstore(code, codeLength)
}
// The create opcode returns the zero address when contract creation fails, so we revert if this happens.
_require(destination != address(0), Errors.CODE_DEPLOYMENT_FAILED);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-pool-utils/contracts/factories/BasePoolSplitCodeFactory.sol";
import "@balancer-labs/v2-pool-utils/contracts/factories/FactoryWidePauseWindow.sol";
import "./ERC4626LinearPool.sol";
contract ERC4626LinearPoolFactory is BasePoolSplitCodeFactory, FactoryWidePauseWindow {
constructor(IVault vault) BasePoolSplitCodeFactory(vault, type(ERC4626LinearPool).creationCode) {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Deploys a new `ERC4626LinearPool`.
*/
function create(
string memory name,
string memory symbol,
IERC20 mainToken,
IERC4626 wrappedToken,
uint256 upperTarget,
uint256 swapFeePercentage,
address owner
) external returns (LinearPool) {
(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration();
LinearPool pool = ERC4626LinearPool(
_create(
abi.encode(
getVault(),
name,
symbol,
mainToken,
wrappedToken,
upperTarget,
swapFeePercentage,
pauseWindowDuration,
bufferPeriodDuration,
owner
)
)
);
// LinearPools have a separate post-construction initialization step: we perform it here to
// ensure deployment and initialization are atomic.
pool.initialize();
return pool;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import "@balancer-labs/v2-solidity-utils/contracts/misc/IERC4626.sol";
import "../LinearPool.sol";
contract ERC4626LinearPool is LinearPool {
using Math for uint256;
uint256 private immutable _rateScaleFactor;
constructor(
IVault vault,
string memory name,
string memory symbol,
IERC20 mainToken,
IERC4626 wrappedToken,
uint256 upperTarget,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
LinearPool(
vault,
name,
symbol,
mainToken,
wrappedToken,
upperTarget,
swapFeePercentage,
pauseWindowDuration,
bufferPeriodDuration,
owner
)
{
// We do NOT enforce mainToken == wrappedToken.asset() even
// though this is the expected behavior in most cases. Instead,
// we assume a 1:1 relationship between mainToken and
// wrappedToken.asset(), but they do not have to be the same
// token. It is vitally important that this 1:1 relationship is
// respected, or the pool will not function as intended.
//
// This allows for use cases where the wrappedToken is
// double-wrapped into an ERC-4626 token. For example, consider
// a linear pool whose goal is to pair DAI with aDAI. Because
// aDAI is a rebasing token, it needs to be wrapped, and let's
// say an ERC-4626 wrapper is chosen for compatibility with this
// linear pool. Then wrappedToken.asset() will return aDAI,
// whereas mainToken is DAI. But the 1:1 relationship holds, and
// the pool is still valid.
// _getWrappedTokenRate is scaled e18, so we may need to scale IERC4626.convertToAssets()
uint256 wrappedTokenDecimals = ERC20(address(wrappedToken)).decimals();
uint256 mainTokenDecimals = ERC20(address(mainToken)).decimals();
// This is always positive because we only accept tokens with <= 18 decimals
uint256 digitsDifference = Math.add(18, wrappedTokenDecimals).sub(mainTokenDecimals);
_rateScaleFactor = 10**digitsDifference;
}
function _getWrappedTokenRate() internal view override returns (uint256) {
IERC4626 wrappedToken = IERC4626(getWrappedToken());
// Main tokens per 1e18 wrapped token wei
// decimals: main + (18 - wrapped)
uint256 assetsPerShare = wrappedToken.convertToAssets(FixedPoint.ONE);
// This function returns a 18 decimal fixed point number
// assetsPerShare decimals: 18 + main - wrapped
// _rateScaleFactor decimals: 18 - main + wrapped
uint256 rate = assetsPerShare.mul(_rateScaleFactor).divDown(FixedPoint.ONE);
return rate;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../openzeppelin/IERC20.sol";
interface IERC4626 is IERC20 {
/**
* @dev `caller` has exchanged `assets` for `shares`, and transferred those `shares` to `owner`.
*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
/**
* @dev `caller` has exchanged `shares`, owned by `owner`, for `assets`,
* and transferred those `assets` to `receiver`.
*/
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Mints `shares` Vault shares to `receiver` by depositing exactly `amount` of underlying tokens.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `receiver`.
*/
function redeem(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
/**
* @dev The address of the underlying token that the Vault uses for accounting, depositing, and withdrawing.
*/
function asset() external view returns (address);
/**
* @dev Total amount of the underlying asset that is “managed” by Vault.
*/
function totalAssets() external view returns (uint256);
/**
* @dev The amount of `assets` that the Vault would exchange for the amount
* of `shares` provided, in an ideal scenario where all the conditions are met.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev The amount of `shares` that the Vault would exchange for the amount
* of `assets` provided, in an ideal scenario where all the conditions are met.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
} | Returns the number of tokens in circulation. In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it./ We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has 18 decimals), but we do it for completeness. | function getVirtualSupply() external view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this));
return _getVirtualSupply(bptBalance);
}
| 9,951,926 |
./partial_match/1/0x2476eC85e55625Eb658CAFAFe5fdc0FAE2954C85/sources/Strategy.sol | approve unirouter to use dai | function _swap(uint _amountIn) internal {
address[] memory path = new address[](2);
path[0] = address(dai);
path[1] = address(want);
Uni(unirouter).swapExactTokensForTokens(_amountIn, 0, path, address(this), now.add(1 days));
}
| 16,043,946 |
./partial_match/1/0x116D7FE7c69d2E1eb8Eaa326df299DA360C47D13/sources/CotiTest.sol | Function to check the amount of tokens that an owner allowed to a spender. _owner address The address which owns the funds. _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];
}
| 2,728,168 |
./full_match/1/0x408867120EF9E352e470335aF79B2591f66e43cb/sources/browser/asset.sol | Arrays are prefixed by a 256 bit length parameter Read the bytes32 from array memory | function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
index += 32;
assembly {
result := mload(add(b, index))
}
return result;
}
| 16,600,480 |
./full_match/4/0xC4E7D388C1Ba2694545a41f7447f62c87e478DA5/sources/contracts/LazyMinting2.sol | @inheritdoc ILazyMinting/ | function getOwner() external view override returns (address owner) {
owner = _owner;
}
| 13,314,087 |
//Address: 0xa76ea481aebdd5703e476cfcb2315d4e014232c1
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 2/27/2018
//Transacion Count: 4345
// CODE STARTS HERE
pragma solidity ^0.4.17;
contract J8TTokenConfig {
// The J8T decimals
uint8 public constant TOKEN_DECIMALS = 8;
// The J8T decimal factor to obtain luckys
uint256 public constant J8T_DECIMALS_FACTOR = 10**uint256(TOKEN_DECIMALS);
}
/**
* @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() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title 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)) 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));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken 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 {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
//////////////////////////////////////////////////////////////////////
// @title J8T Token //
// @dev ERC20 J8T Token //
// //
// J8T Tokens are divisible by 1e8 (100,000,000) base //
// //
// J8T are displayed using 8 decimal places of precision. //
// //
// 1 J8T is equivalent to 100000000 luckys: //
// 100000000 == 1 * 10**8 == 1e8 == One Hundred Million luckys //
// //
// 1,5 Billion J8T (total supply) is equivalent to: //
// 150000000000000000 == 1500000000 * 10**8 == 1,5e17 luckys //
// //
//////////////////////////////////////////////////////////////////////
contract J8TToken is J8TTokenConfig, BurnableToken, Ownable {
string public constant name = "J8T Token";
string public constant symbol = "J8T";
uint256 public constant decimals = TOKEN_DECIMALS;
uint256 public constant INITIAL_SUPPLY = 1500000000 * (10 ** uint256(decimals));
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function J8TToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
//https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
//EIP 20: A token contract which creates new tokens SHOULD trigger a
//Transfer event with the _from address set to 0x0
//when tokens are created.
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
contract ACLManaged is Ownable {
///////////////////////////
// ACLManaged PROPERTIES //
///////////////////////////
// The operational acl address
address public opsAddress;
// The admin acl address
address public adminAddress;
////////////////////////////////////////
// ACLManaged FUNCTIONS and MODIFIERS //
////////////////////////////////////////
function ACLManaged() public Ownable() {}
// Updates the opsAddress propety with the new _opsAddress value
function setOpsAddress(address _opsAddress) external onlyOwner returns (bool) {
require(_opsAddress != address(0));
require(_opsAddress != address(this));
opsAddress = _opsAddress;
return true;
}
// Updates the adminAddress propety with the new _adminAddress value
function setAdminAddress(address _adminAddress) external onlyOwner returns (bool) {
require(_adminAddress != address(0));
require(_adminAddress != address(this));
adminAddress = _adminAddress;
return true;
}
//Checks if an address is owner
function isOwner(address _address) public view returns (bool) {
bool result = (_address == owner);
return result;
}
//Checks if an address is operator
function isOps(address _address) public view returns (bool) {
bool result = (_address == opsAddress);
return result;
}
//Checks if an address is ops or admin
function isOpsOrAdmin(address _address) public view returns (bool) {
bool result = (_address == opsAddress || _address == adminAddress);
return result;
}
//Checks if an address is ops,owner or admin
function isOwnerOrOpsOrAdmin(address _address) public view returns (bool) {
bool result = (_address == opsAddress || _address == adminAddress || _address == owner);
return result;
}
//Checks whether the msg.sender address is equal to the adminAddress property or not
modifier onlyAdmin() {
//Needs to be set. Default constructor will set 0x0;
address _address = msg.sender;
require(_address != address(0));
require(_address == adminAddress);
_;
}
// Checks whether the msg.sender address is equal to the opsAddress property or not
modifier onlyOps() {
//Needs to be set. Default constructor will set 0x0;
address _address = msg.sender;
require(_address != address(0));
require(_address == opsAddress);
_;
}
// Checks whether the msg.sender address is equal to the opsAddress or adminAddress property
modifier onlyAdminAndOps() {
//Needs to be set. Default constructor will set 0x0;
address _address = msg.sender;
require(_address != address(0));
require(_address == opsAddress || _address == adminAddress);
_;
}
}
contract CrowdsaleConfig is J8TTokenConfig {
using SafeMath for uint256;
// Default start token sale date is 28th February 15:00 SGP 2018
uint256 public constant START_TIMESTAMP = 1519801200;
// Default end token sale date is 14th March 15:00 SGP 2018
uint256 public constant END_TIMESTAMP = 1521010800;
// The ETH decimal factor to obtain weis
uint256 public constant ETH_DECIMALS_FACTOR = 10**uint256(18);
// The token sale supply
uint256 public constant TOKEN_SALE_SUPPLY = 450000000 * J8T_DECIMALS_FACTOR;
// The minimum contribution amount in weis
uint256 public constant MIN_CONTRIBUTION_WEIS = 0.1 ether;
// The maximum contribution amount in weis
uint256 public constant MAX_CONTRIBUTION_WEIS = 10 ether;
//@WARNING: WORKING WITH KILO-MULTIPLES TO AVOID IMPOSSIBLE DIVISIONS OF FLOATING POINTS.
uint256 constant dollar_per_kilo_token = 100; //0.1 dollar per token
uint256 public constant dollars_per_kilo_ether = 900000; //900$ per ether
//TOKENS_PER_ETHER = dollars_per_ether / dollar_per_token
uint256 public constant INITIAL_TOKENS_PER_ETHER = dollars_per_kilo_ether.div(dollar_per_kilo_token);
}
contract Ledger is ACLManaged {
using SafeMath for uint256;
///////////////////////
// Ledger PROPERTIES //
///////////////////////
// The Allocation struct represents a token sale purchase
// amountGranted is the amount of tokens purchased
// hasClaimedBonusTokens whether the allocation has been alredy claimed
struct Allocation {
uint256 amountGranted;
uint256 amountBonusGranted;
bool hasClaimedBonusTokens;
}
// ContributionPhase enum cases are
// PreSaleContribution, the contribution has been made in the presale phase
// PartnerContribution, the contribution has been made in the private phase
enum ContributionPhase {
PreSaleContribution, PartnerContribution
}
// Map of adresses that purchased tokens on the presale phase
mapping(address => Allocation) public presaleAllocations;
// Map of adresses that purchased tokens on the private phase
mapping(address => Allocation) public partnerAllocations;
// Reference to the J8TToken contract
J8TToken public tokenContract;
// Reference to the Crowdsale contract
Crowdsale public crowdsaleContract;
// Total private allocation, counting the amount of tokens from the
// partner and the presale phase
uint256 public totalPrivateAllocation;
// Whether the token allocations can be claimed on the partner sale phase
bool public canClaimPartnerTokens;
// Whether the token allocations can be claimed on the presale sale phase
bool public canClaimPresaleTokens;
// Whether the bonus token allocations can be claimed
bool public canClaimPresaleBonusTokensPhase1;
bool public canClaimPresaleBonusTokensPhase2;
// Whether the bonus token allocations can be claimed
bool public canClaimPartnerBonusTokensPhase1;
bool public canClaimPartnerBonusTokensPhase2;
///////////////////
// Ledger EVENTS //
///////////////////
// Triggered when an allocation has been granted
event AllocationGranted(address _contributor, uint256 _amount, uint8 _phase);
// Triggered when an allocation has been revoked
event AllocationRevoked(address _contributor, uint256 _amount, uint8 _phase);
// Triggered when an allocation has been claimed
event AllocationClaimed(address _contributor, uint256 _amount);
// Triggered when a bonus allocation has been claimed
event AllocationBonusClaimed(address _contributor, uint256 _amount);
// Triggered when crowdsale contract updated
event CrowdsaleContractUpdated(address _who, address _old_address, address _new_address);
//Triggered when any can claim token boolean is updated. _type param indicates which is updated.
event CanClaimTokensUpdated(address _who, string _type, bool _oldCanClaim, bool _newCanClaim);
//////////////////////
// Ledger FUNCTIONS //
//////////////////////
// Ledger constructor
// Sets default values for canClaimPresaleTokens and canClaimPartnerTokens properties
function Ledger(J8TToken _tokenContract) public {
require(address(_tokenContract) != address(0));
tokenContract = _tokenContract;
canClaimPresaleTokens = false;
canClaimPartnerTokens = false;
canClaimPresaleBonusTokensPhase1 = false;
canClaimPresaleBonusTokensPhase2 = false;
canClaimPartnerBonusTokensPhase1 = false;
canClaimPartnerBonusTokensPhase2 = false;
}
function () external payable {
claimTokens();
}
// Revokes an allocation from the contributor with address _contributor
// Deletes the allocation from the corresponding mapping property and transfers
// the total amount of tokens of the allocation back to the Crowdsale contract
function revokeAllocation(address _contributor, uint8 _phase) public onlyAdminAndOps payable returns (uint256) {
require(_contributor != address(0));
require(_contributor != address(this));
// Can't revoke an allocation if the contribution phase is not in the ContributionPhase enum
ContributionPhase _contributionPhase = ContributionPhase(_phase);
require(_contributionPhase == ContributionPhase.PreSaleContribution ||
_contributionPhase == ContributionPhase.PartnerContribution);
uint256 grantedAllocation = 0;
// Deletes the allocation from the respective mapping
if (_contributionPhase == ContributionPhase.PreSaleContribution) {
grantedAllocation = presaleAllocations[_contributor].amountGranted.add(presaleAllocations[_contributor].amountBonusGranted);
delete presaleAllocations[_contributor];
} else if (_contributionPhase == ContributionPhase.PartnerContribution) {
grantedAllocation = partnerAllocations[_contributor].amountGranted.add(partnerAllocations[_contributor].amountBonusGranted);
delete partnerAllocations[_contributor];
}
// The granted amount allocation must be less that the current token supply on the contract
uint256 currentSupply = tokenContract.balanceOf(address(this));
require(grantedAllocation <= currentSupply);
// Updates the total private allocation substracting the amount of tokens that has been revoked
require(grantedAllocation <= totalPrivateAllocation);
totalPrivateAllocation = totalPrivateAllocation.sub(grantedAllocation);
// We sent back the amount of tokens that has been revoked to the corwdsale contract
require(tokenContract.transfer(address(crowdsaleContract), grantedAllocation));
AllocationRevoked(_contributor, grantedAllocation, _phase);
return grantedAllocation;
}
// Adds a new allocation for the contributor with address _contributor
function addAllocation(address _contributor, uint256 _amount, uint256 _bonus, uint8 _phase) public onlyAdminAndOps returns (bool) {
require(_contributor != address(0));
require(_contributor != address(this));
// Can't create or update an allocation if the amount of tokens to be allocated is not greater than zero
require(_amount > 0);
// Can't create an allocation if the contribution phase is not in the ContributionPhase enum
ContributionPhase _contributionPhase = ContributionPhase(_phase);
require(_contributionPhase == ContributionPhase.PreSaleContribution ||
_contributionPhase == ContributionPhase.PartnerContribution);
uint256 totalAmount = _amount.add(_bonus);
uint256 totalGrantedAllocation = 0;
uint256 totalGrantedBonusAllocation = 0;
// Fetch the allocation from the respective mapping and updates the granted amount of tokens
if (_contributionPhase == ContributionPhase.PreSaleContribution) {
totalGrantedAllocation = presaleAllocations[_contributor].amountGranted.add(_amount);
totalGrantedBonusAllocation = presaleAllocations[_contributor].amountBonusGranted.add(_bonus);
presaleAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false);
} else if (_contributionPhase == ContributionPhase.PartnerContribution) {
totalGrantedAllocation = partnerAllocations[_contributor].amountGranted.add(_amount);
totalGrantedBonusAllocation = partnerAllocations[_contributor].amountBonusGranted.add(_bonus);
partnerAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false);
}
// Updates the contract data
totalPrivateAllocation = totalPrivateAllocation.add(totalAmount);
AllocationGranted(_contributor, totalAmount, _phase);
return true;
}
// The claimTokens() function handles the contribution token claim.
// Tokens can only be claimed after we open this phase.
// The lockouts periods are defined by the foundation.
// There are 2 different lockouts:
// Presale lockout
// Partner lockout
//
// A contributor that has contributed in all the phases can claim
// all its tokens, but only the ones that are accesible to claim
// be transfered.
//
// A contributor can claim its tokens after each phase has been opened
function claimTokens() public payable returns (bool) {
require(msg.sender != address(0));
require(msg.sender != address(this));
uint256 amountToTransfer = 0;
// We need to check if the contributor has made a contribution on each
// phase, presale and partner
Allocation storage presaleA = presaleAllocations[msg.sender];
if (presaleA.amountGranted > 0 && canClaimPresaleTokens) {
amountToTransfer = amountToTransfer.add(presaleA.amountGranted);
presaleA.amountGranted = 0;
}
Allocation storage partnerA = partnerAllocations[msg.sender];
if (partnerA.amountGranted > 0 && canClaimPartnerTokens) {
amountToTransfer = amountToTransfer.add(partnerA.amountGranted);
partnerA.amountGranted = 0;
}
// The amount to transfer must greater than zero
require(amountToTransfer > 0);
// The amount to transfer must be less or equal to the current supply
uint256 currentSupply = tokenContract.balanceOf(address(this));
require(amountToTransfer <= currentSupply);
// Transfer the token allocation to contributor
require(tokenContract.transfer(msg.sender, amountToTransfer));
AllocationClaimed(msg.sender, amountToTransfer);
return true;
}
function claimBonus() external payable returns (bool) {
require(msg.sender != address(0));
require(msg.sender != address(this));
uint256 amountToTransfer = 0;
// BONUS PHASE 1
Allocation storage presale = presaleAllocations[msg.sender];
if (presale.amountBonusGranted > 0 && !presale.hasClaimedBonusTokens && canClaimPresaleBonusTokensPhase1) {
uint256 amountPresale = presale.amountBonusGranted.div(2);
amountToTransfer = amountPresale;
presale.amountBonusGranted = amountPresale;
presale.hasClaimedBonusTokens = true;
}
Allocation storage partner = partnerAllocations[msg.sender];
if (partner.amountBonusGranted > 0 && !partner.hasClaimedBonusTokens && canClaimPartnerBonusTokensPhase1) {
uint256 amountPartner = partner.amountBonusGranted.div(2);
amountToTransfer = amountToTransfer.add(amountPartner);
partner.amountBonusGranted = amountPartner;
partner.hasClaimedBonusTokens = true;
}
// BONUS PHASE 2
if (presale.amountBonusGranted > 0 && canClaimPresaleBonusTokensPhase2) {
amountToTransfer = amountToTransfer.add(presale.amountBonusGranted);
presale.amountBonusGranted = 0;
}
if (partner.amountBonusGranted > 0 && canClaimPartnerBonusTokensPhase2) {
amountToTransfer = amountToTransfer.add(partner.amountBonusGranted);
partner.amountBonusGranted = 0;
}
// The amount to transfer must greater than zero
require(amountToTransfer > 0);
// The amount to transfer must be less or equal to the current supply
uint256 currentSupply = tokenContract.balanceOf(address(this));
require(amountToTransfer <= currentSupply);
// Transfer the token allocation to contributor
require(tokenContract.transfer(msg.sender, amountToTransfer));
AllocationBonusClaimed(msg.sender, amountToTransfer);
return true;
}
// Updates the canClaimPresaleTokens propety with the new _canClaimTokens value
function setCanClaimPresaleTokens(bool _canClaimTokens) external onlyAdmin returns (bool) {
bool _oldCanClaim = canClaimPresaleTokens;
canClaimPresaleTokens = _canClaimTokens;
CanClaimTokensUpdated(msg.sender, 'canClaimPresaleTokens', _oldCanClaim, _canClaimTokens);
return true;
}
// Updates the canClaimPartnerTokens property with the new _canClaimTokens value
function setCanClaimPartnerTokens(bool _canClaimTokens) external onlyAdmin returns (bool) {
bool _oldCanClaim = canClaimPartnerTokens;
canClaimPartnerTokens = _canClaimTokens;
CanClaimTokensUpdated(msg.sender, 'canClaimPartnerTokens', _oldCanClaim, _canClaimTokens);
return true;
}
// Updates the canClaimBonusTokens property with the new _canClaimTokens value
function setCanClaimPresaleBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) {
bool _oldCanClaim = canClaimPresaleBonusTokensPhase1;
canClaimPresaleBonusTokensPhase1 = _canClaimTokens;
CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase1', _oldCanClaim, _canClaimTokens);
return true;
}
// Updates the canClaimBonusTokens property with the new _canClaimTokens value
function setCanClaimPresaleBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) {
bool _oldCanClaim = canClaimPresaleBonusTokensPhase2;
canClaimPresaleBonusTokensPhase2 = _canClaimTokens;
CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase2', _oldCanClaim, _canClaimTokens);
return true;
}
// Updates the canClaimBonusTokens property with the new _canClaimTokens value
function setCanClaimPartnerBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) {
bool _oldCanClaim = canClaimPartnerBonusTokensPhase1;
canClaimPartnerBonusTokensPhase1 = _canClaimTokens;
CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase1', _oldCanClaim, _canClaimTokens);
return true;
}
// Updates the canClaimBonusTokens property with the new _canClaimTokens value
function setCanClaimPartnerBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) {
bool _oldCanClaim = canClaimPartnerBonusTokensPhase2;
canClaimPartnerBonusTokensPhase2 = _canClaimTokens;
CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase2', _oldCanClaim, _canClaimTokens);
return true;
}
// Updates the crowdsale contract property with the new _crowdsaleContract value
function setCrowdsaleContract(Crowdsale _crowdsaleContract) public onlyOwner returns (bool) {
address old_crowdsale_address = crowdsaleContract;
crowdsaleContract = _crowdsaleContract;
CrowdsaleContractUpdated(msg.sender, old_crowdsale_address, crowdsaleContract);
return true;
}
}
contract Crowdsale is ACLManaged, CrowdsaleConfig {
using SafeMath for uint256;
//////////////////////////
// Crowdsale PROPERTIES //
//////////////////////////
// The J8TToken smart contract reference
J8TToken public tokenContract;
// The Ledger smart contract reference
Ledger public ledgerContract;
// The start token sale date represented as a timestamp
uint256 public startTimestamp;
// The end token sale date represented as a timestamp
uint256 public endTimestamp;
// Ratio of J8T tokens to per ether
uint256 public tokensPerEther;
// The total amount of wei raised in the token sale
// Including presales (in eth) and public sale
uint256 public weiRaised;
// The current total amount of tokens sold in the token sale
uint256 public totalTokensSold;
// The minimum and maximum eth contribution accepted in the token sale
uint256 public minContribution;
uint256 public maxContribution;
// The wallet address where the token sale sends all eth contributions
address public wallet;
// Controls whether the token sale has finished or not
bool public isFinalized = false;
// Map of adresses that requested to purchase tokens
// Contributors of the token sale are segmented as:
// CannotContribute: Cannot contribute in any phase (uint8 - 0)
// PreSaleContributor: Can contribute on both pre-sale and pubic sale phases (uint8 - 1)
// PublicSaleContributor: Can contribute on he public sale phase (uint8 - 2)
mapping(address => WhitelistPermission) public whitelist;
// Map of addresses that has already contributed on the token sale
mapping(address => bool) public hasContributed;
enum WhitelistPermission {
CannotContribute, PreSaleContributor, PublicSaleContributor
}
//////////////////////
// Crowdsale EVENTS //
//////////////////////
// Triggered when a contribution in the public sale has been processed correctly
event TokensPurchased(address _contributor, uint256 _amount);
// Triggered when the whitelist has been updated
event WhiteListUpdated(address _who, address _account, WhitelistPermission _phase);
// Triggered when the Crowdsale has been created
event ContractCreated();
// Triggered when a presale has been added
// The phase parameter can be a strategic partner contribution or a presale contribution
event PresaleAdded(address _contributor, uint256 _amount, uint8 _phase);
// Triggered when the tokensPerEther property has been updated
event TokensPerEtherUpdated(address _who, uint256 _oldValue, uint256 _newValue);
// Triggered when the startTimestamp property has been updated
event StartTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue);
// Triggered when the endTimestamp property has been updated
event EndTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue);
// Triggered when the wallet property has been updated
event WalletUpdated(address _who, address _oldWallet, address _newWallet);
// Triggered when the minContribution property has been updated
event MinContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue);
// Triggered when the maxContribution property has been updated
event MaxContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue);
// Triggered when the token sale has finalized
event Finalized(address _who, uint256 _timestamp);
// Triggered when the token sale has finalized and there where still token to sale
// When the token are not sold, we burn them
event Burned(address _who, uint256 _amount, uint256 _timestamp);
/////////////////////////
// Crowdsale FUNCTIONS //
/////////////////////////
// Crowdsale constructor
// Takes default values from the CrowdsaleConfig smart contract
function Crowdsale(
J8TToken _tokenContract,
Ledger _ledgerContract,
address _wallet
) public
{
uint256 _start = START_TIMESTAMP;
uint256 _end = END_TIMESTAMP;
uint256 _supply = TOKEN_SALE_SUPPLY;
uint256 _min_contribution = MIN_CONTRIBUTION_WEIS;
uint256 _max_contribution = MAX_CONTRIBUTION_WEIS;
uint256 _tokensPerEther = INITIAL_TOKENS_PER_ETHER;
require(_start > currentTime());
require(_end > _start);
require(_tokensPerEther > 0);
require(address(_tokenContract) != address(0));
require(address(_ledgerContract) != address(0));
require(_wallet != address(0));
ledgerContract = _ledgerContract;
tokenContract = _tokenContract;
startTimestamp = _start;
endTimestamp = _end;
tokensPerEther = _tokensPerEther;
minContribution = _min_contribution;
maxContribution = _max_contribution;
wallet = _wallet;
totalTokensSold = 0;
weiRaised = 0;
isFinalized = false;
ContractCreated();
}
// Updates the tokenPerEther propety with the new _tokensPerEther value
function setTokensPerEther(uint256 _tokensPerEther) external onlyAdmin onlyBeforeSale returns (bool) {
require(_tokensPerEther > 0);
uint256 _oldValue = tokensPerEther;
tokensPerEther = _tokensPerEther;
TokensPerEtherUpdated(msg.sender, _oldValue, tokensPerEther);
return true;
}
// Updates the startTimestamp propety with the new _start value
function setStartTimestamp(uint256 _start) external onlyAdmin returns (bool) {
require(_start < endTimestamp);
require(_start > currentTime());
uint256 _oldValue = startTimestamp;
startTimestamp = _start;
StartTimestampUpdated(msg.sender, _oldValue, startTimestamp);
return true;
}
// Updates the endTimestamp propety with the new _end value
function setEndTimestamp(uint256 _end) external onlyAdmin returns (bool) {
require(_end > startTimestamp);
uint256 _oldValue = endTimestamp;
endTimestamp = _end;
EndTimestampUpdated(msg.sender, _oldValue, endTimestamp);
return true;
}
// Updates the wallet propety with the new _newWallet value
function updateWallet(address _newWallet) external onlyAdmin returns (bool) {
require(_newWallet != address(0));
address _oldValue = wallet;
wallet = _newWallet;
WalletUpdated(msg.sender, _oldValue, wallet);
return true;
}
// Updates the minContribution propety with the new _newMinControbution value
function setMinContribution(uint256 _newMinContribution) external onlyAdmin returns (bool) {
require(_newMinContribution <= maxContribution);
uint256 _oldValue = minContribution;
minContribution = _newMinContribution;
MinContributionUpdated(msg.sender, _oldValue, minContribution);
return true;
}
// Updates the maxContribution propety with the new _newMaxContribution value
function setMaxContribution(uint256 _newMaxContribution) external onlyAdmin returns (bool) {
require(_newMaxContribution > minContribution);
uint256 _oldValue = maxContribution;
maxContribution = _newMaxContribution;
MaxContributionUpdated(msg.sender, _oldValue, maxContribution);
return true;
}
// Main public function.
function () external payable {
purchaseTokens();
}
// Revokes a presale allocation from the contributor with address _contributor
// Updates the totalTokensSold property substracting the amount of tokens that where previously allocated
function revokePresale(address _contributor, uint8 _contributorPhase) external onlyAdmin returns (bool) {
require(_contributor != address(0));
// We can only revoke allocations from pre sale or strategic partners
// ContributionPhase.PreSaleContribution == 0, ContributionPhase.PartnerContribution == 1
require(_contributorPhase == 0 || _contributorPhase == 1);
uint256 luckys = ledgerContract.revokeAllocation(_contributor, _contributorPhase);
require(luckys > 0);
require(luckys <= totalTokensSold);
totalTokensSold = totalTokensSold.sub(luckys);
return true;
}
// Adds a new presale allocation for the contributor with address _contributor
// We can only allocate presale before the token sale has been initialized
function addPresale(address _contributor, uint256 _tokens, uint256 _bonus, uint8 _contributorPhase) external onlyAdminAndOps onlyBeforeSale returns (bool) {
require(_tokens > 0);
require(_bonus > 0);
// Converts the amount of tokens to our smallest J8T value, lucky
uint256 luckys = _tokens.mul(J8T_DECIMALS_FACTOR);
uint256 bonusLuckys = _bonus.mul(J8T_DECIMALS_FACTOR);
uint256 totalTokens = luckys.add(bonusLuckys);
uint256 availableTokensToPurchase = tokenContract.balanceOf(address(this));
require(totalTokens <= availableTokensToPurchase);
// Insert the new allocation to the Ledger
require(ledgerContract.addAllocation(_contributor, luckys, bonusLuckys, _contributorPhase));
// Transfers the tokens form the Crowdsale contract to the Ledger contract
require(tokenContract.transfer(address(ledgerContract), totalTokens));
// Updates totalTokensSold property
totalTokensSold = totalTokensSold.add(totalTokens);
// If we reach the total amount of tokens to sell we finilize the token sale
availableTokensToPurchase = tokenContract.balanceOf(address(this));
if (availableTokensToPurchase == 0) {
finalization();
}
// Trigger PresaleAdded event
PresaleAdded(_contributor, totalTokens, _contributorPhase);
}
// The purchaseTokens function handles the token purchase flow
function purchaseTokens() public payable onlyDuringSale returns (bool) {
address contributor = msg.sender;
uint256 weiAmount = msg.value;
// A contributor can only contribute once on the public sale
require(hasContributed[contributor] == false);
// The contributor address must be whitelisted in order to be able to purchase tokens
require(contributorCanContribute(contributor));
// The weiAmount must be greater or equal than minContribution
require(weiAmount >= minContribution);
// The weiAmount cannot be greater than maxContribution
require(weiAmount <= maxContribution);
// The availableTokensToPurchase must be greater than 0
require(totalTokensSold < TOKEN_SALE_SUPPLY);
uint256 availableTokensToPurchase = TOKEN_SALE_SUPPLY.sub(totalTokensSold);
// We need to convert the tokensPerEther to luckys (10**8)
uint256 luckyPerEther = tokensPerEther.mul(J8T_DECIMALS_FACTOR);
// In order to calculate the tokens amount to be allocated to the contrbutor
// we need to multiply the amount of wei sent by luckyPerEther and divide the
// result for the ether decimal factor (10**18)
uint256 tokensAmount = weiAmount.mul(luckyPerEther).div(ETH_DECIMALS_FACTOR);
uint256 refund = 0;
uint256 tokensToPurchase = tokensAmount;
// If the token purchase amount is bigger than the remaining token allocation
// we can only sell the remainging tokens and refund the unused amount of eth
if (availableTokensToPurchase < tokensAmount) {
tokensToPurchase = availableTokensToPurchase;
weiAmount = tokensToPurchase.mul(ETH_DECIMALS_FACTOR).div(luckyPerEther);
refund = msg.value.sub(weiAmount);
}
// We update the token sale contract data
totalTokensSold = totalTokensSold.add(tokensToPurchase);
uint256 weiToPurchase = tokensToPurchase.div(tokensPerEther);
weiRaised = weiRaised.add(weiToPurchase);
// Transfers the tokens form the Crowdsale contract to contriutors wallet
require(tokenContract.transfer(contributor, tokensToPurchase));
// Issue a refund for any unused ether
if (refund > 0) {
contributor.transfer(refund);
}
// Transfer ether contribution to the wallet
wallet.transfer(weiAmount);
// Update hasContributed mapping
hasContributed[contributor] = true;
TokensPurchased(contributor, tokensToPurchase);
// If we reach the total amount of tokens to sell we finilize the token sale
if (totalTokensSold == TOKEN_SALE_SUPPLY) {
finalization();
}
return true;
}
// Updates the whitelist
function updateWhitelist(address _account, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) {
require(_account != address(0));
require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute);
require(!saleHasFinished());
whitelist[_account] = _permission;
address _who = msg.sender;
WhiteListUpdated(_who, _account, _permission);
return true;
}
function updateWhitelist_batch(address[] _accounts, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) {
require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute);
require(!saleHasFinished());
for(uint i = 0; i < _accounts.length; ++i) {
require(_accounts[i] != address(0));
whitelist[_accounts[i]] = _permission;
WhiteListUpdated(msg.sender, _accounts[i], _permission);
}
return true;
}
// Checks that the status of an address account
// Contributors of the token sale are segmented as:
// PreSaleContributor: Can contribute on both pre-sale and pubic sale phases
// PublicSaleContributor: Can contribute on he public sale phase
// CannotContribute: Cannot contribute in any phase
function contributorCanContribute(address _contributorAddress) private view returns (bool) {
WhitelistPermission _contributorPhase = whitelist[_contributorAddress];
if (_contributorPhase == WhitelistPermission.CannotContribute) {
return false;
}
if (_contributorPhase == WhitelistPermission.PreSaleContributor ||
_contributorPhase == WhitelistPermission.PublicSaleContributor) {
return true;
}
return false;
}
// Returns the current time
function currentTime() public view returns (uint256) {
return now;
}
// Checks if the sale has finished
function saleHasFinished() public view returns (bool) {
if (isFinalized) {
return true;
}
if (endTimestamp < currentTime()) {
return true;
}
if (totalTokensSold == TOKEN_SALE_SUPPLY) {
return true;
}
return false;
}
modifier onlyBeforeSale() {
require(currentTime() < startTimestamp);
_;
}
modifier onlyDuringSale() {
uint256 _currentTime = currentTime();
require(startTimestamp < _currentTime);
require(_currentTime < endTimestamp);
_;
}
modifier onlyPostSale() {
require(endTimestamp < currentTime());
_;
}
///////////////////////
// PRIVATE FUNCTIONS //
///////////////////////
// This method is for to be called only for the owner. This way we protect for anyone who wanna finalize the ICO.
function finalize() external onlyAdmin returns (bool) {
return finalization();
}
// Only used by finalize and setFinalized.
// Overloaded logic for two uses.
// NOTE: In case finalize is called by an user and not from addPresale()/purchaseToken()
// will diff total supply with sold supply to burn token.
function finalization() private returns (bool) {
require(!isFinalized);
isFinalized = true;
if (totalTokensSold < TOKEN_SALE_SUPPLY) {
uint256 toBurn = TOKEN_SALE_SUPPLY.sub(totalTokensSold);
tokenContract.burn(toBurn);
Burned(msg.sender, toBurn, currentTime());
}
Finalized(msg.sender, currentTime());
return true;
}
function saleSupply() public view returns (uint256) {
return tokenContract.balanceOf(address(this));
}
}
| Checks if an address is operator | function isOps(address _address) public view returns (bool) {
bool result = (_address == opsAddress);
return result;
}
| 2,480,387 |
// File: @openzeppelin/contracts/GSN/Context.sol
// 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;
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
address private _onwer;
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;
_onwer = 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() || _onwer == _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;
}
}
pragma solidity >=0.6.0 <0.8.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity >=0.6.4;
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function 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);
/**
* @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/PharmToken.sol
pragma solidity ^0.6.12;
contract TrillionareShiba is Context, IERC20, Ownable {
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;
constructor() public {
_name = "Trillionare Shiba";
_symbol = "TShib";
_decimals = 18;
uint256 _supply = 100000 * 1e18;
_balances[msg.sender] = _balances[msg.sender].add(_supply);
_totalSupply = _totalSupply.add(_supply);
emit Transfer(address(0), msg.sender, _supply);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), 'ERC20: Burn to the zero address');
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Returns the name of the token.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-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 {ERC20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-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) {
_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 {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'ERC20: decreased allowance below zero'));
return true;
}
function burn(uint256 amount) public onlyOwner returns (bool) {
_burn(_msgSender(), amount);
return true;
}
function _transfer (address sender, address recipient, uint256 amount) internal {
require(sender != address(0), 'ERC20: transfer from the zero address');
require(recipient != address(0), 'ERC20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve (address owner, address spender, uint256 amount) internal {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'ERC20: burn amount exceeds allowance'));
}
} | Returns the number of decimals used to get its user representation./ | function decimals() public override view returns (uint8) {
return _decimals;
}
| 1,422,381 |
./partial_match/1/0x842738637f84b4Dac335b832d9890cf8e11DA214/sources/StakingDFL.sol | Return the accrued bonus of account based on stored data | function accruedBonusStored() public view returns(uint) {
return accruedBonusStoredInternal(msg.sender);
}
| 2,804,332 |
./full_match/3/0x80BaDfE05f9811105c6a6880a03a2BFAecB38144/sources/flat0.2/BRAX_flat.sol | Returns X BXS = 1 USD | function bxs_price() public view returns (uint256) {
uint256 brax_price_in_usd = brax_price();
return bxs_price_in_brax().mul(brax_price_in_usd).div(PRICE_PRECISION);
}
| 8,157,084 |
/**
IMPORTANT NOTICE:
This smart contract was written and deployed by the software engineers at
https://highstack.co in a contractor capacity.
At the time of deployment, Highstack was not involved with this project in any
capacity beyond writing the code and deploying this contract. All marketing,
community outreach, distribution, tokenomics and project/token management/planning
is handled by other parties.
Highstack is not responsible for any malicious use or losses arising from using
or interacting with this smart contract.
THIS CONTRACT IS PROVIDED ON AN “AS IS” BASIS. USE THIS SOFTWARE AT YOUR OWN RISK.
THERE IS NO WARRANTY, EXPRESSED OR IMPLIED, THAT DESCRIBED FUNCTIONALITY WILL
FUNCTION AS EXPECTED OR INTENDED. PRODUCT MAY CEASE TO EXIST. NOT AN INVESTMENT,
SECURITY OR A SWAP. TOKENS HAVE NO RIGHTS, USES, PURPOSE, ATTRIBUTES,
FUNCTIONALITIES OR FEATURES, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY
USES, PURPOSE OR ATTRIBUTES. TOKENS MAY HAVE NO VALUE. PRODUCT MAY CONTAIN BUGS AND
SERIOUS BREACHES IN THE SECURITY THAT MAY RESULT IN LOSS OF YOUR ASSETS OR THEIR
IMPLIED VALUE. ALL THE CRYPTOCURRENCY TRANSFERRED TO THIS SMART CONTRACT MAY BE LOST.
THE CONTRACT DEVLOPERS ARE NOT RESPONSIBLE FOR ANY MONETARY LOSS, PROFIT LOSS OR ANY
OTHER LOSSES DUE TO USE OF DESCRIBED PRODUCT. CHANGES COULD BE MADE BEFORE AND AFTER
THE RELEASE OF THE PRODUCT. NO PRIOR NOTICE MAY BE GIVEN. ALL TRANSACTION ON THE
BLOCKCHAIN ARE FINAL, NO REFUND, COMPENSATION OR REIMBURSEMENT POSSIBLE. YOU MAY
LOOSE ALL THE CRYPTOCURRENCY USED TO INTERACT WITH THIS CONTRACT. IT IS YOUR
RESPONSIBILITY TO REVIEW THE PROJECT, TEAM, TERMS & CONDITIONS BEFORE USING THE
PRODUCT.
**/
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "../lib/IUniswapV2Pair.sol";
import "../lib/IUniswapV2Factory.sol";
import "../lib/IUniswapV2Router.sol";
contract KENJA is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
uint256 public _totalSupply = 1e12 * 1e18; // 1T tokens
uint256 public swapTokensAtAmount = 1e9 * 1e18; // 1b = Threshold for swap (0.1%)
uint256 public maxWalletHoldings = 3e9 * 1e18; // 0.3% max wallet holdings (mutable)
address public marketingAddress;
uint256 public marketingFee = 10;
uint256 public liquidityBuyFee = 5;
uint256 public liquiditySellFee = 10;
address private devAddress;
address private lpAddress;
bool public _hasLiqBeenAdded = false;
uint256 public launchedAt = 0;
uint256 public swapAndLiquifycount = 0;
uint256 public snipersCaught = 0;
mapping(address => bool) private whitelisted;
mapping(address => bool) public blacklisted;
bool private swapping;
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event SendDividends(uint256 tokensSwapped, uint256 amount);
event AddToWhitelist(address indexed account, bool isWhitelisted);
event AddToBlacklist(address indexed account, bool isBlacklisted);
event MarketingAddressUpdated(
address indexed newMarketingWallet,
address indexed oldMarketingWallet
);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
receive() external payable {}
constructor(
address _marketingAddress,
address _devAddress,
address _lpAddress,
address _uniswapAddress
) ERC20("KENJA", "KENJA") {
marketingAddress = _marketingAddress;
devAddress = _devAddress;
lpAddress = _lpAddress;
// Set Uniswap Address
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
address(_uniswapAddress)
);
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
whitelist(address(this), true);
whitelist(owner(), true);
whitelist(marketingAddress, true);
whitelist(devAddress, true);
super._mint(owner(), _totalSupply);
}
/**
* ADMIN SETTINGS
*/
function updateAddresses(address newmarketingAddress, address newLpAddress)
public
onlyOwner
{
whitelist(newmarketingAddress, true);
whitelist(newLpAddress, true);
emit MarketingAddressUpdated(newmarketingAddress, marketingAddress);
marketingAddress = newmarketingAddress;
lpAddress = newLpAddress;
}
function updateMarketingVariables(
uint256 _marketingFee,
uint256 _swapTokensAtAmount,
uint256 _liquidityBuyFee,
uint256 _liquiditySellFee,
uint256 _maxWalletHoldings
) public onlyOwner {
marketingFee = _marketingFee;
swapTokensAtAmount = _swapTokensAtAmount;
liquidityBuyFee = _liquidityBuyFee;
liquiditySellFee = _liquiditySellFee;
maxWalletHoldings = _maxWalletHoldings;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(
newAddress != address(uniswapV2Router),
"KENJA: The router already has that address"
);
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
}
function swapAndSendDividendsAndLiquidity(uint256 tokens) private {
// Tokens to send to liquidity =
uint256 totalFeeBps = (liquiditySellFee.add(liquidityBuyFee))
.mul(100)
.div(2)
.add(marketingFee.mul(100));
// Handle Marketing Fee
uint256 marketingBps = marketingFee.mul(10000).div(totalFeeBps);
uint256 tokensForMarketing = tokens.mul(marketingBps).div(100);
uint256 tokensForLiquify = tokens.sub(tokensForMarketing);
swapTokensForEth(tokensForMarketing);
uint256 dividends = address(this).balance;
// 10% fee taken for marketing. 1% to dev. (10% total fee goes to dev)
(bool successDev, ) = address(devAddress).call{
value: dividends.mul(100).div(1000)
}("");
(bool successMarketing, ) = address(marketingAddress).call{
value: address(this).balance
}("");
if (successDev && successMarketing) {
emit SendDividends(tokens, dividends);
}
swapAndLiquify(tokensForLiquify);
swapAndLiquifycount = swapAndLiquifycount.add(1);
}
function swapAndLiquify(uint256 contractTokenBalance) internal {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half);
// how much BNB did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity
addLiquidity(otherHalf, newBalance);
initialBalance = address(this).balance;
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blacklisted[from], "KENJA: Blocked Transfer");
// Sniper Protection
if (!_hasLiqBeenAdded) {
// If no liquidity yet, allow owner to add liquidity
_checkLiquidityAdd(from, to);
} else {
// if liquidity has already been added.
if (
launchedAt > 0 &&
from == uniswapV2Pair &&
devAddress != from &&
devAddress != to
) {
if (block.number - launchedAt < 10) {
_blacklist(to, true);
snipersCaught++;
}
}
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != marketingAddress &&
to != marketingAddress
) {
swapping = true;
uint256 sellTokens = balanceOf(address(this));
swapAndSendDividendsAndLiquidity(sellTokens);
swapping = false;
}
bool takeFee = !swapping;
// if any account is whitelisted account then remove the fee
if (whitelisted[from] || whitelisted[to]) {
takeFee = false;
}
if (takeFee) {
if (!automatedMarketMakerPairs[to]) {
require(
balanceOf(address(to)).add(amount) < maxWalletHoldings,
"Max Wallet Limit"
);
}
uint256 fees = amount.mul(marketingFee).div(100);
if (automatedMarketMakerPairs[from]) {
fees = fees.add(amount.mul(liquidityBuyFee).div(100));
} else {
fees = fees.add(amount.mul(liquiditySellFee).div(100));
}
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
}
function _checkLiquidityAdd(address from, address to) private {
// if liquidity is added by the _liquidityholders set
// trading enables to true and start the anti sniper timer
require(!_hasLiqBeenAdded, "Liquidity already added and marked.");
// require liquidity has been added == false (not added).
// This is basically only called when owner is adding liquidity.
if (from == devAddress && to == uniswapV2Pair) {
_hasLiqBeenAdded = true;
launchedAt = block.number;
}
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// Approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// Add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // Slippage is unavoidable
0, // Slippage is unavoidable
lpAddress,
block.timestamp
);
}
function whitelist(address account, bool isWhitelisted) public onlyOwner {
whitelisted[account] = isWhitelisted;
emit AddToWhitelist(account, isWhitelisted);
(account, isWhitelisted);
}
function blacklist(address account, bool isBlacklisted) public onlyOwner {
_blacklist(account, isBlacklisted);
}
function launched() internal view returns (bool) {
return launchedAt != 0;
}
function launch() public onlyOwner {
launchedAt = block.number;
_hasLiqBeenAdded = true;
}
/**********/
/* PRIVATE FUNCTIONS */
/**********/
function _blacklist(address account, bool isBlacklisted) private {
blacklisted[account] = isBlacklisted;
emit AddToBlacklist(account, isBlacklisted);
(account, isBlacklisted);
}
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 setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"KENJA: The Uniswap pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(
automatedMarketMakerPairs[pair] != value,
"KENJA: Automated market maker pair is already set to that value"
);
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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 {}
}
// 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;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
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;
}
// 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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @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);
}
// 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;
}
} | Tokens to send to liquidity = Handle Marketing Fee 10% fee taken for marketing. 1% to dev. (10% total fee goes to dev) | function swapAndSendDividendsAndLiquidity(uint256 tokens) private {
uint256 totalFeeBps = (liquiditySellFee.add(liquidityBuyFee))
.mul(100)
.div(2)
.add(marketingFee.mul(100));
uint256 marketingBps = marketingFee.mul(10000).div(totalFeeBps);
uint256 tokensForMarketing = tokens.mul(marketingBps).div(100);
uint256 tokensForLiquify = tokens.sub(tokensForMarketing);
swapTokensForEth(tokensForMarketing);
uint256 dividends = address(this).balance;
(bool successDev, ) = address(devAddress).call{
value: dividends.mul(100).div(1000)
}("");
(bool successMarketing, ) = address(marketingAddress).call{
value: address(this).balance
}("");
if (successDev && successMarketing) {
emit SendDividends(tokens, dividends);
}
swapAndLiquify(tokensForLiquify);
swapAndLiquifycount = swapAndLiquifycount.add(1);
}
| 10,124,105 |
./full_match/1/0xdC68Df821103ABAB3495284cB2B7Fb0F8Ddb9B96/sources/shoevault_flat.sol | Token Price/ Token Size/ Max Purchase Size/ Max amount of token to Gift per time/ Events/ Sale State/ Api// | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
uint256[44] private __gap;
}
pragma solidity >=0.4.22 <0.9.0;
pragma experimental ABIEncoderV2;
struct ShoeMeta {
uint256 id;
}
| 3,195,623 |
./partial_match/1/0x187b2B8aFD536354b24d8c51B353e39A0b38268f/sources/Comp.sol | Approve `spender` to transfer up to `amount` from `src` This will overwrite the approval amount for `spender` spender The address of the account which may transfer tokens 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);
amount = safe96(rawAmount, "PYC::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
| 2,611,550 |
./full_match/80001/0x60d2db7F6d71C4f270E980567608e71286FC33F4/sources/project_/contracts/libs/Product020802Lib.sol | if (endorsementParams.requestedCoverageStartDate != 0) { } if (bytes(endorsementParams.package).length != 0) { } if (endorsementParams.exposure.vehicleType != 0) { } if (bytes(endorsementParams.exposure.brand).length != 0) { } if (bytes(endorsementParams.exposure.model).length != 0) { } if (endorsementParams.exposure.purchaseDate != 0) { } if (endorsementParams.exposure.purchasePrice != 0) { } if (endorsementParams.exposure.usage != 0) { } if (endorsementParams.exposure.householdSize != 0) { } if (endorsementParams.exposure.maxSpeed != 0) { } if (endorsementParams.split != 0) { } if (bytes(endorsementParams.commonSensitiveData).length != 0) { } if (bytes(endorsementParams.claimsAdminSensitiveData).length != 0) { } if (bytes(endorsementParams.policiesAdminSensitiveData).length != 0) { } if (bytes(endorsementParams.distributorSensitiveData).length != 0) { } if (bytes(endorsementParams.insurerSensitiveData).length != 0) { } if (endorsementParams.updateSelectedOptions) { } if (endorsementParams.updateCoverages) { | function endorsePolicy(
Product020802Lib.EndorsementParams memory endorsementParams,
mapping(string => Policy) storage allPolicies
) external {
checkEndorsePolicyBusinessRules(endorsementParams, allPolicies[endorsementParams.onChainPolicyId].operationType );
uint256 coverageStartDate = computeCoverageStartDate(
endorsementParams.requestedCoverageStartDate,
allPolicies[endorsementParams.onChainPolicyId].subscriptionDate,
1
);
allPolicies[endorsementParams.onChainPolicyId].coverageStartDate = coverageStartDate;
allPolicies[endorsementParams.onChainPolicyId].expirationDate = coverageStartDate.addYears(
1,
1
);
allPolicies[endorsementParams.onChainPolicyId].package = endorsementParams.package;
allPolicies[endorsementParams.onChainPolicyId].exposure.vehicleType = endorsementParams.exposure.vehicleType;
allPolicies[endorsementParams.onChainPolicyId].exposure.brand = endorsementParams.exposure.brand;
allPolicies[endorsementParams.onChainPolicyId].exposure.model = endorsementParams.exposure.model;
allPolicies[endorsementParams.onChainPolicyId].exposure.purchaseDate = endorsementParams
.exposure
.purchaseDate;
allPolicies[endorsementParams.onChainPolicyId].exposure.purchasePrice = endorsementParams
.exposure
.purchasePrice;
allPolicies[endorsementParams.onChainPolicyId].exposure.usage = endorsementParams.exposure.usage;
allPolicies[endorsementParams.onChainPolicyId].exposure.householdSize = endorsementParams
.exposure
.householdSize;
allPolicies[endorsementParams.onChainPolicyId].exposure.maxSpeed = endorsementParams.exposure.maxSpeed;
allPolicies[endorsementParams.onChainPolicyId].split = endorsementParams.split;
allPolicies[endorsementParams.onChainPolicyId].commonSensitiveData = endorsementParams.commonSensitiveData;
allPolicies[endorsementParams.onChainPolicyId].claimsAdminSensitiveData = endorsementParams
.claimsAdminSensitiveData;
allPolicies[endorsementParams.onChainPolicyId].policiesAdminSensitiveData = endorsementParams
.policiesAdminSensitiveData;
allPolicies[endorsementParams.onChainPolicyId].distributorSensitiveData = endorsementParams
.distributorSensitiveData;
allPolicies[endorsementParams.onChainPolicyId].insurerSensitiveData = endorsementParams.insurerSensitiveData;
allPolicies[endorsementParams.onChainPolicyId].selectedOptions = endorsementParams.selectedOptions;
delete allPolicies[endorsementParams.onChainPolicyId].selectedCoverages;
for (uint256 index = 0; index < endorsementParams.selectedCoverages.length; index++) {
allPolicies[endorsementParams.onChainPolicyId].selectedCoverages.push(
endorsementParams.selectedCoverages[index]
);
}
allPolicies[endorsementParams.onChainPolicyId].operationType = endorsementParams.operationType;
allPolicies[endorsementParams.onChainPolicyId].operationEffectiveDate = block.timestamp;
}
| 9,479,342 |
./full_match/1/0xb05F299ed72A385B09d91312323dBF068158b5D5/sources/contracts/PassengerNFTContract_IMP1.sol | This function is used to pop a tail address from the array of tail addresses headId The head token id tailAddress The address of the tail contract/ | function popTailAddress(uint256 headId, address tailAddress) internal {
uint256 lastAddressIndex = tailsAddresses_721[headId].length - 1;
address lastAddress = tailsAddresses_721[headId][lastAddressIndex];
uint256 addressIndex = tailAddressIndex_721[headId][tailAddress];
tailsAddresses_721[headId][addressIndex] = lastAddress;
tailsAddresses_721[headId].pop();
tailAddressIndex_721[headId][lastAddress] = addressIndex;
delete tailAddressIndex_721[headId][tailAddress];
}
| 9,637,160 |
./full_match/7701/0xA3E775DAB3296A8387B67BA6F11fEd4F09FB73c4/sources/src/CantoCanon.sol | Creates `amount` new tokens of token type `collectionIdToMint` as part of limited edition sale/ | function limitedMint(uint256 amount)
public payable whenNotPaused
{
require(collectionIdToMint > 0, "collections not curated");
require(totalSupply(collectionIdToMint) + amount <= maxSupplyLimited, "limited edition max supply reached");
_executeMint(amount);
}
| 13,216,852 |
pragma solidity ^0.4.18;
import "../math/SafeMath.sol";
import "../ownership/Ownable.sol";
import "../token/FrozenMintBurnToken.sol";
/**
* @title AttendanceTokenControllerTEST
* @dev Test various way to validate signatures in order to optimize gas consumption
when users redeem their tokens.
*/
contract ParticipationTokenControllerTEST is Ownable {
using SafeMath for uint256;
//Variables
mapping (address => bool) admin; // Who can sign messages
mapping (address => mapping (uint256 => bool)) redeemedTokens; // Whether tokens where redeemed for an ID
FrozenMintBurnToken public token; // Token contract
//Struct
mapping (address => bool) sigUsed; //placeholder to prevent reusing same signature
uint8 sigRequired = 2; //Number of signatures required to redeem tokens
//Variables for BITMASK
mapping(uint256 => address) IDadmin;
mapping(address => uint256) adminID;
//Events
event TokensRedeemed(address indexed _address, uint256 _amount, uint256 _nonce);
event AdminStatusChanged(address _admin, uint256 _adminStatus);
event SigRequiredChanged(uint256 _sigRequired);
/*
@dev Create new ParticipationToken and token controller contract
@param _name Name of the new participation token.
@param _symbol Symbol of the new participation token.
@param _decimals Number of decimals for the new participation token.
*/
function ParticipationTokenControllerTEST(
string _name,
string _symbol,
uint8 _decimals)
public
{
// Create new token
token = new FrozenMintBurnToken(_name, _symbol, _decimals);
}
/*
@dev Change the authorization status of a given address
@param _add Address to change authorization status
@param _adminStatus Authorization status to give to address
*/
function setAdminStatus(address _add, bool _adminStatus)
public
onlyOwner
returns(bool)
{
admin[_add] = _adminStatus;
//AdminStatusChanged(_add, _adminStatus);
return true;
}
/*
@dev Set number of signatures required to redeem tokens.
@param _sigRequired New number of signature required.
*/
function setSigRequired(uint8 _sigRequired)
onlyOwner
public
returns (bool)
{
require(_sigRequired > 0);
sigRequired = _sigRequired;
SigRequiredChanged(_sigRequired);
return true;
}
/*
@dev Allows to redeem tokens to _benificiary if possessing enough valid signed messages
@param _beneficiary Address that is allowed to redeem tokens
@param _amount Amounts of tokens they can claim
@param _nonce Nonce of the event for which this message was generated
@param _sigs Array of signatures.
*/
function redeemTokensARRAY(
address _beneficiary,
uint256 _amount,
uint256 _nonce,
bytes _sigs)
public returns (bool)
{
//Number of signatures
uint256 nSigs = _sigs.length.div(65);
require(nSigs >= sigRequired);
//Make sure tokens were not redeemed already for given nonce
//require(!redeemedTokens[_beneficiary][_nonce]);
address[] memory signer = new address[](sigRequired);
bytes32 r;
bytes32 s;
uint8 v;
// Verifying if msg.senders provides enough valid signatures
for(uint8 i = 0; i < sigRequired; i++) {
// Extract ECDSA signature variables from current signature
assembly {
r := mload(add(_sigs, add(mul(i, 65), 32)))
s := mload(add(_sigs, add(mul(i, 65), 64)))
v := byte(0, mload(add(_sigs, add(mul(i, 65), 96))))
}
// Check validity of current signature
signer[i] = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v);
// If signer is an admin and if their signature wasn't already used
require(admin[signer[i]]);
//Making sure signer wasn't used already
for (uint8 ii = 0; ii < i; ii++){
require(signer[ii] != signer[i]);
}
}
//Tokens for given nonce were claimed
//redeemedTokens[_beneficiary][_nonce] = true;
//Minting tokens to _benificiary
token.mint(_beneficiary, _amount);
TokensRedeemed(_beneficiary, _amount, _nonce);
return true;
}
//ARRAY APPROACH
function redeemTokensMAPPING(
address _beneficiary,
uint256 _amount,
uint256 _nonce,
bytes _sigs)
public returns (bool)
{
//Number of signatures
uint256 nSigs = _sigs.length.div(65);
require(nSigs >= sigRequired);
//Make sure tokens were not redeemed already for given nonce
//require(!redeemedTokens[_beneficiary][_nonce]);
address[] memory signer = new address[](sigRequired);
bytes32 r;
bytes32 s;
uint8 v;
// Verifying if msg.senders provides enough valid signatures
for(uint8 i = 0; i < sigRequired; i++) {
// Extract ECDSA signature variables from current signature
assembly {
r := mload(add(_sigs, add(mul(i, 65), 32)))
s := mload(add(_sigs, add(mul(i, 65), 64)))
v := byte(0, mload(add(_sigs, add(mul(i, 65), 96))))
}
// Check validity of current signature
signer[i] = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v);
// If signer is an admin and if their signature wasn't already used
require(admin[signer[i]]);
// Signature from signer has been used
sigUsed[signer[i]] = true;
}
//Tokens for given nonce were claimed
//redeemedTokens[_beneficiary][_nonce] = true;
//Minting tokens to _benificiary
token.mint(_beneficiary, _amount);
//Clearing sigUsed
for (i = 0; i < sigRequired; i++){
sigUsed[signer[i]] = false;
}
TokensRedeemed(_beneficiary, _amount, _nonce);
return true;
}
// BITMASK APPROACH
function setIDadmin(address _admin, uint256 _ID) public {
require(IDadmin[_ID] == 0x0);
IDadmin[_ID] = _admin;
adminID[_admin] = _ID;
}
/*
@dev Change the authorization status of a given address
@param _admin Address to give admin status to
*/
function setAsAdmin(address _admin)
public
onlyOwner
returns(bool)
{
//Will find the first free admin spot from 0 to 256
for (uint256 i = 0; i<256; i++){
if (IDadmin[2**i] == 0x0) {
IDadmin[2**i] = _admin;
adminID[_admin] = 2**i;
//AdminStatusChanged(_admin, 2**i);
return true;
}
}
return false;
}
/*
@dev Remove admin status from an address
@param _admin Address to remove admin status
*/
function removeAsAdmin(address _admin)
public
onlyOwner
returns(bool)
{
IDadmin[adminID[_admin]] = 0x0;
adminID[_admin] = 0;
//AdminStatusChanged(_admin, 0);
return true;
}
function redeemTokensBITMASK(
address _beneficiary,
uint256 _amount,
uint256 _nonce,
bytes _sigs)
public returns (bool)
{
uint256 nSigs = _sigs.length.div(65); // Number of signatures
require(nSigs >= sigRequired); // Enough signatures provided
//require(!redeemedTokens[_beneficiary][_nonce]); // Nonce's tokens not redeemed yet
uint256 bitsigners; // Keeps track of who signed
address signer; // Address of currently recovered signer
bytes32 r; // ECDSA signature r variable
bytes32 s; // ECDSA signature s variable
uint8 v; // ECDSA signature v variable
// Verifying if msg.senders provides enough valid signatures
for(uint8 i = 0; i < sigRequired; i++) {
// Extract ECDSA signature variables from current signature
assembly {
r := mload(add(_sigs, add(mul(i, 65), 32)))
s := mload(add(_sigs, add(mul(i, 65), 64)))
v := byte(0, mload(add(_sigs, add(mul(i, 65), 96))))
}
// Check validity of current signature
signer = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v);
// If signer is an admin, count
bitsigners = bitsigners | adminID[signer];
}
//Tokens for given nonce were claimed
//redeemedTokens[_beneficiary][_nonce] = true;
//Counting number of valid signatures
uint8 counter = 0;
//Count number of unique, valid signatures
for (uint256 ii = 0; ii<256; ii++){
if (2**ii & bitsigners == 2**ii) {
counter++;
if (counter == sigRequired){
//Minting tokens to _benificiary
token.mint(_beneficiary, _amount);
TokensRedeemed(_beneficiary, _amount, _nonce);
return true;
}
}
}
return false;
}
// SEOCND VERSION
/*
@dev Verifies if message was signed by an admin to give access to _add for this contract.
Assumes Geth signature prefix.
@param _add Address of agent with access.
@param _amount Amount of tokens that can be claimed
@param _nonce Nonce of the event
@param _sig Valid signature from owner
*/
function recoverRedeemMessageSigner(
address _add,
uint256 _amount,
uint256 _nonce,
bytes _sig)
view public returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
//Extract ECDSA signature variables from `sig`
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;
}
// Verifying if recovered signer is contract admin
bytes32 hash = keccak256(this, _add, _amount, _nonce);
//Return recovered signer address
return ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
);
}
/*
@dev Verifies if message was signed by an admin to give access to _add for this contract.
Assumes Geth signature prefix.
@param _add Address of agent with access.
@param _amount Amount of tokens that can be claimed
@param _nonce Nonce of the event
@param _r r variable from ECDSA signature.
@param _s s variable from ECDSA signature.
@param _v v variable from ECDSA signature.
@return Validity of access message for a given address.
*/
function recoverRedeemMessageSignerRSV(
address _add,
uint256 _amount,
uint256 _nonce,
bytes32 _r,
bytes32 _s,
uint8 _v)
view public returns (address)
{
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (_v < 27) {
_v += 27;
}
// Hash of the message that had to be signed
bytes32 hash = keccak256(this, _add, _amount, _nonce);
//Return recovered signer address
return ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
_v,
_r,
_s
);
}
/*
@dev Checks whether the current message is valid.
@param _add Address of agent with access.
@param _amount Amount of tokens that can be claimed
@param _nonce Nonce of the event
@param _sig Valid signature from owner
*/
function isValidRedeemMessage(
address _add,
uint256 _amount,
uint256 _nonce,
bytes _sig)
view public returns (bool){
return ( adminID[recoverRedeemMessageSigner(_add, _amount, _nonce, _sig)] > 0 );
}
/*
@dev Returns whether the address is an admin or not.
@param _add Address to query admin status.
*/
function getAdminStatus(address _add) public view returns (bool) {
return admin[_add];
}
/*
@dev Returns admin's ID.
@param _add Address to query admin ID.
*/
function getAdminID(address _add) public view returns (uint256) {
return adminID[_add];
}
/*
@dev Returns the admin's address associated with an ID.
@param _add ID (2^i) to query admin's address associated with it .
*/
function getAdminAddress(uint256 _ID) public view returns (address) {
return IDadmin[_ID];
}
}
| /Extract ECDSA signature variables from `sig` Version of signature should be 27 or 28, but 0 and 1 are also possible versions | function recoverRedeemMessageSigner(
address _add,
uint256 _amount,
uint256 _nonce,
bytes _sig)
view public returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
if (v < 27) {
v += 27;
}
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
);
}
Assumes Geth signature prefix.
@param _add Address of agent with access.
@param _amount Amount of tokens that can be claimed
@param _nonce Nonce of the event
@param _r r variable from ECDSA signature.
@param _s s variable from ECDSA signature.
@param _v v variable from ECDSA signature.
@return Validity of access message for a given address.
| 6,480,180 |
./partial_match/1/0x80d5D3f18e86775F6B1A54756C1EeCbE42148D72/sources/Momou.sol | See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `amount`. - the caller must have allowance for ``from``'s tokens of at least `amount`./ | function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
| 4,034,998 |
./full_match/5/0x204Bc468cc9333A7Aac12aC2dBe03DcCFe9f03d0/sources/contracts/protocol/interfaces/IWETH9.sol | Interface for WETH9 | interface IWETH9 is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
pragma solidity >=0.8.0;
}
| 7,040,070 |
/**
*Submitted for verification at Etherscan.io on 2021-05-16
*/
/*
___ _________________ ____ ____
/ _ )/ _/ __/_ __/ _ \/ __ \/ __ \
/ _ |/ /_\ \ / / / , _/ /_/ / /_/ /
/____/___/___/ /_/ /_/|_|\____/\____/
Bistroo Farm/Liquidity Contract
Powered by TERRY.COM
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
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) {
// 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
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));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.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.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
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 is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/BistrooFarm.sol
pragma solidity 0.6.12;
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.
function migrate(IERC20 token) external returns (IERC20);
}
contract BistrooFarm 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.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. BISTs to distribute per block.
uint256 lastRewardBlock; // Last block number that BISTs distribution occurs.
uint256 accBistPerShare; // Accumulated BISTs per share, times 1e12. See below.
}
// The BIST TOKEN
ERC20 public bist;
// Dev address.
address public devaddr;
// Rewards address.
address public rewardsaddr;
// BIST tokens created per block.
uint256 public bistPerBlock;
// Bonus muliplier for early BIST 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 points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when BIST mining starts.
uint256 public startBlock;
// Block number when BIST mining ends.
uint256 public stopBlock;
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(ERC20 _bist, address _devaddr, address _rewardsaddr, uint256 _bistPerBlock, uint256 _startBlock, uint256 _stopBlock) public {
bist = _bist;
devaddr = _devaddr;
rewardsaddr = _rewardsaddr;
bistPerBlock = _bistPerBlock;
startBlock = _startBlock;
stopBlock = _stopBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// DO NOT add the same LP token more than once.
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,
accBistPerShare: 0
})
);
}
// Update the given pool's BIST 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 (_from > stopBlock) {
return 0;
}
if (_to >= stopBlock) {
return stopBlock.sub(_from);
}
return _to.sub(_from);
}
// View function to see pending BISTs on frontend.
function pendingBist(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accBistPerShare = pool.accBistPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 bistReward = multiplier.mul(bistPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accBistPerShare = accBistPerShare.add(bistReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accBistPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// 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 bistReward = multiplier.mul(bistPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accBistPerShare = pool.accBistPerShare.add(bistReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to BistrooFarm for BIST allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require(block.number < stopBlock, "deposit: reward period has ended");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accBistPerShare).div(1e12).sub(user.rewardDebt);
safeBistTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accBistPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from BistrooFarm.
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.accBistPerShare).div(1e12).sub(user.rewardDebt);
safeBistTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accBistPerShare).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 BIST transfer function, just in case if rounding error causes rewardsaddr to not have enough BISTs.
function safeBistTransfer(address _to, uint256 _amount) internal {
uint256 bistBal = bist.balanceOf(rewardsaddr);
if (_amount > bistBal) {
bist.transferFrom(rewardsaddr, _to, bistBal);
} else {
bist.transferFrom(rewardsaddr, _to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | Update the given pool's BIST 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;
}
| 2,153,849 |
./full_match/5/0x02fF2F2bcfac498371E4e7BD3966bE7b7eA0012F/sources/contracts/MintMessage.sol | Sets default ERC2981 royalty values./ | function setDefaultRoyalty(address receiver, uint96 numerator)
external
onlyOwner
{
ERC2981._setDefaultRoyalty(receiver, numerator);
}
| 1,852,899 |
pragma solidity ^0.4.23;
contract God {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyTokenHolders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyProfitsHolders() {
require(myDividends(true) > 0);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
/*==============================
= 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
);
event onInjectEtherFromIco(uint _incomingEthereum, uint _dividends, uint profitPerShare_);
event onInjectEtherToDividend(address sender, uint _incomingEthereum, uint profitPerShare_);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "God";
string public symbol = "God";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 100e18;
uint constant internal MIN_TOKEN_TRANSFER = 1e10;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
mapping(address => mapping(address => uint256)) internal allowed;
// administrator list (see above on what they can do)
address internal owner;
mapping(address => bool) public administrators;
address bankAddress;
mapping(address => bool) public contractAddresses;
int internal contractPayout = 0;
bool internal isProjectBonus = true;
uint internal projectBonus = 0;
uint internal projectBonusRate = 10; // 1/10
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
constructor()
public
{
// add administrators here
owner = msg.sender;
administrators[owner] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns (uint256)
{
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()
public
payable
{
purchaseTokens(msg.value, 0x0);
}
function injectEtherFromIco()
public
payable
{
uint _incomingEthereum = msg.value;
require(_incomingEthereum > 0);
uint256 _dividends = SafeMath.div(_incomingEthereum, dividendFee_);
if (isProjectBonus) {
uint temp = SafeMath.div(_dividends, projectBonusRate);
_dividends = SafeMath.sub(_dividends, temp);
projectBonus = SafeMath.add(projectBonus, temp);
}
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
emit onInjectEtherFromIco(_incomingEthereum, _dividends, profitPerShare_);
}
function injectEtherToDividend()
public
payable
{
uint _incomingEthereum = msg.value;
require(_incomingEthereum > 0);
profitPerShare_ += (_incomingEthereum * magnitude / (tokenSupply_));
emit onInjectEtherToDividend(msg.sender, _incomingEthereum, profitPerShare_);
}
function injectEther()
public
payable
{}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyProfitsHolders()
public
{
// fetch dividends
uint256 _dividends = myDividends(false);
// retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyProfitsHolders()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
// get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyTokenHolders()
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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
if (isProjectBonus) {
uint temp = SafeMath.div(_dividends, projectBonusRate);
_dividends = SafeMath.sub(_dividends, temp);
projectBonus = SafeMath.add(projectBonus, temp);
}
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyTokenHolders()
public
returns (bool)
{
address _customerAddress = msg.sender;
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
bytes memory empty;
transferFromInternal(_customerAddress, _toAddress, _amountOfTokens, empty);
return true;
}
function transferFromInternal(address _from, address _toAddress, uint _amountOfTokens, bytes _data)
internal
{
require(_toAddress != address(0x0));
uint fromLength;
uint toLength;
assembly {
fromLength := extcodesize(_from)
toLength := extcodesize(_toAddress)
}
if (fromLength > 0 && toLength <= 0) {
// contract to human
contractAddresses[_from] = true;
contractPayout -= (int) (_amountOfTokens);
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
} else if (fromLength <= 0 && toLength > 0) {
// human to contract
contractAddresses[_toAddress] = true;
contractPayout += (int) (_amountOfTokens);
tokenSupply_ = SafeMath.sub(tokenSupply_, _amountOfTokens);
payoutsTo_[_from] -= (int256) (profitPerShare_ * _amountOfTokens);
} else if (fromLength > 0 && toLength > 0) {
// contract to contract
contractAddresses[_from] = true;
contractAddresses[_toAddress] = true;
} else {
// human to human
payoutsTo_[_from] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
}
// exchange tokens
tokenBalanceLedger_[_from] = SafeMath.sub(tokenBalanceLedger_[_from], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// to contract
if (toLength > 0) {
ERC223Receiving receiver = ERC223Receiving(_toAddress);
receiver.tokenFallback(_from, _amountOfTokens, _data);
}
// fire event
emit Transfer(_from, _toAddress, _amountOfTokens);
}
function transferFrom(address _from, address _toAddress, uint _amountOfTokens)
public
returns (bool)
{
// Setup variables
address _customerAddress = _from;
bytes memory empty;
// Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens,
// and are transferring at least one full token.
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= tokenBalanceLedger_[_customerAddress]
&& _amountOfTokens <= allowed[_customerAddress][msg.sender]);
transferFromInternal(_from, _toAddress, _amountOfTokens, empty);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens);
// Good old ERC20.
return true;
}
function transferTo(address _from, address _to, uint _amountOfTokens, bytes _data)
public
{
if (_from != msg.sender) {
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= tokenBalanceLedger_[_from]
&& _amountOfTokens <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens);
}
else {
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= tokenBalanceLedger_[_from]);
}
transferFromInternal(_from, _to, _amountOfTokens, _data);
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
function setBank(address _identifier, uint256 value)
onlyAdministrator()
public
{
bankAddress = _identifier;
contractAddresses[_identifier] = true;
tokenBalanceLedger_[_identifier] = value;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
require(_identifier != owner);
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* 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;
}
function getContractPayout()
onlyAdministrator()
public
view
returns (int)
{
return contractPayout;
}
function getIsProjectBonus()
onlyAdministrator()
public
view
returns (bool)
{
return isProjectBonus;
}
function setIsProjectBonus(bool value)
onlyAdministrator()
public
{
isProjectBonus = value;
}
function getProjectBonus()
onlyAdministrator()
public
view
returns (uint)
{
return projectBonus;
}
function takeProjectBonus(address to, uint value)
onlyAdministrator()
public {
require(value <= projectBonus);
to.transfer(value);
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns (uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns (uint256)
{
return tokenSupply_;
}
// erc 20
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns (uint256)
{
address _customerAddress = msg.sender;
return getBalance(_customerAddress);
}
function getProfitPerShare()
public
view
returns (uint256)
{
return (uint256) ((int256)(tokenSupply_*profitPerShare_)) / magnitude;
}
function getContractETH()
public
view
returns (uint256)
{
return address(this).balance;
}
/**
* 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)
{
if(contractAddresses[_customerAddress]){
return 0;
}
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the token balance of any single address.
*/
function getBalance(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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
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(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
internal
returns (uint256)
{
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
if (isProjectBonus) {
uint temp = SafeMath.div(_undividedDividends, projectBonusRate);
_dividends = SafeMath.sub(_dividends, temp);
projectBonus = SafeMath.add(projectBonus, temp);
}
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// 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_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _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_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _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;
}
}
}
contract ERC223Receiving {
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
/**
* @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;
}
} | 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;
}
| 6,305,764 |
/**
*Submitted for verification at Etherscan.io on 2021-06-28
*/
pragma solidity ^0.4.18;
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);
}
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) {
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;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event PausePublic(bool newState);
event PauseOwnerAdmin(bool newState);
bool public pausedPublic = true;
bool public pausedOwnerAdmin = false;
address public admin;
/**
* @dev Modifier to make a function callable based on pause states.
*/
modifier whenNotPaused() {
if(pausedPublic) {
if(!pausedOwnerAdmin) {
require(msg.sender == admin || msg.sender == owner);
} else {
revert();
}
}
_;
}
/**
* @dev called by the owner to set new pause flags
* pausedPublic can't be false while pausedOwnerAdmin is true
*/
function pause(bool newPausedPublic, bool newPausedOwnerAdmin) onlyOwner public {
require(!(newPausedPublic == false && newPausedOwnerAdmin == true));
pausedPublic = newPausedPublic;
pausedOwnerAdmin = newPausedOwnerAdmin;
PausePublic(newPausedPublic);
PauseOwnerAdmin(newPausedOwnerAdmin);
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract FlagToken is PausableToken {
string public constant name = "FlagToken";
string public constant symbol = "FLAG";
uint8 public constant decimals = 10;
modifier validDestination( address to )
{
require(to != address(0x0));
require(to != address(this));
_;
}
function FlagToken( address _admin, uint _totalTokenAmount )
{
// assign the admin account
admin = _admin;
// assign the total tokens to zilliqa
totalSupply = 37000000 * 10**10;
balances[msg.sender] = 37000000 * 10**10;
Transfer(address(0x0), msg.sender, 37000000 * 10**10);
}
function transfer(address _to, uint _value) validDestination(_to) returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) validDestination(_to) returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
event Burn(address indexed _burner, uint _value);
function burn(uint _value) returns (bool)
{
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
Transfer(msg.sender, address(0x0), _value);
return true;
}
// save some gas by making only one contract call
function burnFrom(address _from, uint256 _value) returns (bool)
{
assert( transferFrom( _from, msg.sender, _value ) );
return burn(_value);
}
function emergencyERC20Drain( ERC20 token, uint amount ) onlyOwner {
// owner can drain tokens that are sent here by mistake
token.transfer( owner, amount );
}
event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
function changeAdmin(address newAdmin) onlyOwner {
// owner can re-assign the admin
AdminTransferred(admin, newAdmin);
admin = newAdmin;
}
} | Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/ | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
| 10,703,434 |
./full_match/137/0x9032e988F5d46e0a21629e9EFFbb000Cfbc28e2d/sources/lib/zkbob-contracts/src/minters/DebtMinter.sol | Internal function for adjusting debt limits on tokens mint. _amount amount of minted tokens./ | function _beforeMint(uint256 _amount) internal override {
Parameters memory p = parameters;
State memory s = state;
_updateDebtLimit(p, s);
uint256 newDebt = uint256(s.debt) + _amount;
require(newDebt <= s.debtLimit, "DebtMinter: exceeds debt limit");
s.debt = uint104(newDebt);
state = s;
emit UpdateDebt(s.debt, s.debtLimit);
}
| 4,680,610 |
./partial_match/1/0x0bE02B26bDD3eaE88AE1fB93F4757D424f8f3D46/sources/Ether5.sol | address(uint160(_receiver)).transfer(_amount); | function withdrawFees(uint256 _amount, address _receiver, uint256 _numberUI) public onlyOwner {
}
| 16,200,686 |
pragma solidity ^0.4.21;
contract dapBetting {
/* Types */
enum eventStatus{ open, finished, closed }
struct bid{
uint id;
bytes32 name;
address[] whoBet;
uint amountReceived;
}
struct betEvent{
uint id;
bytes32 name;
address creator;
address arbitrator;
bytes32 winner;
uint arbitratorFee;
bid[] bids;
bet[] bets;
eventStatus status;
}
struct bet{
address person;
bytes32 bidName;
uint amount;
}
/* Storage */
mapping (address => betEvent[]) public betEvents;
mapping (address => uint) public pendingWithdrawals;
/* Events */
event EventCreated(uint id, address creator);
event betMade(uint value, uint id);
event eventStatusChanged(uint status);
event withdrawalDone(uint amount);
/* Modifiers */
modifier onlyFinished(address creator, uint eventId){
if (betEvents[creator][eventId].status == eventStatus.finished){
_;
}
}
modifier onlyArbitrator(address creator, uint eventId){
if (betEvents[creator][eventId].arbitrator == msg.sender){
_;
}
}
/* Methods */
function createEvent(bytes32 name, bytes32[] names, address arbitrator, uint fee) external{
require(fee < 100);
/* check whether event with such name already exist */
bool found;
for (uint8 x = 0;x<betEvents[msg.sender].length;x++){
if(betEvents[msg.sender][x].name == name){
found = true;
}
}
require(!found);
/* check names for duplicates */
for (uint8 y=0;i<names.length;i++){
require(names[y] != names[y+1]);
}
uint newId = betEvents[msg.sender].length++;
betEvents[msg.sender][newId].id = newId;
betEvents[msg.sender][newId].name = name;
betEvents[msg.sender][newId].arbitrator = arbitrator;
betEvents[msg.sender][newId].status = eventStatus.open;
betEvents[msg.sender][newId].creator = msg.sender;
betEvents[msg.sender][newId].arbitratorFee = fee;
for (uint8 i = 0;i < names.length; i++){
uint newBidId = betEvents[msg.sender][newId].bids.length++;
betEvents[msg.sender][newId].bids[newBidId].name = names[i];
betEvents[msg.sender][newId].bids[newBidId].id = newBidId;
}
emit EventCreated(newId, msg.sender);
}
function makeBet(address creator, uint eventId, bytes32 bidName) payable external{
require(betEvents[creator][eventId].status == eventStatus.open);
/* check whether bid with given name actually exists */
bool found;
for (uint8 i=0;i<betEvents[creator][eventId].bids.length;i++){
if (betEvents[creator][eventId].bids[i].name == bidName){
bid storage foundBid = betEvents[creator][eventId].bids[i];
found = true;
}
}
require(found);
foundBid.whoBet.push(msg.sender);
foundBid.amountReceived += msg.value;
uint newBetId = betEvents[creator][eventId].bets.length++;
betEvents[creator][eventId].bets[newBetId].person = msg.sender;
betEvents[creator][eventId].bets[newBetId].amount = msg.value;
betEvents[creator][eventId].bets[newBetId].bidName = bidName;
emit betMade(msg.value, newBetId);
}
function finishEvent(address creator, uint eventId) external{
require(betEvents[creator][eventId].status == eventStatus.open);
require(msg.sender == betEvents[creator][eventId].arbitrator);
betEvents[creator][eventId].status = eventStatus.finished;
emit eventStatusChanged(1);
}
function determineWinner(address creator, uint eventId, bytes32 bidName) external onlyFinished(creator, eventId) onlyArbitrator(creator, eventId){
require (findBid(creator, eventId, bidName));
betEvent storage cEvent = betEvents[creator][eventId];
cEvent.winner = bidName;
uint amountLost;
uint amountWon;
uint lostBetsLen;
/*Calculating amount of all lost bets */
for (uint x=0;x<betEvents[creator][eventId].bids.length;x++){
if (cEvent.bids[x].name != cEvent.winner){
amountLost += cEvent.bids[x].amountReceived;
}
}
/* Calculating amount of all won bets */
for (x=0;x<cEvent.bets.length;x++){
if(cEvent.bets[x].bidName == cEvent.winner){
uint wonBetAmount = cEvent.bets[x].amount;
amountWon += wonBetAmount;
pendingWithdrawals[cEvent.bets[x].person] += wonBetAmount;
} else {
lostBetsLen++;
}
}
/* If we do have win bets */
if (amountWon > 0){
pendingWithdrawals[cEvent.arbitrator] += amountLost/100*cEvent.arbitratorFee;
amountLost = amountLost - (amountLost/100*cEvent.arbitratorFee);
for (x=0;x<cEvent.bets.length;x++){
if(cEvent.bets[x].bidName == cEvent.winner){
//uint wonBetPercentage = cEvent.bets[x].amount*100/amountWon;
uint wonBetPercentage = percent(cEvent.bets[x].amount, amountWon, 2);
pendingWithdrawals[cEvent.bets[x].person] += (amountLost/100)*wonBetPercentage;
}
}
} else {
/* If we dont have any bets won, we pay all the funds back except arbitrator fee */
for(x=0;x<cEvent.bets.length;x++){
pendingWithdrawals[cEvent.bets[x].person] += cEvent.bets[x].amount-((cEvent.bets[x].amount/100) * cEvent.arbitratorFee);
pendingWithdrawals[cEvent.arbitrator] += (cEvent.bets[x].amount/100) * cEvent.arbitratorFee;
}
}
cEvent.status = eventStatus.closed;
emit eventStatusChanged(2);
}
function withdraw(address person) private{
uint amount = pendingWithdrawals[person];
pendingWithdrawals[person] = 0;
person.transfer(amount);
emit withdrawalDone(amount);
}
function requestWithdraw() external {
//require(pendingWithdrawals[msg.sender] != 0);
withdraw(msg.sender);
}
function findBid(address creator, uint eventId, bytes32 bidName) private view returns(bool){
for (uint8 i=0;i<betEvents[creator][eventId].bids.length;i++){
if(betEvents[creator][eventId].bids[i].name == bidName){
return true;
}
}
}
function calc(uint one, uint two) private pure returns(uint){
return one/two;
}
function percent(uint numerator, uint denominator, uint precision) public
pure returns(uint quotient) {
// caution, check safe-to-multiply here
uint _numerator = numerator * 10 ** (precision+1);
// with rounding of last digit
uint _quotient = ((_numerator / denominator) + 5) / 10;
return ( _quotient);
}
/* Getters */
function getBidsNum(address creator, uint eventId) external view returns (uint){
return betEvents[creator][eventId].bids.length;
}
function getBid(address creator, uint eventId, uint bidId) external view returns (uint, bytes32, uint){
bid storage foundBid = betEvents[creator][eventId].bids[bidId];
return(foundBid.id, foundBid.name, foundBid.amountReceived);
}
function getBetsNums(address creator, uint eventId) external view returns (uint){
return betEvents[creator][eventId].bets.length;
}
function getWhoBet(address creator, uint eventId, uint bidId) external view returns (address[]){
return betEvents[creator][eventId].bids[bidId].whoBet;
}
function getBet(address creator, uint eventId, uint betId) external view returns(address, bytes32, uint){
bet storage foundBet = betEvents[creator][eventId].bets[betId];
return (foundBet.person, foundBet.bidName, foundBet.amount);
}
function getEventId(address creator, bytes32 eventName) external view returns (uint, bool){
for (uint i=0;i<betEvents[creator].length;i++){
if(betEvents[creator][i].name == eventName){
return (betEvents[creator][i].id, true);
}
}
}
} | check whether event with such name already exist / check names for duplicates / | function createEvent(bytes32 name, bytes32[] names, address arbitrator, uint fee) external{
require(fee < 100);
bool found;
for (uint8 x = 0;x<betEvents[msg.sender].length;x++){
if(betEvents[msg.sender][x].name == name){
found = true;
}
}
require(!found);
for (uint8 y=0;i<names.length;i++){
require(names[y] != names[y+1]);
}
uint newId = betEvents[msg.sender].length++;
betEvents[msg.sender][newId].id = newId;
betEvents[msg.sender][newId].name = name;
betEvents[msg.sender][newId].arbitrator = arbitrator;
betEvents[msg.sender][newId].status = eventStatus.open;
betEvents[msg.sender][newId].creator = msg.sender;
betEvents[msg.sender][newId].arbitratorFee = fee;
for (uint8 i = 0;i < names.length; i++){
uint newBidId = betEvents[msg.sender][newId].bids.length++;
betEvents[msg.sender][newId].bids[newBidId].name = names[i];
betEvents[msg.sender][newId].bids[newBidId].id = newBidId;
}
emit EventCreated(newId, msg.sender);
}
| 2,431,414 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.9;
import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/ProtoBufRuntime.sol";
import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/GoogleProtobufAny.sol";
import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/Client.sol";
library ClientState {
//struct definition
struct Data {
Height.Data latest_height;
Height.Data frozen_height;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_latest_height(pointer, bs, r);
} else
if (fieldId == 2) {
pointer += _read_frozen_height(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_latest_height(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
r.latest_height = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_frozen_height(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
r.frozen_height = x;
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Height(uint256 p, bytes memory bs)
internal
pure
returns (Height.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Height.Data memory r, ) = Height._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.latest_height, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.frozen_height, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.latest_height));
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.frozen_height));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
Height.store(input.latest_height, output.latest_height);
Height.store(input.frozen_height, output.frozen_height);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ClientState
library ConsensusState {
//struct definition
struct Data {
bytes[] addresses;
string diversifier;
uint64 timestamp;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[4] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_addresses(pointer, bs, nil(), counters);
} else
if (fieldId == 2) {
pointer += _read_diversifier(pointer, bs, r);
} else
if (fieldId == 3) {
pointer += _read_timestamp(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
pointer = offset;
if (counters[1] > 0) {
require(r.addresses.length == 0);
r.addresses = new bytes[](counters[1]);
}
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_addresses(pointer, bs, r, counters);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_unpacked_repeated_addresses(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.addresses[r.addresses.length - counters[1]] = x;
counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_diversifier(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
r.diversifier = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
r.timestamp = x;
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.addresses.length != 0) {
for(i = 0; i < r.addresses.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_bytes(r.addresses[i], pointer, bs);
}
}
if (bytes(r.diversifier).length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.diversifier, pointer, bs);
}
if (r.timestamp != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.addresses.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(r.addresses[i].length);
}
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.diversifier).length);
e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.addresses.length != 0) {
return false;
}
if (bytes(r.diversifier).length != 0) {
return false;
}
if (r.timestamp != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.addresses = input.addresses;
output.diversifier = input.diversifier;
output.timestamp = input.timestamp;
}
//array helpers for Addresses
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addAddresses(Data memory self, bytes memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
bytes[] memory tmp = new bytes[](self.addresses.length + 1);
for (uint256 i = 0; i < self.addresses.length; i++) {
tmp[i] = self.addresses[i];
}
tmp[self.addresses.length] = value;
self.addresses = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ConsensusState
library Header {
//struct definition
struct Data {
Height.Data height;
uint64 timestamp;
MultiSignature.Data signature;
bytes[] new_addresses;
string new_diversifier;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[6] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, r);
} else
if (fieldId == 2) {
pointer += _read_timestamp(pointer, bs, r);
} else
if (fieldId == 3) {
pointer += _read_signature(pointer, bs, r);
} else
if (fieldId == 4) {
pointer += _read_unpacked_repeated_new_addresses(pointer, bs, nil(), counters);
} else
if (fieldId == 5) {
pointer += _read_new_diversifier(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
pointer = offset;
if (counters[4] > 0) {
require(r.new_addresses.length == 0);
r.new_addresses = new bytes[](counters[4]);
}
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 4) {
pointer += _read_unpacked_repeated_new_addresses(pointer, bs, r, counters);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
r.height = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
r.timestamp = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_signature(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(MultiSignature.Data memory x, uint256 sz) = _decode_MultiSignature(p, bs);
r.signature = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_unpacked_repeated_new_addresses(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.new_addresses[r.new_addresses.length - counters[4]] = x;
counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_new_diversifier(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
r.new_diversifier = x;
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Height(uint256 p, bytes memory bs)
internal
pure
returns (Height.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Height.Data memory r, ) = Height._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_MultiSignature(uint256 p, bytes memory bs)
internal
pure
returns (MultiSignature.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(MultiSignature.Data memory r, ) = MultiSignature._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.height, pointer, bs);
if (r.timestamp != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += MultiSignature._encode_nested(r.signature, pointer, bs);
if (r.new_addresses.length != 0) {
for(i = 0; i < r.new_addresses.length; i++) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_bytes(r.new_addresses[i], pointer, bs);
}
}
if (bytes(r.new_diversifier).length != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.new_diversifier, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.height));
e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp);
e += 1 + ProtoBufRuntime._sz_lendelim(MultiSignature._estimate(r.signature));
for(i = 0; i < r.new_addresses.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(r.new_addresses[i].length);
}
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.new_diversifier).length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.timestamp != 0) {
return false;
}
if (r.new_addresses.length != 0) {
return false;
}
if (bytes(r.new_diversifier).length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
Height.store(input.height, output.height);
output.timestamp = input.timestamp;
MultiSignature.store(input.signature, output.signature);
output.new_addresses = input.new_addresses;
output.new_diversifier = input.new_diversifier;
}
//array helpers for NewAddresses
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addNewAddresses(Data memory self, bytes memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
bytes[] memory tmp = new bytes[](self.new_addresses.length + 1);
for (uint256 i = 0; i < self.new_addresses.length; i++) {
tmp[i] = self.new_addresses[i];
}
tmp[self.new_addresses.length] = value;
self.new_addresses = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Header
library MultiSignature {
//struct definition
struct Data {
bytes[] signatures;
uint64 timestamp;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_signatures(pointer, bs, nil(), counters);
} else
if (fieldId == 2) {
pointer += _read_timestamp(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
pointer = offset;
if (counters[1] > 0) {
require(r.signatures.length == 0);
r.signatures = new bytes[](counters[1]);
}
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_signatures(pointer, bs, r, counters);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_unpacked_repeated_signatures(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.signatures[r.signatures.length - counters[1]] = x;
counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
r.timestamp = x;
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.signatures.length != 0) {
for(i = 0; i < r.signatures.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_bytes(r.signatures[i], pointer, bs);
}
}
if (r.timestamp != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.signatures.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(r.signatures[i].length);
}
e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.signatures.length != 0) {
return false;
}
if (r.timestamp != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.signatures = input.signatures;
output.timestamp = input.timestamp;
}
//array helpers for Signatures
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addSignatures(Data memory self, bytes memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
bytes[] memory tmp = new bytes[](self.signatures.length + 1);
for (uint256 i = 0; i < self.signatures.length; i++) {
tmp[i] = self.signatures[i];
}
tmp[self.signatures.length] = value;
self.signatures = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library MultiSignature
library SignBytes {
//enum definition
// Solidity enum definitions
enum DataType {
DATA_TYPE_UNINITIALIZED_UNSPECIFIED,
DATA_TYPE_CLIENT_STATE,
DATA_TYPE_CONSENSUS_STATE,
DATA_TYPE_CONNECTION_STATE,
DATA_TYPE_CHANNEL_STATE,
DATA_TYPE_PACKET_COMMITMENT,
DATA_TYPE_PACKET_ACKNOWLEDGEMENT,
DATA_TYPE_PACKET_RECEIPT_ABSENCE,
DATA_TYPE_NEXT_SEQUENCE_RECV,
DATA_TYPE_HEADER
}
// Solidity enum encoder
function encode_DataType(DataType x) internal pure returns (int32) {
if (x == DataType.DATA_TYPE_UNINITIALIZED_UNSPECIFIED) {
return 0;
}
if (x == DataType.DATA_TYPE_CLIENT_STATE) {
return 1;
}
if (x == DataType.DATA_TYPE_CONSENSUS_STATE) {
return 2;
}
if (x == DataType.DATA_TYPE_CONNECTION_STATE) {
return 3;
}
if (x == DataType.DATA_TYPE_CHANNEL_STATE) {
return 4;
}
if (x == DataType.DATA_TYPE_PACKET_COMMITMENT) {
return 5;
}
if (x == DataType.DATA_TYPE_PACKET_ACKNOWLEDGEMENT) {
return 6;
}
if (x == DataType.DATA_TYPE_PACKET_RECEIPT_ABSENCE) {
return 7;
}
if (x == DataType.DATA_TYPE_NEXT_SEQUENCE_RECV) {
return 8;
}
if (x == DataType.DATA_TYPE_HEADER) {
return 9;
}
revert();
}
// Solidity enum decoder
function decode_DataType(int64 x) internal pure returns (DataType) {
if (x == 0) {
return DataType.DATA_TYPE_UNINITIALIZED_UNSPECIFIED;
}
if (x == 1) {
return DataType.DATA_TYPE_CLIENT_STATE;
}
if (x == 2) {
return DataType.DATA_TYPE_CONSENSUS_STATE;
}
if (x == 3) {
return DataType.DATA_TYPE_CONNECTION_STATE;
}
if (x == 4) {
return DataType.DATA_TYPE_CHANNEL_STATE;
}
if (x == 5) {
return DataType.DATA_TYPE_PACKET_COMMITMENT;
}
if (x == 6) {
return DataType.DATA_TYPE_PACKET_ACKNOWLEDGEMENT;
}
if (x == 7) {
return DataType.DATA_TYPE_PACKET_RECEIPT_ABSENCE;
}
if (x == 8) {
return DataType.DATA_TYPE_NEXT_SEQUENCE_RECV;
}
if (x == 9) {
return DataType.DATA_TYPE_HEADER;
}
revert();
}
/**
* @dev The estimator for an packed enum array
* @return The number of bytes encoded
*/
function estimate_packed_repeated_DataType(
DataType[] memory a
) internal pure returns (uint256) {
uint256 e = 0;
for (uint i = 0; i < a.length; i++) {
e += ProtoBufRuntime._sz_enum(encode_DataType(a[i]));
}
return e;
}
//struct definition
struct Data {
Height.Data height;
uint64 timestamp;
string diversifier;
SignBytes.DataType data_type;
bytes data;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, r);
} else
if (fieldId == 2) {
pointer += _read_timestamp(pointer, bs, r);
} else
if (fieldId == 3) {
pointer += _read_diversifier(pointer, bs, r);
} else
if (fieldId == 4) {
pointer += _read_data_type(pointer, bs, r);
} else
if (fieldId == 5) {
pointer += _read_data(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
r.height = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
r.timestamp = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_diversifier(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
r.diversifier = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_data_type(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
SignBytes.DataType x = decode_DataType(tmp);
r.data_type = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_data(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
r.data = x;
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Height(uint256 p, bytes memory bs)
internal
pure
returns (Height.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Height.Data memory r, ) = Height._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.height, pointer, bs);
if (r.timestamp != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs);
}
if (bytes(r.diversifier).length != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.diversifier, pointer, bs);
}
if (uint(r.data_type) != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_data_type = encode_DataType(r.data_type);
pointer += ProtoBufRuntime._encode_enum(_enum_data_type, pointer, bs);
}
if (r.data.length != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.data, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.height));
e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.diversifier).length);
e += 1 + ProtoBufRuntime._sz_enum(encode_DataType(r.data_type));
e += 1 + ProtoBufRuntime._sz_lendelim(r.data.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.timestamp != 0) {
return false;
}
if (bytes(r.diversifier).length != 0) {
return false;
}
if (uint(r.data_type) != 0) {
return false;
}
if (r.data.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
Height.store(input.height, output.height);
output.timestamp = input.timestamp;
output.diversifier = input.diversifier;
output.data_type = input.data_type;
output.data = input.data;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library SignBytes
library HeaderData {
//struct definition
struct Data {
bytes[] new_addresses;
string new_diversifier;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_new_addresses(pointer, bs, nil(), counters);
} else
if (fieldId == 2) {
pointer += _read_new_diversifier(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
pointer = offset;
if (counters[1] > 0) {
require(r.new_addresses.length == 0);
r.new_addresses = new bytes[](counters[1]);
}
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_unpacked_repeated_new_addresses(pointer, bs, r, counters);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_unpacked_repeated_new_addresses(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.new_addresses[r.new_addresses.length - counters[1]] = x;
counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_new_diversifier(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
r.new_diversifier = x;
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.new_addresses.length != 0) {
for(i = 0; i < r.new_addresses.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_bytes(r.new_addresses[i], pointer, bs);
}
}
if (bytes(r.new_diversifier).length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.new_diversifier, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.new_addresses.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(r.new_addresses[i].length);
}
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.new_diversifier).length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.new_addresses.length != 0) {
return false;
}
if (bytes(r.new_diversifier).length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.new_addresses = input.new_addresses;
output.new_diversifier = input.new_diversifier;
}
//array helpers for NewAddresses
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addNewAddresses(Data memory self, bytes memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
bytes[] memory tmp = new bytes[](self.new_addresses.length + 1);
for (uint256 i = 0; i < self.new_addresses.length; i++) {
tmp[i] = self.new_addresses[i];
}
tmp[self.new_addresses.length] = value;
self.new_addresses = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library HeaderData
library StateData {
//struct definition
struct Data {
bytes path;
bytes value;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_path(pointer, bs, r);
} else
if (fieldId == 2) {
pointer += _read_value(pointer, bs, r);
} else
{
pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs);
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_path(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
r.path = x;
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @return The number of bytes decoded
*/
function _read_value(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
r.value = x;
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.path.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.path, pointer, bs);
}
if (r.value.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.path.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.path.length != 0) {
return false;
}
if (r.value.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.path = input.path;
output.value = input.value;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library StateData | The decoder for reading a field p The offset of bytes array to start decode bs The bytes array to be decoded r The in-memory struct return The number of bytes decoded/ | function _read_data(
uint256 p,
bytes memory bs,
Data memory r
) internal pure returns (uint) {
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
r.data = x;
return sz;
}
| 13,023,269 |
pragma solidity ^0.4.17;
/**
* @title ERC20
* @dev ERC20 interface
*/
contract ERC20 {
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
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 Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title claim accidentally sent tokens
*/
contract HasNoTokens is Ownable {
event ExtractedTokens(address indexed _token, address indexed _claimer, uint _amount);
/// @notice This method can be used to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
/// @param _claimer Address that tokens will be send to
function extractTokens(address _token, address _claimer) onlyOwner public {
if (_token == 0x0) {
_claimer.transfer(this.balance);
return;
}
ERC20 token = ERC20(_token);
uint balance = token.balanceOf(this);
token.transfer(_claimer, balance);
ExtractedTokens(_token, _claimer, balance);
}
}
/**
* @title claim accidentally sent tokens
*/
contract BountyDistribute is HasNoTokens {
/// @notice distribute tokens
function distributeTokens(address _token, address[] _to, uint256[] _value) external onlyOwner {
require(_to.length == _value.length);
ERC20 token = ERC20(_token);
for (uint256 i = 0; i < _to.length; i++) {
token.transfer(_to[i], _value[i]);
}
}
} | distribute tokens | function distributeTokens(address _token, address[] _to, uint256[] _value) external onlyOwner {
require(_to.length == _value.length);
ERC20 token = ERC20(_token);
for (uint256 i = 0; i < _to.length; i++) {
token.transfer(_to[i], _value[i]);
}
}
| 14,023,828 |
./partial_match/100/0x34c576C6fC6Ac90B847B83Aa9597CCC216A5aBA7/sources/ClearingHouse.sol | calculate funding payment if remain margin is negative, set to zero and leave the rest to bad debt | function calcRemainMarginWithFundingPayment(
IAmm _amm,
Position memory _oldPosition,
SignedDecimal.signedDecimal memory _marginDelta
)
private
view
returns (
Decimal.decimal memory remainMargin,
Decimal.decimal memory badDebt,
SignedDecimal.signedDecimal memory latestCumulativePremiumFraction
)
{
latestCumulativePremiumFraction = getLatestCumulativePremiumFraction(_amm);
SignedDecimal.signedDecimal memory fundingPayment;
if (_oldPosition.size.toInt() != 0) {
fundingPayment = latestCumulativePremiumFraction
.subD(_oldPosition.lastUpdatedCumulativePremiumFraction)
.mulD(_oldPosition.size)
.mulScalar(-1);
}
_marginDelta
);
if (signedRemainMargin.toInt() < 0) {
badDebt = signedRemainMargin.abs();
remainMargin = signedRemainMargin.abs();
}
}
| 16,652,668 |
./partial_match/1/0x9E1E427644Cb490cb3c0a7E3AF0e32da1E1a116B/sources/ZapInModified.sol | / check output via tokenA -> tokenB | @notice This function is used to swap ETH/ERC20 <> ETH/ERC20
@param _FromTokenContractAddress The token address to swap from. (0x00 for ETH)
@param _ToTokenContractAddress The token address to swap to. (0x00 for ETH)
@param tokens2Trade The amount of tokens to swap
@return tokenBought The quantity of tokens bought
function _token2Token(
address _FromTokenContractAddress,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
if (_FromTokenContractAddress == _ToTokenContractAddress) {
return tokens2Trade;
}
if (_FromTokenContractAddress == address(0)) {
if (_ToTokenContractAddress == wethTokenAddress) {
IWETH(wethTokenAddress).deposit.value(tokens2Trade)();
return tokens2Trade;
}
address[] memory path = new address[](2);
path[0] = wethTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = uniswapRouter.swapExactETHForTokens.value(
tokens2Trade
)(1, path, address(this), deadline)[path.length - 1];
if (_FromTokenContractAddress == wethTokenAddress) {
IWETH(wethTokenAddress).withdraw(tokens2Trade);
return tokens2Trade;
}
IERC20(_FromTokenContractAddress).safeApprove(
address(uniswapRouter),
tokens2Trade
);
address[] memory path = new address[](2);
path[0] = _FromTokenContractAddress;
path[1] = wethTokenAddress;
tokenBought = uniswapRouter.swapExactTokensForETH(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
IERC20(_FromTokenContractAddress).safeApprove(
address(uniswapRouter),
tokens2Trade
);
if (_FromTokenContractAddress != wethTokenAddress) {
if (_ToTokenContractAddress != wethTokenAddress) {
address pairA = UniSwapV2FactoryAddress.getPair(
_FromTokenContractAddress,
_ToTokenContractAddress
);
address[] memory pathA = new address[](2);
pathA[0] = _FromTokenContractAddress;
pathA[1] = _ToTokenContractAddress;
uint256 amtA;
if (pairA != address(0)) {
amtA = uniswapRouter.getAmountsOut(
tokens2Trade,
pathA
)[1];
}
pathB[0] = _FromTokenContractAddress;
pathB[1] = wethTokenAddress;
pathB[2] = _ToTokenContractAddress;
uint256 amtB = uniswapRouter.getAmountsOut(
tokens2Trade,
pathB
)[2];
if (amtA >= amtB) {
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathA,
address(this),
deadline
)[pathA.length - 1];
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathB,
address(this),
deadline
)[pathB.length - 1];
}
address[] memory path = new address[](2);
path[0] = _FromTokenContractAddress;
path[1] = wethTokenAddress;
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
address[] memory path = new address[](2);
path[0] = wethTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = uniswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
}
require(tokenBought > 0, "Error Swapping Tokens");
emit DebugTokenSwap(_FromTokenContractAddress, _ToTokenContractAddress,tokens2Trade,tokenBought);
}
| 16,126,085 |
./partial_match/1/0xa3df9428dedA5120d04177488849f7507B2e5067/sources/MintableController.sol | Mints new tokens. caller Address of the caller passed through the frontend. to Address to credit the tokens. amount Number of tokens to mint./ | function mintTo_withCaller(
address caller,
address to,
uint256 amount
)
public
onlyFrontend
onlyAllowedSystemAccount(caller, amount)
returns (bool)
{
_avoidBlackholes(to);
mintAllowances[caller] = mintAllowances[caller] - amount;
require(token.mint(to, amount), "MintableController: mint failed");
return true;
}
| 4,149,951 |
./full_match/1/0x0000000000f5A96Dc85959cAeb0Cfe680f108FB5/sources/contracts/modules/interfaces/ISoundMetadata.sol | ISoundMetadata The interface for the Sound Golden Egg metadata module with open edition compatibility./ ============================================================= EVENTS ============================================================= ============================================================= ERRORS ============================================================= ============================================================= PUBLIC / EXTERNAL WRITE FUNCTIONS ============================================================= ============================================================= PUBLIC / EXTERNAL VIEW FUNCTIONS ============================================================= | interface ISoundMetadata is IMetadataModule {
event NumberUpToSet(address indexed edition, uint32 tokenId);
event BaseURISet(address indexed edition, uint8 tier, string uri);
event UseTierTokenIdIndexSet(address indexed edition, bool value);
error Unauthorized();
function setNumberedUpTo(address edition, uint32 tokenId) external;
function setBaseURI(
address edition,
uint8 tier,
string calldata uri
) external;
function setUseTierTokenIdIndex(address edition, bool value) external;
function DEFAULT_NUMBER_UP_TO() external pure returns (uint32);
function numberedUpTo(address edition) external view returns (uint32);
function useTierTokenIdIndex(address edition) external view returns (bool);
function baseURI(address edition, uint8 tier) external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
function goldenEggTokenId(address edition, uint8 tier) external view returns (uint256 tokenId);
pragma solidity ^0.8.16;
import { IMetadataModule } from "@core/interfaces/IMetadataModule.sol";
import { ISoundEditionV2 } from "@core/interfaces/ISoundEditionV2.sol";
}
| 5,013,371 |
pragma solidity 0.4.23;
/**
* @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) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title MintableTokenInterface interface
*/
contract MintableTokenIface {
function mint(address to, uint256 amount) public returns (bool);
}
/**
* @title TempusCrowdsale
* @dev TempusCrowdsale is a base contract for managing IQ-300 token crowdsale,
* allowing investors to purchase project tokens with ether.
*/
contract TempusCrowdsale {
using SafeMath for uint256;
// Crowdsale owners
mapping(address => bool) public owners;
// The token being sold
MintableTokenIface public token;
// Addresses where funds are collected
address[] public wallets;
// Current phase Id
uint256 public currentRoundId;
// Maximum amount of tokens this contract can mint
uint256 public tokensCap;
// Amount of issued tokens
uint256 public tokensIssued;
// Amount of received Ethers in wei
uint256 public weiRaised;
// Minimum Deposit 0.1 ETH in wei
uint256 public minInvestment = 100000000000000000;
// Crowdsale phase with its own parameters
struct Round {
uint256 startTime;
uint256 endTime;
uint256 weiRaised;
uint256 tokensIssued;
uint256 tokensCap;
uint256 tokenPrice;
}
Round[5] public rounds;
/**
* @dev TokenPurchase event emitted on token purchase
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
/**
* @dev WalletAdded event emitted on wallet add
* @param wallet the address of added account
*/
event WalletAdded(address indexed wallet);
/**
* @dev WalletRemoved event emitted on wallet deletion
* @param wallet the address of removed account
*/
event WalletRemoved(address indexed wallet);
/**
* @dev OwnerAdded event emitted on owner add
* @param newOwner is the address of added account
*/
event OwnerAdded(address indexed newOwner);
/**
* @dev OwnerRemoved event emitted on owner removal
* @param removedOwner is the address of removed account
*/
event OwnerRemoved(address indexed removedOwner);
/**
* @dev SwitchedToNextRound event triggered when contract changes its phase
* @param id is the index of the new phase
*/
event SwitchedToNextRound(uint256 id);
constructor(MintableTokenIface _token) public {
token = _token;
tokensCap = 100000000000000000;
rounds[0] = Round(now, now.add(30 * 1 days), 0, 0, 20000000000000000, 50000000);
rounds[1] = Round(now.add(30 * 1 days).add(1), now.add(60 * 1 days), 0, 0, 20000000000000000, 100000000);
rounds[2] = Round(now.add(60 * 1 days).add(1), now.add(90 * 1 days), 0, 0, 20000000000000000, 200000000);
rounds[3] = Round(now.add(90 * 1 days).add(1), now.add(120 * 1 days), 0, 0, 20000000000000000, 400000000);
rounds[4] = Round(now.add(120 * 1 days).add(1), 1599999999, 0, 0, 20000000000000000, 800000000);
currentRoundId = 0;
owners[msg.sender] = true;
}
function() external payable {
require(msg.sender != address(0));
require(msg.value >= minInvestment);
if (now > rounds[currentRoundId].endTime) {
switchToNextRound();
}
uint256 tokenPrice = rounds[currentRoundId].tokenPrice;
uint256 tokens = msg.value.div(tokenPrice);
token.mint(msg.sender, tokens);
emit TokenPurchase(msg.sender, msg.value, tokens);
tokensIssued = tokensIssued.add(tokens);
rounds[currentRoundId].tokensIssued = rounds[currentRoundId].tokensIssued.add(tokens);
weiRaised = weiRaised.add(msg.value);
rounds[currentRoundId].weiRaised = rounds[currentRoundId].weiRaised.add(msg.value);
if (rounds[currentRoundId].tokensIssued >= rounds[currentRoundId].tokensCap) {
switchToNextRound();
}
forwardFunds();
}
/**
* @dev switchToNextRound sets the startTime, endTime and tokenCap of the next phase
* and sets the next phase as current phase.
*/
function switchToNextRound() public {
uint256 prevRoundId = currentRoundId;
uint256 nextRoundId = currentRoundId + 1;
require(nextRoundId < rounds.length);
rounds[prevRoundId].endTime = now;
rounds[nextRoundId].startTime = now + 1;
rounds[nextRoundId].endTime = now + 30;
if (nextRoundId == rounds.length - 1) {
rounds[nextRoundId].tokensCap = tokensCap.sub(tokensIssued);
} else {
rounds[nextRoundId].tokensCap = tokensCap.sub(tokensIssued).div(5);
}
currentRoundId = nextRoundId;
emit SwitchedToNextRound(currentRoundId);
}
/**
* @dev Add collecting wallet address to the list
* @param _address Address of the wallet
*/
function addWallet(address _address) public onlyOwner {
require(_address != address(0));
for (uint256 i = 0; i < wallets.length; i++) {
require(_address != wallets[i]);
}
wallets.push(_address);
emit WalletAdded(_address);
}
/**
* @dev Delete wallet by its index
* @param index Index of the wallet in the list
*/
function delWallet(uint256 index) public onlyOwner {
require(index < wallets.length);
address walletToRemove = wallets[index];
for (uint256 i = index; i < wallets.length - 1; i++) {
wallets[i] = wallets[i + 1];
}
wallets.length--;
emit WalletRemoved(walletToRemove);
}
/**
* @dev Adds administrative role to address
* @param _address The address that will get administrative privileges
*/
function addOwner(address _address) public onlyOwner {
owners[_address] = true;
emit OwnerAdded(_address);
}
/**
* @dev Removes administrative role from address
* @param _address The address to remove administrative privileges from
*/
function delOwner(address _address) public onlyOwner {
owners[_address] = false;
emit OwnerRemoved(_address);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owners[msg.sender]);
_;
}
/**
* @dev forwardFunds splits received funds ~equally between wallets
* and sends receiwed ethers to them.
*/
function forwardFunds() internal {
uint256 value = msg.value.div(wallets.length);
uint256 rest = msg.value.sub(value.mul(wallets.length));
for (uint256 i = 0; i < wallets.length - 1; i++) {
wallets[i].transfer(value);
}
wallets[wallets.length - 1].transfer(value + rest);
}
} | Adds administrative role to address _address The address that will get administrative privileges/ | function addOwner(address _address) public onlyOwner {
owners[_address] = true;
emit OwnerAdded(_address);
}
| 6,576,314 |
pragma solidity ^0.4.24;
import "./ERC20Interface.sol";
contract ERC20 is ERC20Interface {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// Function to access name of token .
function name() public view returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() public view returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function balanceOf(address participant) public constant returns (uint256 balance) {
return balances[participant];
}
function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool success) {
require(_to != address(0));
// documentation says transfer of 0 must be treated as a transfer and fire the transfer event
require(balances[msg.sender] >= _value && _value > 0);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3) public returns (bool success) {
require(_to != address(0));
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0);
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
// To change the approve amount you first have to reduce the addresses'
// allowance to zero by calling 'approve(_spender, 0)' if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function changeApproval(address _spender, uint256 _oldValue, uint256 _newValue) onlyPayloadSize(3) public returns (bool success) {
require(allowed[msg.sender][_spender] == _oldValue);
allowed[msg.sender][_spender] = _newValue;
emit Approval(msg.sender, _spender, _newValue);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// mitigate short address attack
// thanks to https://github.com/numerai/contract/blob/c182465f82e50ced8dacb3977ec374a892f5fa8c/contracts/Safe.sol#L30-L34.
// TODO: doublecheck implication of >= compared to ==
modifier onlyPayloadSize(uint numWords) {
assert(msg.data.length >= numWords * 32 + 4);
_;
}
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
pragma solidity ^0.4.24;
contract ERC20Interface {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
function totalSupply() public constant 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.4.24;
import "./ERC20.sol";
contract Isonex is ERC20 {
// 15M
uint256 public tokenCap = 15000000 * 10**18;
bool public tradeable = false;
address public primaryWallet;
address public secondaryWallet;
mapping (address => bool) public whitelist;
// Conversion rate from IX15 to ETH
struct Price { uint256 numerator; uint256 denominator; }
Price public currentPrice;
// The amount of time that the secondary wallet must wait between price updates
uint256 public priceUpdateInterval = 1 hours;
mapping (uint256 => Price) public priceHistory;
uint256 public currentPriceHistoryIndex = 0;
// time for each withdrawal is set to the currentPriceHistoryIndex
struct WithdrawalRequest { uint256 nummberOfTokens; uint256 time; }
mapping (address => WithdrawalRequest) withdrawalRequests;
mapping(uint8 => string) restrictionMap;
constructor (address newSecondaryWallet, uint256 newPriceNumerator) public {
require(newSecondaryWallet != address(0), "newSecondaryWallet != address(0)");
require(newPriceNumerator > 0, "newPriceNumerator > 0");
name = "Isonex";
symbol = "IX15";
decimals = 18;
primaryWallet = msg.sender;
secondaryWallet = newSecondaryWallet;
whitelist[primaryWallet] = true;
whitelist[secondaryWallet] = true;
currentPrice = Price(newPriceNumerator, 1000);
currentPriceHistoryIndex = now;
restrictionMap[1] = "Sender is not whitelisted";
restrictionMap[2] = "Receiver is not whitelisted";
restrictionMap[3] = "Trading is not enabled";
}
// Primary and Secondary wallets may updated the current price. Secondary wallet has time and change size constrainst
function updatePrice(uint256 newNumerator) external onlyPrimaryAndSecondaryWallets {
require(newNumerator > 0, "newNumerator > 0");
checkSecondaryWalletRestrictions(newNumerator);
currentPrice.numerator = newNumerator;
// After the token sale, map time to new Price
priceHistory[currentPriceHistoryIndex] = currentPrice;
currentPriceHistoryIndex = now;
emit PriceUpdated(newNumerator, currentPrice.denominator);
}
// secondaryWallet can only increase price by up to 20% and only every priceUpdateInterval
function checkSecondaryWalletRestrictions (uint256 newNumerator) view private
onlySecondaryWallet priceUpdateIntervalElapsed ifNewNumeratorGreater(newNumerator) {
uint256 percentageDiff = safeSub(safeMul(newNumerator, 100) / currentPrice.numerator, 100);
require(percentageDiff <= 20, "percentageDiff <= 20");
}
function updatePriceDenominator(uint256 newDenominator) external onlyPrimaryWallet {
require(newDenominator > 0, "newDenominator > 0");
currentPrice.denominator = newDenominator;
// map time to new Price
priceHistory[currentPriceHistoryIndex] = currentPrice;
currentPriceHistoryIndex = now;
emit PriceUpdated(currentPrice.numerator, newDenominator);
}
function processDeposit(address participant, uint numberOfTokens) external onlyPrimaryWallet {
require(participant != address(0), "participant != address(0)");
whitelist[participant] = true;
allocateTokens(participant, numberOfTokens);
emit Whitelisted(participant);
emit DepositProcessed(participant, numberOfTokens);
}
// When Ether is sent directly to the contract
function() public payable {
}
function allocateTokens(address participant, uint256 numberOfTokens) private {
// check that token cap is not exceeded
require(safeAdd(totalSupply, numberOfTokens) <= tokenCap, "Exceeds token cap");
// increase token supply, assign tokens to participant
totalSupply = safeAdd(totalSupply, numberOfTokens);
balances[participant] = safeAdd(balances[participant], numberOfTokens);
emit Transfer(address(0), participant, numberOfTokens);
}
function verifyParticipant(address participant) external onlyPrimaryAndSecondaryWallets {
whitelist[participant] = true;
emit Whitelisted(participant);
}
function removeFromWhitelist(address participant) external onlyPrimaryAndSecondaryWallets {
whitelist[participant] = false;
emit RemovedFromWhitelist(participant);
}
function requestWithdrawal(uint256 amountOfTokensToWithdraw) external isTradeable onlyWhitelist {
require(amountOfTokensToWithdraw > 0, "Amount must be greater than 0");
address participant = msg.sender;
require(balanceOf(participant) >= amountOfTokensToWithdraw, "Not enough balance");
require(withdrawalRequests[participant].nummberOfTokens == 0, "Outstanding withdrawal request must be processed");
balances[participant] = safeSub(balanceOf(participant), amountOfTokensToWithdraw);
withdrawalRequests[participant] = WithdrawalRequest({nummberOfTokens: amountOfTokensToWithdraw, time: currentPriceHistoryIndex});
emit WithdrawalRequested(participant, amountOfTokensToWithdraw);
}
function withdraw() external {
address participant = msg.sender;
uint256 nummberOfTokens = withdrawalRequests[participant].nummberOfTokens;
require(nummberOfTokens > 0, "Missing withdrawal request");
uint256 requestTime = withdrawalRequests[participant].time;
Price storage price = priceHistory[requestTime];
require(price.numerator > 0, 'Please wait for the next price update');
uint256 etherAmount = safeMul(nummberOfTokens, price.denominator) / price.numerator;
require(address(this).balance >= etherAmount, "Not enough Ether in the smart contract.");
withdrawalRequests[participant].nummberOfTokens = 0;
// Move the Isonex tokens to the primary wallet
balances[primaryWallet] = safeAdd(balances[primaryWallet], nummberOfTokens);
// Send ether from the contract wallet to the participant
participant.transfer(etherAmount);
emit Withdrew(participant, etherAmount, nummberOfTokens);
}
function checkWithdrawValue(uint256 amountTokensToWithdraw) public constant returns (uint256 etherValue) {
require(amountTokensToWithdraw > 0, "Amount must be greater than 0");
require(balanceOf(msg.sender) >= amountTokensToWithdraw, "Not enough balance");
uint256 withdrawValue = safeMul(amountTokensToWithdraw, currentPrice.denominator) / currentPrice.numerator;
require(address(this).balance >= withdrawValue, "Not enough balance in contract");
return withdrawValue;
}
// allow the primaryWallet or secondaryWallet to add Ether to the contract
function addLiquidity() external onlyPrimaryAndSecondaryWallets payable {
require(msg.value > 0, "Amount must be greater than 0");
emit LiquidityAdded(msg.value);
}
// allow the primaryWallet or secondaryWallet to remove Ether from contract
function removeLiquidity(uint256 amount) external onlyPrimaryAndSecondaryWallets {
require(amount <= address(this).balance, "amount <= address(this).balance");
primaryWallet.transfer(amount);
emit LiquidityRemoved(amount);
}
function changePrimaryWallet(address newPrimaryWallet) external onlyPrimaryWallet {
require(newPrimaryWallet != address(0), "newPrimaryWallet != address(0)");
primaryWallet = newPrimaryWallet;
}
function changeSecondaryWallet(address newSecondaryWallet) external onlyPrimaryWallet {
require(newSecondaryWallet != address(0), "newSecondaryWallet != address(0)");
secondaryWallet = newSecondaryWallet;
}
function changePriceUpdateInterval(uint256 newPriceUpdateInterval) external onlyPrimaryWallet {
priceUpdateInterval = newPriceUpdateInterval;
}
function enableTrading() external onlyPrimaryWallet {
tradeable = true;
}
function claimTokens(address _token) external onlyPrimaryWallet {
require(_token != address(0), "_token != address(0)");
ERC20Interface token = ERC20Interface(_token);
uint256 balance = token.balanceOf(this);
token.transfer(primaryWallet, balance);
}
// override transfer and transferFrom to add is tradeable modifier
function transfer(address _to, uint256 _value) public notRestricted(msg.sender, _to, _value) returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
public notRestricted(_from, _to, _value) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function pendingWithdrawalAmount() external constant returns (uint256) {
return withdrawalRequests[msg.sender].nummberOfTokens;
}
function pendingWithdrawalRateNumerator() external constant returns (uint256) {
return priceHistory[withdrawalRequests[msg.sender].time].numerator;
}
function isInWhitelist(address participant) external constant onlyPrimaryWallet returns (bool) {
return whitelist[participant];
}
function amIWhitelisted() external constant returns (bool) {
return whitelist[msg.sender];
}
// returns a restriction code,
// where 0 success
function detectTransferRestriction(address from, address to, uint256 value) public view returns (uint8) {
if (whitelist[from] == false) {
return 1;
}
if (whitelist[to] == false) {
return 2;
}
if (!(tradeable || msg.sender == primaryWallet)) {
return 3;
}
return 0;
}
function messageForTransferRestriction (uint8 restrictionCode) public view returns (string){
if (bytes(restrictionMap[restrictionCode]).length == 0 ){
return "Invalid restriction code";
}
return restrictionMap[restrictionCode];
}
// Events
event PriceUpdated(uint256 numerator, uint256 denominator);
event DepositProcessed(address indexed participant, uint256 numberOfTokens);
event Whitelisted(address indexed participant);
event RemovedFromWhitelist(address indexed participant);
event WithdrawalRequested(address indexed participant, uint256 numberOfTokens);
event Withdrew(address indexed participant, uint256 etherAmount, uint256 numberOfTokens);
event LiquidityAdded(uint256 ethAmount);
event LiquidityRemoved(uint256 ethAmount);
event UserDeposited(address indexed participant, address indexed beneficiary, uint256 ethValue, uint256 numberOfTokens);
// Modifiers
modifier onlyWhitelist {
require(whitelist[msg.sender], "Not whitelisted");
_;
}
modifier onlyPrimaryWallet {
require(msg.sender == primaryWallet, "Unauthorized");
_;
}
modifier onlySecondaryWallet {
if (msg.sender == secondaryWallet)
_;
}
modifier onlyPrimaryAndSecondaryWallets {
require(msg.sender == secondaryWallet || msg.sender == primaryWallet, "Unauthorized");
_;
}
modifier priceUpdateIntervalElapsed {
require(safeSub(now, priceUpdateInterval) >= currentPriceHistoryIndex, "Price update interval");
_;
}
modifier ifNewNumeratorGreater (uint256 newNumerator) {
if (newNumerator > currentPrice.numerator)
_;
}
modifier isTradeable { // exempt primaryWallet to allow dev allocations
require(tradeable || msg.sender == primaryWallet, "Trading is currently disabled");
_;
}
modifier notRestricted (address from, address to, uint256 value) {
uint8 restrictionCode = detectTransferRestriction(from, to, value);
require(restrictionCode == 0, messageForTransferRestriction(restrictionCode));
_;
}
}
pragma solidity ^0.4.24;
import "./ERC20Interface.sol";
contract ERC20 is ERC20Interface {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// Function to access name of token .
function name() public view returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() public view returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function balanceOf(address participant) public constant returns (uint256 balance) {
return balances[participant];
}
function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool success) {
require(_to != address(0));
// documentation says transfer of 0 must be treated as a transfer and fire the transfer event
require(balances[msg.sender] >= _value && _value > 0);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3) public returns (bool success) {
require(_to != address(0));
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0);
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
// To change the approve amount you first have to reduce the addresses'
// allowance to zero by calling 'approve(_spender, 0)' if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function changeApproval(address _spender, uint256 _oldValue, uint256 _newValue) onlyPayloadSize(3) public returns (bool success) {
require(allowed[msg.sender][_spender] == _oldValue);
allowed[msg.sender][_spender] = _newValue;
emit Approval(msg.sender, _spender, _newValue);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// mitigate short address attack
// thanks to https://github.com/numerai/contract/blob/c182465f82e50ced8dacb3977ec374a892f5fa8c/contracts/Safe.sol#L30-L34.
// TODO: doublecheck implication of >= compared to ==
modifier onlyPayloadSize(uint numWords) {
assert(msg.data.length >= numWords * 32 + 4);
_;
}
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
pragma solidity ^0.4.24;
contract ERC20Interface {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
function totalSupply() public constant 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.4.24;
import "./ERC20.sol";
contract Isonex is ERC20 {
// 15M
uint256 public tokenCap = 15000000 * 10**18;
bool public tradeable = false;
address public primaryWallet;
address public secondaryWallet;
mapping (address => bool) public whitelist;
// Conversion rate from IX15 to ETH
struct Price { uint256 numerator; uint256 denominator; }
Price public currentPrice;
// The amount of time that the secondary wallet must wait between price updates
uint256 public priceUpdateInterval = 1 hours;
mapping (uint256 => Price) public priceHistory;
uint256 public currentPriceHistoryIndex = 0;
// time for each withdrawal is set to the currentPriceHistoryIndex
struct WithdrawalRequest { uint256 nummberOfTokens; uint256 time; }
mapping (address => WithdrawalRequest) withdrawalRequests;
mapping(uint8 => string) restrictionMap;
constructor (address newSecondaryWallet, uint256 newPriceNumerator) public {
require(newSecondaryWallet != address(0), "newSecondaryWallet != address(0)");
require(newPriceNumerator > 0, "newPriceNumerator > 0");
name = "Isonex";
symbol = "IX15";
decimals = 18;
primaryWallet = msg.sender;
secondaryWallet = newSecondaryWallet;
whitelist[primaryWallet] = true;
whitelist[secondaryWallet] = true;
currentPrice = Price(newPriceNumerator, 1000);
currentPriceHistoryIndex = now;
restrictionMap[1] = "Sender is not whitelisted";
restrictionMap[2] = "Receiver is not whitelisted";
restrictionMap[3] = "Trading is not enabled";
}
// Primary and Secondary wallets may updated the current price. Secondary wallet has time and change size constrainst
function updatePrice(uint256 newNumerator) external onlyPrimaryAndSecondaryWallets {
require(newNumerator > 0, "newNumerator > 0");
checkSecondaryWalletRestrictions(newNumerator);
currentPrice.numerator = newNumerator;
// After the token sale, map time to new Price
priceHistory[currentPriceHistoryIndex] = currentPrice;
currentPriceHistoryIndex = now;
emit PriceUpdated(newNumerator, currentPrice.denominator);
}
// secondaryWallet can only increase price by up to 20% and only every priceUpdateInterval
function checkSecondaryWalletRestrictions (uint256 newNumerator) view private
onlySecondaryWallet priceUpdateIntervalElapsed ifNewNumeratorGreater(newNumerator) {
uint256 percentageDiff = safeSub(safeMul(newNumerator, 100) / currentPrice.numerator, 100);
require(percentageDiff <= 20, "percentageDiff <= 20");
}
function updatePriceDenominator(uint256 newDenominator) external onlyPrimaryWallet {
require(newDenominator > 0, "newDenominator > 0");
currentPrice.denominator = newDenominator;
// map time to new Price
priceHistory[currentPriceHistoryIndex] = currentPrice;
currentPriceHistoryIndex = now;
emit PriceUpdated(currentPrice.numerator, newDenominator);
}
function processDeposit(address participant, uint numberOfTokens) external onlyPrimaryWallet {
require(participant != address(0), "participant != address(0)");
whitelist[participant] = true;
allocateTokens(participant, numberOfTokens);
emit Whitelisted(participant);
emit DepositProcessed(participant, numberOfTokens);
}
// When Ether is sent directly to the contract
function() public payable {
}
function allocateTokens(address participant, uint256 numberOfTokens) private {
// check that token cap is not exceeded
require(safeAdd(totalSupply, numberOfTokens) <= tokenCap, "Exceeds token cap");
// increase token supply, assign tokens to participant
totalSupply = safeAdd(totalSupply, numberOfTokens);
balances[participant] = safeAdd(balances[participant], numberOfTokens);
emit Transfer(address(0), participant, numberOfTokens);
}
function verifyParticipant(address participant) external onlyPrimaryAndSecondaryWallets {
whitelist[participant] = true;
emit Whitelisted(participant);
}
function removeFromWhitelist(address participant) external onlyPrimaryAndSecondaryWallets {
whitelist[participant] = false;
emit RemovedFromWhitelist(participant);
}
function requestWithdrawal(uint256 amountOfTokensToWithdraw) external isTradeable onlyWhitelist {
require(amountOfTokensToWithdraw > 0, "Amount must be greater than 0");
address participant = msg.sender;
require(balanceOf(participant) >= amountOfTokensToWithdraw, "Not enough balance");
require(withdrawalRequests[participant].nummberOfTokens == 0, "Outstanding withdrawal request must be processed");
balances[participant] = safeSub(balanceOf(participant), amountOfTokensToWithdraw);
withdrawalRequests[participant] = WithdrawalRequest({nummberOfTokens: amountOfTokensToWithdraw, time: currentPriceHistoryIndex});
emit WithdrawalRequested(participant, amountOfTokensToWithdraw);
}
function withdraw() external {
address participant = msg.sender;
uint256 nummberOfTokens = withdrawalRequests[participant].nummberOfTokens;
require(nummberOfTokens > 0, "Missing withdrawal request");
uint256 requestTime = withdrawalRequests[participant].time;
Price storage price = priceHistory[requestTime];
require(price.numerator > 0, 'Please wait for the next price update');
uint256 etherAmount = safeMul(nummberOfTokens, price.denominator) / price.numerator;
require(address(this).balance >= etherAmount, "Not enough Ether in the smart contract.");
withdrawalRequests[participant].nummberOfTokens = 0;
// Move the Isonex tokens to the primary wallet
balances[primaryWallet] = safeAdd(balances[primaryWallet], nummberOfTokens);
// Send ether from the contract wallet to the participant
participant.transfer(etherAmount);
emit Withdrew(participant, etherAmount, nummberOfTokens);
}
function checkWithdrawValue(uint256 amountTokensToWithdraw) public constant returns (uint256 etherValue) {
require(amountTokensToWithdraw > 0, "Amount must be greater than 0");
require(balanceOf(msg.sender) >= amountTokensToWithdraw, "Not enough balance");
uint256 withdrawValue = safeMul(amountTokensToWithdraw, currentPrice.denominator) / currentPrice.numerator;
require(address(this).balance >= withdrawValue, "Not enough balance in contract");
return withdrawValue;
}
// allow the primaryWallet or secondaryWallet to add Ether to the contract
function addLiquidity() external onlyPrimaryAndSecondaryWallets payable {
require(msg.value > 0, "Amount must be greater than 0");
emit LiquidityAdded(msg.value);
}
// allow the primaryWallet or secondaryWallet to remove Ether from contract
function removeLiquidity(uint256 amount) external onlyPrimaryAndSecondaryWallets {
require(amount <= address(this).balance, "amount <= address(this).balance");
primaryWallet.transfer(amount);
emit LiquidityRemoved(amount);
}
function changePrimaryWallet(address newPrimaryWallet) external onlyPrimaryWallet {
require(newPrimaryWallet != address(0), "newPrimaryWallet != address(0)");
primaryWallet = newPrimaryWallet;
}
function changeSecondaryWallet(address newSecondaryWallet) external onlyPrimaryWallet {
require(newSecondaryWallet != address(0), "newSecondaryWallet != address(0)");
secondaryWallet = newSecondaryWallet;
}
function changePriceUpdateInterval(uint256 newPriceUpdateInterval) external onlyPrimaryWallet {
priceUpdateInterval = newPriceUpdateInterval;
}
function enableTrading() external onlyPrimaryWallet {
tradeable = true;
}
function claimTokens(address _token) external onlyPrimaryWallet {
require(_token != address(0), "_token != address(0)");
ERC20Interface token = ERC20Interface(_token);
uint256 balance = token.balanceOf(this);
token.transfer(primaryWallet, balance);
}
// override transfer and transferFrom to add is tradeable modifier
function transfer(address _to, uint256 _value) public notRestricted(msg.sender, _to, _value) returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
public notRestricted(_from, _to, _value) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function pendingWithdrawalAmount() external constant returns (uint256) {
return withdrawalRequests[msg.sender].nummberOfTokens;
}
function pendingWithdrawalRateNumerator() external constant returns (uint256) {
return priceHistory[withdrawalRequests[msg.sender].time].numerator;
}
function isInWhitelist(address participant) external constant onlyPrimaryWallet returns (bool) {
return whitelist[participant];
}
function amIWhitelisted() external constant returns (bool) {
return whitelist[msg.sender];
}
// returns a restriction code,
// where 0 success
function detectTransferRestriction(address from, address to, uint256 value) public view returns (uint8) {
if (whitelist[from] == false) {
return 1;
}
if (whitelist[to] == false) {
return 2;
}
if (!(tradeable || msg.sender == primaryWallet)) {
return 3;
}
return 0;
}
function messageForTransferRestriction (uint8 restrictionCode) public view returns (string){
if (bytes(restrictionMap[restrictionCode]).length == 0 ){
return "Invalid restriction code";
}
return restrictionMap[restrictionCode];
}
// Events
event PriceUpdated(uint256 numerator, uint256 denominator);
event DepositProcessed(address indexed participant, uint256 numberOfTokens);
event Whitelisted(address indexed participant);
event RemovedFromWhitelist(address indexed participant);
event WithdrawalRequested(address indexed participant, uint256 numberOfTokens);
event Withdrew(address indexed participant, uint256 etherAmount, uint256 numberOfTokens);
event LiquidityAdded(uint256 ethAmount);
event LiquidityRemoved(uint256 ethAmount);
event UserDeposited(address indexed participant, address indexed beneficiary, uint256 ethValue, uint256 numberOfTokens);
// Modifiers
modifier onlyWhitelist {
require(whitelist[msg.sender], "Not whitelisted");
_;
}
modifier onlyPrimaryWallet {
require(msg.sender == primaryWallet, "Unauthorized");
_;
}
modifier onlySecondaryWallet {
if (msg.sender == secondaryWallet)
_;
}
modifier onlyPrimaryAndSecondaryWallets {
require(msg.sender == secondaryWallet || msg.sender == primaryWallet, "Unauthorized");
_;
}
modifier priceUpdateIntervalElapsed {
require(safeSub(now, priceUpdateInterval) >= currentPriceHistoryIndex, "Price update interval");
_;
}
modifier ifNewNumeratorGreater (uint256 newNumerator) {
if (newNumerator > currentPrice.numerator)
_;
}
modifier isTradeable { // exempt primaryWallet to allow dev allocations
require(tradeable || msg.sender == primaryWallet, "Trading is currently disabled");
_;
}
modifier notRestricted (address from, address to, uint256 value) {
uint8 restrictionCode = detectTransferRestriction(from, to, value);
require(restrictionCode == 0, messageForTransferRestriction(restrictionCode));
_;
}
}
pragma solidity ^0.4.24;
import "./ERC20Interface.sol";
contract ERC20 is ERC20Interface {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// Function to access name of token .
function name() public view returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() public view returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function balanceOf(address participant) public constant returns (uint256 balance) {
return balances[participant];
}
function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool success) {
require(_to != address(0));
// documentation says transfer of 0 must be treated as a transfer and fire the transfer event
require(balances[msg.sender] >= _value && _value > 0);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3) public returns (bool success) {
require(_to != address(0));
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0);
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
// To change the approve amount you first have to reduce the addresses'
// allowance to zero by calling 'approve(_spender, 0)' if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function changeApproval(address _spender, uint256 _oldValue, uint256 _newValue) onlyPayloadSize(3) public returns (bool success) {
require(allowed[msg.sender][_spender] == _oldValue);
allowed[msg.sender][_spender] = _newValue;
emit Approval(msg.sender, _spender, _newValue);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// mitigate short address attack
// thanks to https://github.com/numerai/contract/blob/c182465f82e50ced8dacb3977ec374a892f5fa8c/contracts/Safe.sol#L30-L34.
// TODO: doublecheck implication of >= compared to ==
modifier onlyPayloadSize(uint numWords) {
assert(msg.data.length >= numWords * 32 + 4);
_;
}
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
pragma solidity ^0.4.24;
contract ERC20Interface {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
function totalSupply() public constant 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.4.24;
import "./ERC20.sol";
contract Isonex is ERC20 {
// 15M
uint256 public tokenCap = 15000000 * 10**18;
bool public tradeable = false;
address public primaryWallet;
address public secondaryWallet;
mapping (address => bool) public whitelist;
// Conversion rate from IX15 to ETH
struct Price { uint256 numerator; uint256 denominator; }
Price public currentPrice;
// The amount of time that the secondary wallet must wait between price updates
uint256 public priceUpdateInterval = 1 hours;
mapping (uint256 => Price) public priceHistory;
uint256 public currentPriceHistoryIndex = 0;
// time for each withdrawal is set to the currentPriceHistoryIndex
struct WithdrawalRequest { uint256 nummberOfTokens; uint256 time; }
mapping (address => WithdrawalRequest) withdrawalRequests;
mapping(uint8 => string) restrictionMap;
constructor (address newSecondaryWallet, uint256 newPriceNumerator) public {
require(newSecondaryWallet != address(0), "newSecondaryWallet != address(0)");
require(newPriceNumerator > 0, "newPriceNumerator > 0");
name = "Isonex";
symbol = "IX15";
decimals = 18;
primaryWallet = msg.sender;
secondaryWallet = newSecondaryWallet;
whitelist[primaryWallet] = true;
whitelist[secondaryWallet] = true;
currentPrice = Price(newPriceNumerator, 1000);
currentPriceHistoryIndex = now;
restrictionMap[1] = "Sender is not whitelisted";
restrictionMap[2] = "Receiver is not whitelisted";
restrictionMap[3] = "Trading is not enabled";
}
// Primary and Secondary wallets may updated the current price. Secondary wallet has time and change size constrainst
function updatePrice(uint256 newNumerator) external onlyPrimaryAndSecondaryWallets {
require(newNumerator > 0, "newNumerator > 0");
checkSecondaryWalletRestrictions(newNumerator);
currentPrice.numerator = newNumerator;
// After the token sale, map time to new Price
priceHistory[currentPriceHistoryIndex] = currentPrice;
currentPriceHistoryIndex = now;
emit PriceUpdated(newNumerator, currentPrice.denominator);
}
// secondaryWallet can only increase price by up to 20% and only every priceUpdateInterval
function checkSecondaryWalletRestrictions (uint256 newNumerator) view private
onlySecondaryWallet priceUpdateIntervalElapsed ifNewNumeratorGreater(newNumerator) {
uint256 percentageDiff = safeSub(safeMul(newNumerator, 100) / currentPrice.numerator, 100);
require(percentageDiff <= 20, "percentageDiff <= 20");
}
function updatePriceDenominator(uint256 newDenominator) external onlyPrimaryWallet {
require(newDenominator > 0, "newDenominator > 0");
currentPrice.denominator = newDenominator;
// map time to new Price
priceHistory[currentPriceHistoryIndex] = currentPrice;
currentPriceHistoryIndex = now;
emit PriceUpdated(currentPrice.numerator, newDenominator);
}
function processDeposit(address participant, uint numberOfTokens) external onlyPrimaryWallet {
require(participant != address(0), "participant != address(0)");
whitelist[participant] = true;
allocateTokens(participant, numberOfTokens);
emit Whitelisted(participant);
emit DepositProcessed(participant, numberOfTokens);
}
// When Ether is sent directly to the contract
function() public payable {
}
function allocateTokens(address participant, uint256 numberOfTokens) private {
// check that token cap is not exceeded
require(safeAdd(totalSupply, numberOfTokens) <= tokenCap, "Exceeds token cap");
// increase token supply, assign tokens to participant
totalSupply = safeAdd(totalSupply, numberOfTokens);
balances[participant] = safeAdd(balances[participant], numberOfTokens);
emit Transfer(address(0), participant, numberOfTokens);
}
function verifyParticipant(address participant) external onlyPrimaryAndSecondaryWallets {
whitelist[participant] = true;
emit Whitelisted(participant);
}
function removeFromWhitelist(address participant) external onlyPrimaryAndSecondaryWallets {
whitelist[participant] = false;
emit RemovedFromWhitelist(participant);
}
function requestWithdrawal(uint256 amountOfTokensToWithdraw) external isTradeable onlyWhitelist {
require(amountOfTokensToWithdraw > 0, "Amount must be greater than 0");
address participant = msg.sender;
require(balanceOf(participant) >= amountOfTokensToWithdraw, "Not enough balance");
require(withdrawalRequests[participant].nummberOfTokens == 0, "Outstanding withdrawal request must be processed");
balances[participant] = safeSub(balanceOf(participant), amountOfTokensToWithdraw);
withdrawalRequests[participant] = WithdrawalRequest({nummberOfTokens: amountOfTokensToWithdraw, time: currentPriceHistoryIndex});
emit WithdrawalRequested(participant, amountOfTokensToWithdraw);
}
function withdraw() external {
address participant = msg.sender;
uint256 nummberOfTokens = withdrawalRequests[participant].nummberOfTokens;
require(nummberOfTokens > 0, "Missing withdrawal request");
uint256 requestTime = withdrawalRequests[participant].time;
Price storage price = priceHistory[requestTime];
require(price.numerator > 0, 'Please wait for the next price update');
uint256 etherAmount = safeMul(nummberOfTokens, price.denominator) / price.numerator;
require(address(this).balance >= etherAmount, "Not enough Ether in the smart contract.");
withdrawalRequests[participant].nummberOfTokens = 0;
// Move the Isonex tokens to the primary wallet
balances[primaryWallet] = safeAdd(balances[primaryWallet], nummberOfTokens);
// Send ether from the contract wallet to the participant
participant.transfer(etherAmount);
emit Withdrew(participant, etherAmount, nummberOfTokens);
}
function checkWithdrawValue(uint256 amountTokensToWithdraw) public constant returns (uint256 etherValue) {
require(amountTokensToWithdraw > 0, "Amount must be greater than 0");
require(balanceOf(msg.sender) >= amountTokensToWithdraw, "Not enough balance");
uint256 withdrawValue = safeMul(amountTokensToWithdraw, currentPrice.denominator) / currentPrice.numerator;
require(address(this).balance >= withdrawValue, "Not enough balance in contract");
return withdrawValue;
}
// allow the primaryWallet or secondaryWallet to add Ether to the contract
function addLiquidity() external onlyPrimaryAndSecondaryWallets payable {
require(msg.value > 0, "Amount must be greater than 0");
emit LiquidityAdded(msg.value);
}
// allow the primaryWallet or secondaryWallet to remove Ether from contract
function removeLiquidity(uint256 amount) external onlyPrimaryAndSecondaryWallets {
require(amount <= address(this).balance, "amount <= address(this).balance");
primaryWallet.transfer(amount);
emit LiquidityRemoved(amount);
}
function changePrimaryWallet(address newPrimaryWallet) external onlyPrimaryWallet {
require(newPrimaryWallet != address(0), "newPrimaryWallet != address(0)");
primaryWallet = newPrimaryWallet;
}
function changeSecondaryWallet(address newSecondaryWallet) external onlyPrimaryWallet {
require(newSecondaryWallet != address(0), "newSecondaryWallet != address(0)");
secondaryWallet = newSecondaryWallet;
}
function changePriceUpdateInterval(uint256 newPriceUpdateInterval) external onlyPrimaryWallet {
priceUpdateInterval = newPriceUpdateInterval;
}
function enableTrading() external onlyPrimaryWallet {
tradeable = true;
}
function claimTokens(address _token) external onlyPrimaryWallet {
require(_token != address(0), "_token != address(0)");
ERC20Interface token = ERC20Interface(_token);
uint256 balance = token.balanceOf(this);
token.transfer(primaryWallet, balance);
}
// override transfer and transferFrom to add is tradeable modifier
function transfer(address _to, uint256 _value) public notRestricted(msg.sender, _to, _value) returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
public notRestricted(_from, _to, _value) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function pendingWithdrawalAmount() external constant returns (uint256) {
return withdrawalRequests[msg.sender].nummberOfTokens;
}
function pendingWithdrawalRateNumerator() external constant returns (uint256) {
return priceHistory[withdrawalRequests[msg.sender].time].numerator;
}
function isInWhitelist(address participant) external constant onlyPrimaryWallet returns (bool) {
return whitelist[participant];
}
function amIWhitelisted() external constant returns (bool) {
return whitelist[msg.sender];
}
// returns a restriction code,
// where 0 success
function detectTransferRestriction(address from, address to, uint256 value) public view returns (uint8) {
if (whitelist[from] == false) {
return 1;
}
if (whitelist[to] == false) {
return 2;
}
if (!(tradeable || msg.sender == primaryWallet)) {
return 3;
}
return 0;
}
function messageForTransferRestriction (uint8 restrictionCode) public view returns (string){
if (bytes(restrictionMap[restrictionCode]).length == 0 ){
return "Invalid restriction code";
}
return restrictionMap[restrictionCode];
}
// Events
event PriceUpdated(uint256 numerator, uint256 denominator);
event DepositProcessed(address indexed participant, uint256 numberOfTokens);
event Whitelisted(address indexed participant);
event RemovedFromWhitelist(address indexed participant);
event WithdrawalRequested(address indexed participant, uint256 numberOfTokens);
event Withdrew(address indexed participant, uint256 etherAmount, uint256 numberOfTokens);
event LiquidityAdded(uint256 ethAmount);
event LiquidityRemoved(uint256 ethAmount);
event UserDeposited(address indexed participant, address indexed beneficiary, uint256 ethValue, uint256 numberOfTokens);
// Modifiers
modifier onlyWhitelist {
require(whitelist[msg.sender], "Not whitelisted");
_;
}
modifier onlyPrimaryWallet {
require(msg.sender == primaryWallet, "Unauthorized");
_;
}
modifier onlySecondaryWallet {
if (msg.sender == secondaryWallet)
_;
}
modifier onlyPrimaryAndSecondaryWallets {
require(msg.sender == secondaryWallet || msg.sender == primaryWallet, "Unauthorized");
_;
}
modifier priceUpdateIntervalElapsed {
require(safeSub(now, priceUpdateInterval) >= currentPriceHistoryIndex, "Price update interval");
_;
}
modifier ifNewNumeratorGreater (uint256 newNumerator) {
if (newNumerator > currentPrice.numerator)
_;
}
modifier isTradeable { // exempt primaryWallet to allow dev allocations
require(tradeable || msg.sender == primaryWallet, "Trading is currently disabled");
_;
}
modifier notRestricted (address from, address to, uint256 value) {
uint8 restrictionCode = detectTransferRestriction(from, to, value);
require(restrictionCode == 0, messageForTransferRestriction(restrictionCode));
_;
}
}
| documentation says transfer of 0 must be treated as a transfer and fire the transfer event | function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool success) {
require(_to != address(0));
require(balances[msg.sender] >= _value && _value > 0);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 1,051,708 |
./full_match/4/0xB15421Fd33b2F785c15AD15087e5B02aA38AaB10/sources/SussyKneelsNFT.sol | URIs will be returned baseUri/tokenId | function safeMintBatch(address to, string memory baseUri, uint16 numTokens) public onlyOwner {
uint16 counter = _tokenIdCounter;
for(uint16 i=0; i<numTokens; i++) {
_safeMint(to, counter);
counter++;
}
_tokensPerUri.push(counter);
_baseURIs.push(baseUri);
_tokenIdCounter = counter + 1;
}
| 737,480 |
./partial_match/3/0x3d5A54D0aE3F304a7d1B03fef1EDf72316aF0B34/sources/BondMakerHelper.sol | return fnMaps divided into SBT and LBT/ | function _getSbtAndLbtFnMap(uint64 strikePrice)
internal
pure
returns (bytes[] memory fnMaps)
{
require(strikePrice <= uint64(-2), "the strike price is too large");
uint256[] memory sbtPolyline;
{
Point[] memory points = new Point[](2);
points[0] = Point(strikePrice, strikePrice);
points[1] = Point(strikePrice + 1, strikePrice);
sbtPolyline = _calcPolyline(points);
}
uint256[] memory lbtPolyline;
{
Point[] memory points = new Point[](2);
points[0] = Point(strikePrice, 0);
points[1] = Point(strikePrice + 1, 1);
lbtPolyline = _calcPolyline(points);
}
fnMaps = new bytes[](2);
fnMaps[0] = abi.encode(sbtPolyline);
fnMaps[1] = abi.encode(lbtPolyline);
}
| 5,077,951 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./BaseERC721A.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract AmazingNFT is BaseERC721A {
using SafeMath for uint256;
uint256 public constant MAX_SUPPLY = 10000;
string private _baseTokenURI;
address private _wallet = 0xC7BF7161A09Cf7123CB8983C5E35abE569344Bbd;
constructor(string memory _tokenURI) ERC721A("AmazingNFT", "AMAZING", 4) {
_baseTokenURI = _tokenURI;
}
// update token URI
function updateMyTokenURI888(string memory tokenURI) external onlyOwner {
_baseTokenURI = tokenURI;
}
// update wallet address
function updateWalletAddress(address _address)
external
onlyOwner
{
_wallet = _address;
}
// airdrop NFT
function airdropNFTDynamic(address[] calldata _address, uint256[] calldata _nums)
external
onlyOwner
{
uint256 sum = 0;
for (uint i = 0; i < _nums.length; i++) {
sum = sum + _nums[i];
}
require(
sum <= 1000,
"Maximum 1000 tokens per transaction"
);
require(
totalSupply() + sum <= MAX_SUPPLY,
"Exceeds maximum supply"
);
for (uint256 i = 0; i < _address.length; i++) {
_baseMint(_address[i], _nums[i]);
}
}
// withdraw the balance if needed
function withdraw() external onlyOwner {
payable(_wallet).transfer( address(this).balance );
}
// required override
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
// return the wallet address by index
function walletAddress() external view returns (address) {
return _wallet;
}
}
//SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./ERC721A.sol";
abstract contract BaseERC721A is Ownable, ERC721A {
using SafeMath for uint256;
function _baseMint(uint256 quantity) internal {
// mint the token
_baseMint(msg.sender, quantity);
}
function _baseMint(address _address, uint256 quantity) internal {
// mint the token to target address
if ( quantity > 4) {
for (uint256 i = 0; i < quantity; i++) {
_safeMint(_address, 1);
}
} else {
_safeMint(_address, quantity);
}
}
function tokenURI(uint256 tokenId)
public
view
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,
Strings.toString(tokenId),
".json"
)
)
: "";
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// Creators: locationtba.eth, 2pmflow.eth
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721A: balance query for the zero address"
);
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721A: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721A: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | Explicitly set `owners` to eliminate loops in future calls of ownerOf()./ | function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
| 1,292,327 |
./partial_match/8453/0x46Cf9B499ecE1098beB860a9767e8c2c39AE747B/sources/ChainlinkPriceOracle.sol | Users borrow assets from the protocol to their own address borrowAmount The amount of the underlying asset to borrow/ Fail if borrow not allowed / Verify market's block number equals current block number / Fail gracefully if protocol has insufficient underlying cash / | function borrowFresh(address payable borrower, uint256 borrowAmount)
internal
{
uint256 allowed = comptroller.borrowAllowed(
address(this),
borrower,
borrowAmount
);
if (allowed != 0) {
revert BorrowComptrollerRejection(allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
revert BorrowFreshnessCheck();
}
if (getCashPrior() < borrowAmount) {
revert BorrowCashNotAvailable();
}
uint256 accountBorrowsNew = accountBorrowsPrev + borrowAmount;
uint256 totalBorrowsNew = totalBorrows + borrowAmount;
accountBorrows[borrower].principal = accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = totalBorrowsNew;
}
| 16,722,330 |
// SPDX-License-Identifier: None
// File: ..\..\..\node_modules\@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\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\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\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\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\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\utils\Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin\contracts\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\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: ..\..\..\node_modules\@openzeppelin\contracts\interfaces\IERC165.sol
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
// File: @openzeppelin\contracts\interfaces\IERC2981.sol
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File: monk.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);
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable,
Ownable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string public baseURI;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory URI = _baseURI();
return
bytes(URI).length > 0
? string(abi.encodePacked(URI, tokenId.toString(), ".json"))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return baseURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
contract Monkfer is ERC721A, IERC2981 {
uint256 mintCost = 0.001 ether;
uint256 private constant MAX_NFTS_FOR_SALE = 10000;
// Address of the royalties recipient
address private _royaltiesReceiver = 0x627831FCa64488f8471536A0D112f72ed062FCcc;
// Percentage of each sale to pay as royalties
uint256 public constant royaltiesPercentage = 88; //8.8% royalty fee
constructor() ERC721A("M0nkeyF3Rs", "M0nkF3r", 20) {
_safeMint(msg.sender, 20);
_safeMint(msg.sender, 20);
_safeMint(msg.sender, 20);
_safeMint(msg.sender, 20);
_safeMint(msg.sender, 20); //mint 100 tokens to the owner
}
/// @notice Getter function for _royaltiesReceiver
/// @return the address of the royalties recipient
function royaltiesReceiver() external view returns(address) {
return _royaltiesReceiver;
}
/// @notice Changes the royalties' recipient address (in case rights are
/// transferred for instance)
/// @param newRoyaltiesReceiver - address of the new royalties recipient
function setRoyaltiesReceiver(address newRoyaltiesReceiver)
external onlyOwner {
require(newRoyaltiesReceiver != _royaltiesReceiver); // dev: Same address
_royaltiesReceiver = newRoyaltiesReceiver;
}
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - 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 _value sale price
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override
returns (address receiver, uint256 royaltyAmount) {
uint256 _royalties = (_salePrice * royaltiesPercentage) / 1000;
return (_royaltiesReceiver, _royalties);
}
function mint(uint256 quantity) external payable {
require(totalSupply() + quantity <= MAX_NFTS_FOR_SALE, "Limit exceeded");
require(msg.value >= quantity*mintCost, "More ether required!");
_safeMint(msg.sender, quantity);
}
function reveal(string memory _URI) external onlyOwner {
// require(totalSupply() == MAX_NFTS_FOR_SALE, "NFTs not minted yet!");
require(bytes(baseURI).length == 0, "Already revealed!"); // ensures base uri is set only once
baseURI = _URI;
}
function airdrop(address _to, uint256 _amount) public onlyOwner {
require(totalSupply()+_amount < MAX_NFTS_FOR_SALE, "Cannot airdrop more");
_safeMint(_to, _amount);
}
/// @notice Informs callers (like OpenSea) that this contract supports ERC2981 royaltyies standard
function supportsInterface(bytes4 interfaceId)
public view override(ERC721A, IERC165)
returns (bool) {
return interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
} | Getter function for _royaltiesReceiver return the address of the royalties recipient | function royaltiesReceiver() external view returns(address) {
return _royaltiesReceiver;
}
| 361,111 |
// 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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The 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_) {
_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");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @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);
}
// 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) {
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.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "hardhat/console.sol";
contract Kranz is ERC20, Ownable {
using SafeMath for uint256;
// Default percent to charge on each transfer (Note: 1e18 == 100%)
uint256 private _transactionFeePercent;
// Default percent to charge when selling tokens (Note: 1e18 == 100%)
uint256 private _transactionFeePercentDex;
// DEX (Uniswap or PancakeSwap) address to use when check if is a seller transfer (i.e. V2 Pair / V3 Pool address)
// mitigated - Contract only permits a single DEX address
mapping(address => bool) dexAddresses;
// Timelcok feature
enum Functions {
FEE,
FEE_DEX,
FEE_DIST
}
uint256 private constant _TIMELOCK = 1 days;
mapping(Functions => uint256) public currentTimelocks;
mapping(Functions => bool) public hasPendingFee;
// Fee Beneficiaries
address public _rewardWallet;
address public _developerWallet;
address public _liquidityWallet;
// Percent distribution among wallets and burn
// Note: The sum of these four values should be 100% (1e18)
uint256 public _burnPercent;
uint256 public _rewardWalletFeePercent;
uint256 public _developerWalletFeePercent;
uint256 public _liquidityWalletFeePercent;
// Proposal Variables
uint256 private _pendingTransactionFeePercent;
uint256 private _pendingTransactionFeePercentDex;
uint256 private _pendingBurnPercent;
uint256 private _pendingRewardWalletFeePercent;
uint256 private _pendingDeveloperWalletFeePercent;
uint256 private _pendingLiquidityWalletFeePercent;
uint256 private _feeUpdateTimestamp;
constructor(
uint256 initialSupply,
address tokensBeneficiary,
address rewardWallet,
address developerWallet,
address liquidityWallet
) ERC20("Kranz Token", "KRZ") {
_mint(tokensBeneficiary, initialSupply);
_transactionFeePercent = 1e16; // 1%
_transactionFeePercentDex = 3e16; // 3%
_rewardWallet = rewardWallet;
_developerWallet = developerWallet;
_liquidityWallet = liquidityWallet;
_burnPercent = 5e17; // 50%
_rewardWalletFeePercent = 1e17; // 10%
_developerWalletFeePercent = 3e17; // 30%
_liquidityWalletFeePercent = 1e17; // 10%
// initialize timelock conditions
currentTimelocks[Functions.FEE] = 0;
currentTimelocks[Functions.FEE_DEX] = 0;
currentTimelocks[Functions.FEE_DIST] = 0;
hasPendingFee[Functions.FEE] = false;
hasPendingFee[Functions.FEE_DEX] = false;
hasPendingFee[Functions.FEE_DIST] = false;
}
// TODO: Mitigate Contract owner from front-run transfers with fee changes
// Consider modifing fees with a time lock approach. An initial transaction could specify the new fees,
// and a subsequent transaction (which must be more than a fixed number of blocks later) can then update the fees.
// Transfer functions with fee charging
//
function transfer(address recipient, uint256 amount)
public
override
updateFees()
returns (bool)
{
_transferWithFee(_msgSender(), recipient, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override updateFees() returns (bool) {
_transferWithFee(sender, recipient, amount);
uint256 currentAllowance = allowance(sender, _msgSender());
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function _transferWithFee(
address sender,
address recipient,
uint256 amount
) private {
uint256 feeToCharge;
if (dexAddresses[recipient]) {
feeToCharge = amount.mul(_transactionFeePercentDex).div(1e18);
} else {
feeToCharge = amount.mul(_transactionFeePercent).div(1e18);
}
uint256 amountAfterFee = amount.sub(feeToCharge);
(
uint256 toReward,
uint256 toDeveloper,
uint256 toLiquidity,
uint256 toBurn
) = calculateFeeDistribution(feeToCharge);
_transfer(sender, 0x000000000000000000000000000000000000dEaD, toBurn);
_transfer(sender, _rewardWallet, toReward);
_transfer(sender, _developerWallet, toDeveloper);
_transfer(sender, _liquidityWallet, toLiquidity);
_transfer(sender, recipient, amountAfterFee);
}
// Note: run this code before transfers (from modifier or function's body)
modifier updateFees() {
setTransactionFee();
setTransactionFeeDex();
setFeeDistribution();
_;
}
// Getters for Current Transaction fees / distributions
function getCurrentTransactionFee() public view returns (uint256) {
return _transactionFeePercent;
}
function getCurrentTransactionFeeDex() public view returns (uint256) {
return _transactionFeePercentDex;
}
function getCurrentFeeDistribution()
public
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
return (
_burnPercent,
_rewardWalletFeePercent,
_developerWalletFeePercent,
_liquidityWalletFeePercent
);
}
// Getters for Pending Transaction fees / distributions
function getPendingTransactionFee() public view returns (uint256) {
return _pendingTransactionFeePercent;
}
function getPendingTransactionFeeDex() public view returns (uint256) {
return _pendingTransactionFeePercentDex;
}
function getPendingFeeDistribution()
public
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
return (
_pendingBurnPercent,
_pendingRewardWalletFeePercent,
_pendingDeveloperWalletFeePercent,
_pendingLiquidityWalletFeePercent
);
}
// Getters for Pending Transaction fees / distributions
function getPendingTransactionFeeTime() public view returns (uint256) {
return currentTimelocks[Functions.FEE];
}
function getPendingTransactionFeeDexTime() public view returns (uint256) {
return currentTimelocks[Functions.FEE_DEX];
}
function getPendingFeeDistributionTime() public view returns (uint256) {
return currentTimelocks[Functions.FEE_DIST];
}
// Calculate Fee distributions
function calculateFeeDistribution(uint256 amount)
private
view
returns (
uint256 toReward,
uint256 toDeveloper,
uint256 toLiquidity,
uint256 toBurn
)
{
toReward = amount.mul(_rewardWalletFeePercent).div(1e18);
toDeveloper = amount.mul(_developerWalletFeePercent).div(1e18);
toLiquidity = amount.mul(_liquidityWalletFeePercent).div(1e18);
// fixed (mitigated - transfer less than expected)
toBurn = amount.sub(toReward).sub(toDeveloper).sub(toLiquidity);
}
//
// Administration setter functions
//
function proposeTransactionFee(uint256 fee) public onlyOwner {
require(
fee >= 0 && fee <= 5e16,
"Kranz: transaction fee should be >= 0 and <= 5%"
);
require(
!hasPendingFee[Functions.FEE],
"Kranz: There is a pending fee change already."
);
require(
currentTimelocks[Functions.FEE] == 0,
"Current Timelock is already initialized with a value"
);
_pendingTransactionFeePercent = fee;
// intialize timelock conditions
currentTimelocks[Functions.FEE] = block.timestamp + _TIMELOCK; // resets timelock with future timestamp that it will be unlocked
hasPendingFee[Functions.FEE] = true;
}
function proposeTransactionFeeDex(uint256 fee) public onlyOwner {
require(
fee >= 0 && fee <= 5e16,
"Krans: sell transaction fee should be >= 0 and <= 5%"
);
require(
!hasPendingFee[Functions.FEE_DEX],
"Kranz: There is a pending dex fee change already."
);
require(
currentTimelocks[Functions.FEE_DEX] == 0,
"Current Timelock is already initialized with a value"
);
_pendingTransactionFeePercentDex = fee;
// intialize timelock conditions
currentTimelocks[Functions.FEE_DEX] = block.timestamp + _TIMELOCK; // resets timelock with future timestamp that it will be unlocked
hasPendingFee[Functions.FEE_DEX] = true;
}
function proposeFeeDistribution(
uint256 burnPercent,
uint256 rewardWalletFeePercent,
uint256 developerWalletFeePercent,
uint256 liquidityWalletFeePercent
) public onlyOwner {
require(
burnPercent
.add(rewardWalletFeePercent)
.add(developerWalletFeePercent)
.add(liquidityWalletFeePercent) == 1e18,
"Kranz: The sum of distribuition should be 100%"
);
require(
!hasPendingFee[Functions.FEE_DIST],
"Kranz: There is a pending dsitribution fee change already."
);
require(
currentTimelocks[Functions.FEE_DIST] == 0,
"Current Timelock is already initialized with a value"
);
_pendingBurnPercent = burnPercent;
_pendingRewardWalletFeePercent = rewardWalletFeePercent;
_pendingDeveloperWalletFeePercent = developerWalletFeePercent;
_pendingLiquidityWalletFeePercent = liquidityWalletFeePercent;
// intialize timelock conditions
currentTimelocks[Functions.FEE_DIST] = block.timestamp + _TIMELOCK;
hasPendingFee[Functions.FEE_DIST] = true;
}
function setTransactionFee() private {
if (
hasPendingFee[Functions.FEE] == true &&
currentTimelocks[Functions.FEE] <= block.timestamp
) {
_transactionFeePercent = _pendingTransactionFeePercent;
// reset timelock conditions
currentTimelocks[Functions.FEE] = 0;
hasPendingFee[Functions.FEE] = false;
}
}
function setTransactionFeeDex() private {
if (
hasPendingFee[Functions.FEE_DEX] == true &&
currentTimelocks[Functions.FEE_DEX] <= block.timestamp
) {
_transactionFeePercentDex = _pendingTransactionFeePercentDex;
// reset timelock conditions
currentTimelocks[Functions.FEE_DEX] = 0;
hasPendingFee[Functions.FEE_DEX] = false;
}
}
function setFeeDistribution() private {
if (
hasPendingFee[Functions.FEE_DIST] == true &&
currentTimelocks[Functions.FEE_DIST] <= block.timestamp
) {
_burnPercent = _pendingBurnPercent;
_rewardWalletFeePercent = _pendingRewardWalletFeePercent;
_developerWalletFeePercent = _pendingDeveloperWalletFeePercent;
_liquidityWalletFeePercent = _pendingLiquidityWalletFeePercent;
// reset timelock conditions
currentTimelocks[Functions.FEE_DIST] = 0;
hasPendingFee[Functions.FEE_DIST] = false;
}
}
function setDeveloperWalletAddress(address devAddress) public onlyOwner {
require(
devAddress != address(0),
"Kranz: devAddress cannot be zero address"
);
_developerWallet = devAddress;
}
function setRewardWalletAddress(address rewardAddress) public onlyOwner {
require(
rewardAddress != address(0),
"Kranz: rewardAddress cannot be zero address"
);
_rewardWallet = rewardAddress;
}
function setLiquidityWalletAddress(address liquidityAddress)
public
onlyOwner
{
require(
liquidityAddress != address(0),
"Kranz: liquidityAddress cannot be zero address"
);
_liquidityWallet = liquidityAddress;
}
function addDexAddress(address dexAddress) public onlyOwner {
dexAddresses[dexAddress] = true;
}
function removeDexAddress(address dexAddress) public onlyOwner {
require(
dexAddresses[dexAddress] == true,
"The DEX address you're trying to remove does not exist or already has been removed"
);
dexAddresses[dexAddress] = false;
}
}
// 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));
}
}
| reset timelock conditions | function setTransactionFeeDex() private {
if (
hasPendingFee[Functions.FEE_DEX] == true &&
currentTimelocks[Functions.FEE_DEX] <= block.timestamp
) {
_transactionFeePercentDex = _pendingTransactionFeePercentDex;
currentTimelocks[Functions.FEE_DEX] = 0;
hasPendingFee[Functions.FEE_DEX] = false;
}
}
| 1,346,808 |
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));
}
} | add or update Global Constraint _globalConstraint the address of the global constraint to be added. _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);
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);
globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params;
}
}
emit AddGlobalConstraint(_globalConstraint, _params,when);
return true;
}
| 1,299,088 |
pragma solidity ^0.5.2;
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol
interface intvoteinterface31 { //inject NONSTANDARD NAMING
//When implementing this interface please do not only override function and modifier,
//but also to keep the modifiers on the overridden functions.
modifier ONLYPROPOSALOWNER70(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
modifier VOTABLE14(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
event NEWPROPOSAL82( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event EXECUTEPROPOSAL67(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VOTEPROPOSAL81( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CANCELPROPOSAL59(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING
event CANCELVOTING5(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING
function PROPOSE48( //inject NONSTANDARD NAMING
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function VOTE79( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function CANCELVOTE62(bytes32 _proposalId) external; //inject NONSTANDARD NAMING
function GETNUMBEROFCHOICES23(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function ISVOTABLE72(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING
function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING
function ISABSTAINALLOW86() external pure returns(bool); //inject NONSTANDARD NAMING
function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
interface ierc2016 { //inject NONSTANDARD NAMING
function TRANSFER74(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE55(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM94(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY28() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF62(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE21(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL97(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol
interface votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING
function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function BURNREPUTATION8(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function STAKINGTOKENTRANSFER23(ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
returns(bool);
function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
contract ownable56 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED0(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED0(address(0), _owner);
}
function OWNER8() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER65() { //inject NONSTANDARD NAMING
require(ISOWNER85());
_;
}
function ISOWNER85() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP94() public ONLYOWNER65 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED0(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP25(address newOwner) public ONLYOWNER65 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP15(newOwner);
}
function _TRANSFEROWNERSHIP15(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED0(_owner, newOwner);
_owner = newOwner;
}
}
// File: @daostack/infra/contracts/Reputation.sol
contract reputation51 is ownable56 { //inject NONSTANDARD NAMING
uint8 public decimals = 18; //Number of decimals of the smallest unit
// Event indicating minting of reputation to an address.
event MINT64(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING
// Event indicating burning of reputation for an address.
event BURN4(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of reputation at a specific block number
uint128 value;
}
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// Tracks the history of the `totalSupply` of the reputation
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING
return TOTALSUPPLYAT94(block.number);
}
// Query balance and totalSupply in History
function BALANCEOF62(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
return BALANCEOFAT72(_owner, block.number);
}
function BALANCEOFAT72(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected balance during normal situations
} else {
return GETVALUEAT9(balances[_owner], _blockNumber);
}
}
function TOTALSUPPLYAT94(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return GETVALUEAT9(totalSupplyHistory, _blockNumber);
}
}
function MINT38(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY28();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = BALANCEOF62(_user);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply + _amount);
UPDATEVALUEATNOW85(balances[_user], previousBalanceTo + _amount);
emit MINT64(_user, _amount);
return true;
}
function BURN49(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY28();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = BALANCEOF62(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply - amountBurned);
UPDATEVALUEATNOW85(balances[_user], previousBalanceFrom - amountBurned);
emit BURN4(_user, amountBurned);
return true;
}
// Internal helper functions to query and set a value in a snapshot array
function GETVALUEAT9(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING
if (checkpoints.length == 0) {
return 0;
}
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function UPDATEVALUEATNOW85(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING
require(uint128(_value) == _value); //check value is in the 128 bits bounderies
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
// File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol
library safemath4 { //inject NONSTANDARD NAMING
function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV25(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function SUB37(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD40(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
contract erc2045 is ierc2016 { //inject NONSTANDARD NAMING
using safemath4 for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF62(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE21(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER74(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER44(msg.sender, to, value);
return true;
}
function APPROVE55(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit APPROVAL97(msg.sender, spender, value);
return true;
}
function TRANSFERFROM94(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[from][msg.sender] = _allowed[from][msg.sender].SUB37(value);
_TRANSFER44(from, to, value);
emit APPROVAL97(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function INCREASEALLOWANCE67(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD40(addedValue);
emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function DECREASEALLOWANCE11(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB37(subtractedValue);
emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _TRANSFER44(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB37(value);
_balances[to] = _balances[to].ADD40(value);
emit TRANSFER49(from, to, value);
}
function _MINT14(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD40(value);
_balances[account] = _balances[account].ADD40(value);
emit TRANSFER49(address(0), account, value);
}
function _BURN11(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB37(value);
_balances[account] = _balances[account].SUB37(value);
emit TRANSFER49(account, address(0), value);
}
function _BURNFROM86(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_allowed[account][msg.sender] = _allowed[account][msg.sender].SUB37(value);
_BURN11(account, value);
emit APPROVAL97(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
contract erc20burnable16 is erc2045 { //inject NONSTANDARD NAMING
function BURN49(uint256 value) public { //inject NONSTANDARD NAMING
_BURN11(msg.sender, value);
}
function BURNFROM98(address from, uint256 value) public { //inject NONSTANDARD NAMING
_BURNFROM86(from, value);
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/controller/DAOToken.sol
contract daotoken36 is erc2045, erc20burnable16, ownable56 { //inject NONSTANDARD NAMING
string public name;
string public symbol;
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals61 = 18; //inject NONSTANDARD NAMING
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function MINT38(address _to, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING
if (cap > 0)
require(TOTALSUPPLY28().ADD40(_amount) <= cap);
_MINT14(_to, _amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
library address8 { //inject NONSTANDARD NAMING
function ISCONTRACT13(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/libs/SafeERC20.sol
pragma solidity ^0.5.2;
library safeerc2019 { //inject NONSTANDARD NAMING
using address8 for address;
bytes4 constant private transfer_selector2 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private transferfrom_selector45 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private approve_selector67 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING
function SAFETRANSFER100(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT13());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transfer_selector2, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFETRANSFERFROM10(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT13());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transferfrom_selector45, _from, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFEAPPROVE78(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT13());
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero.
require((_value == 0) || (ierc2016(_erc20Addr).ALLOWANCE21(msg.sender, _spender) == 0));
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(approve_selector67, _spender, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/controller/Avatar.sol
contract avatar70 is ownable56 { //inject NONSTANDARD NAMING
using safeerc2019 for address;
string public orgName;
daotoken36 public nativeToken;
reputation51 public nativeReputation;
event GENERICCALL1(address indexed _contract, bytes _params, bool _success); //inject NONSTANDARD NAMING
event SENDETHER8(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFER37(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFERFROM36(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENAPPROVAL0(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING
event RECEIVEETHER12(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING
constructor(string memory _orgName, daotoken36 _nativeToken, reputation51 _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit RECEIVEETHER12(msg.sender, msg.value);
}
function GENERICCALL24(address _contract, bytes memory _data) //inject NONSTANDARD NAMING
public
ONLYOWNER65
returns(bool success, bytes memory returnValue) {
// solhint-disable-next-line avoid-low-level-calls
(success, returnValue) = _contract.call(_data);
emit GENERICCALL1(_contract, _data, success);
}
function SENDETHER91(uint256 _amountInWei, address payable _to) public ONLYOWNER65 returns(bool) { //inject NONSTANDARD NAMING
_to.transfer(_amountInWei);
emit SENDETHER8(_amountInWei, _to);
return true;
}
function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER65 returns(bool)
{
address(_externalToken).SAFETRANSFER100(_to, _value);
emit EXTERNALTOKENTRANSFER37(address(_externalToken), _to, _value);
return true;
}
function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING
ierc2016 _externalToken,
address _from,
address _to,
uint256 _value
)
public ONLYOWNER65 returns(bool)
{
address(_externalToken).SAFETRANSFERFROM10(_from, _to, _value);
emit EXTERNALTOKENTRANSFERFROM36(address(_externalToken), _from, _to, _value);
return true;
}
function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER65 returns(bool)
{
address(_externalToken).SAFEAPPROVE78(_spender, _value);
emit EXTERNALTOKENAPPROVAL0(address(_externalToken), _spender, _value);
return true;
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalSchemeInterface.sol
contract universalschemeinterface23 { //inject NONSTANDARD NAMING
function UPDATEPARAMETERS61(bytes32 _hashedParameters) public; //inject NONSTANDARD NAMING
function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/globalConstraints/GlobalConstraintInterface.sol
contract globalconstraintinterface55 { //inject NONSTANDARD NAMING
enum CallPhase { Pre, Post, PreAndPost }
function PRE44( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function POST41( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function WHEN71() public returns(CallPhase); //inject NONSTANDARD NAMING
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/controller/ControllerInterface.sol
interface controllerinterface59 { //inject NONSTANDARD NAMING
function MINTREPUTATION65(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function BURNREPUTATION8(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function MINTTOKENS53(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function REGISTERSCHEME80(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSCHEME15(address _scheme, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSELF18(address _avatar) external returns(bool); //inject NONSTANDARD NAMING
function ADDGLOBALCONSTRAINT70(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function REMOVEGLOBALCONSTRAINT6 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function UPGRADECONTROLLER96(address _newController, avatar70 _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function GENERICCALL24(address _contract, bytes calldata _data, avatar70 _avatar) //inject NONSTANDARD NAMING
external
returns(bool, bytes memory);
function SENDETHER91(uint256 _amountInWei, address payable _to, avatar70 _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING
ierc2016 _externalToken,
address _from,
address _to,
uint256 _value,
avatar70 _avatar)
external
returns(bool);
function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function GETNATIVEREPUTATION64(address _avatar) //inject NONSTANDARD NAMING
external
view
returns(address);
function ISSCHEMEREGISTERED53( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
function GETSCHEMEPARAMETERS80(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETGLOBALCONSTRAINTPARAMETERS50(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETSCHEMEPERMISSIONS72(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING
function GLOBALCONSTRAINTSCOUNT61(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING
function ISGLOBALCONSTRAINTREGISTERED65(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalScheme.sol
contract universalscheme48 is ownable56, universalschemeinterface23 { //inject NONSTANDARD NAMING
bytes32 public hashedParameters; // For other parameters.
function UPDATEPARAMETERS61( //inject NONSTANDARD NAMING
bytes32 _hashedParameters
)
public
ONLYOWNER65
{
hashedParameters = _hashedParameters;
}
function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING
require(controllerinterface59(_avatar.OWNER8()).ISSCHEMEREGISTERED53(address(this), address(_avatar)),
"scheme is not registered");
return controllerinterface59(_avatar.OWNER8()).GETSCHEMEPARAMETERS80(address(this), address(_avatar));
}
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
library ecdsa86 { //inject NONSTANDARD NAMING
function RECOVER59(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING
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);
}
}
function TOETHSIGNEDMESSAGEHASH91(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/libs/RealMath.sol
library realmath32 { //inject NONSTANDARD NAMING
uint256 constant private real_bits92 = 256; //inject NONSTANDARD NAMING
uint256 constant private real_fbits8 = 40; //inject NONSTANDARD NAMING
uint256 constant private real_one87 = uint256(1) << real_fbits8; //inject NONSTANDARD NAMING
function POW66(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
// Start with the 0th power
uint256 realResult = real_one87;
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 = MUL16(realResult, tempRealBase);
}
// Shift off the low bit
tempExponent = tempExponent >> 1;
// Do the squaring
tempRealBase = MUL16(tempRealBase, tempRealBase);
}
// Return the final result.
return uint216(realResult / real_one87);
}
function FRACTION6(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV25(uint256(numerator) * real_one87, uint256(denominator) * real_one87);
}
function MUL16(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 uint256((uint256(realA) * uint256(realB)) >> real_fbits8);
}
function DIV25(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 uint256((uint256(realNumerator) * real_one87) / uint256(realDenominator));
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol
interface proposalexecuteinterface9 { //inject NONSTANDARD NAMING
function EXECUTEPROPOSAL85(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
// File: openzeppelin-solidity/contracts/math/Math.sol
library math46 { //inject NONSTANDARD NAMING
function MAX19(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE32(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol
contract genesisprotocollogic61 is intvoteinterface31 { //inject NONSTANDARD NAMING
using safemath4 for uint;
using math46 for uint;
using realmath32 for uint216;
using realmath32 for uint256;
using address8 for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
//Organization's parameters
struct Parameters {
uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar.
uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode.
uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode.
uint256 preBoostedVotePeriodLimit; //the time limit for a proposal
//to be in an preparation state (stable) before boosted.
uint256 thresholdConst; //constant for threshold calculation .
//threshold =thresholdConst ** (numberOfBoostedProposals)
uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals
//in the threshold calculation to prevent overflow
uint256 quietEndingPeriod; //quite ending period
uint256 proposingRepReward;//proposer reputation reward.
uint256 votersReputationLossRatio;//Unsuccessful pre booster
//voters lose votersReputationLossRatio% of their reputation.
uint256 minimumDaoBounty;
uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula
//(daoBountyConst * averageBoostDownstakes)/100 .
uint256 activationTime;//the point in time after which proposals can be created.
//if this address is set so only this address is allowed to vote of behalf of someone else.
address voteOnBehalf;
}
struct Voter {
uint256 vote; // YES(1) ,NO(2)
uint256 reputation; // amount of voter's reputation
bool preBoosted;
}
struct Staker {
uint256 vote; // YES(1) ,NO(2)
uint256 amount; // amount of staker's stake
uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation.
}
struct Proposal {
bytes32 organizationId; // the organization unique identifier the proposal is target to.
address callbacks; // should fulfill voting callbacks interface.
ProposalState state;
uint256 winningVote; //the winning vote.
address proposer;
//the proposal boosted period limit . it is updated for the case of quiteWindow mode.
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time.
uint256 daoBounty;
uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers.
uint256 confidenceThreshold;
//The percentage from upper stakes which the caller for the expiration was given.
uint256 expirationCallBountyPercentage;
uint[3] times; //times[0] - submittedTime
//times[1] - boostedPhaseTime
//times[2] -preBoostedPhaseTime;
// vote reputation
mapping(uint256 => uint256 ) votes;
// vote reputation
mapping(uint256 => uint256 ) preBoostedVotes;
// address voter
mapping(address => Voter ) voters;
// vote stakes
mapping(uint256 => uint256 ) stakes;
// address staker
mapping(address => Staker ) stakers;
}
event STAKE61(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event REDEEM77(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMDAOBOUNTY80(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMREPUTATION31(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event STATECHANGE55(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING
event GPEXECUTEPROPOSAL49(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING
event EXPIRATIONCALLBOUNTY13(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING
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(bytes32=>uint) public orgBoostedProposalsCnt;
//organizationId => organization
mapping(bytes32 => address ) public organizations;
//organizationId => averageBoostDownstakes
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public num_of_choices20 = 2; //inject NONSTANDARD NAMING
uint256 constant public no97 = 2; //inject NONSTANDARD NAMING
uint256 constant public yes52 = 1; //inject NONSTANDARD NAMING
uint256 public proposalsCnt; // Total number of proposals
ierc2016 public stakingToken;
address constant private gen_token_address24 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING
uint256 constant private max_boosted_proposals66 = 4096; //inject NONSTANDARD NAMING
constructor(ierc2016 _stakingToken) public {
//The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS .
//This will work for a network which already hosted the GEN token on this address (e.g mainnet).
//If such contract address does not exist in the network (e.g ganache)
//the contract will use the _stakingToken param as the
//staking token address.
if (address(gen_token_address24).ISCONTRACT13()) {
stakingToken = ierc2016(gen_token_address24);
} else {
stakingToken = _stakingToken;
}
}
modifier VOTABLE14(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(_ISVOTABLE26(_proposalId));
_;
}
function PROPOSE48(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING
external
returns(bytes32)
{
// solhint-disable-next-line not-rely-on-time
require(now > parameters[_paramsHash].activationTime, "not active yet");
//Check parameters existence.
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
// Generate a unique ID:
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.ADD40(1);
// Open proposal:
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
// solhint-disable-next-line not-rely-on-time
proposal.times[0] = now;//submitted time
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = no97;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
//calc dao bounty
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.MUL16(averagesDownstakesOfBoosted[proposal.organizationId]).DIV25(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[no97] = proposal.daoBountyRemain;//dao downstake on the proposal
Staker storage staker = proposals[proposalId].stakers[organizations[proposal.organizationId]];
staker.vote = no97;
staker.amount = proposal.daoBountyRemain;
emit NEWPROPOSAL82(proposalId, organizations[proposal.organizationId], num_of_choices20, _proposer, _paramsHash);
return proposalId;
}
function EXECUTEBOOSTED98(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted);
require(_EXECUTE0(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
// solhint-disable-next-line not-rely-on-time
(uint(1).ADD40(now.SUB37(proposal.currentBoostedVotePeriodLimit.ADD40(proposal.times[1])).DIV25(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.MUL16(proposal.stakes[yes52]).DIV25(100);
require(stakingToken.TRANSFER74(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit EXPIRATIONCALLBOUNTY13(_proposalId, msg.sender, expirationCallBounty);
}
function SETPARAMETERS19( //inject NONSTANDARD NAMING
uint[11] calldata _params, //use array here due to stack too deep issue.
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = GETPARAMETERSHASH35(_params, _voteOnBehalf);
//set a limit for power for a given alpha to prevent overflow
uint256 limitExponent = 172;//for alpha less or equal 2
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).FRACTION6(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
// solhint-disable-next-line function-max-lines,code-complexity
function REDEEM91(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == yes52) {
lostReputation = proposal.preBoostedVotes[no97];
} else {
lostReputation = proposal.preBoostedVotes[yes52];
}
lostReputation = (lostReputation.MUL16(params.votersReputationLossRatio))/100;
//as staker
Staker storage staker = proposal.stakers[_beneficiary];
if (staker.amount > 0) {
if (proposal.state == ProposalState.ExpiredInQueue) {
//Stakes of a proposal that expires in Queue are sent back to stakers
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
uint256 totalStakes = proposal.stakes[yes52].ADD40(proposal.stakes[no97]);
if (staker.vote == yes52) {
uint256 _totalStakes =
((totalStakes.MUL16(100 - proposal.expirationCallBountyPercentage))/100) - proposal.daoBounty;
rewards[0] = (staker.amount.MUL16(_totalStakes))/totalWinningStakes;
} else {
rewards[0] = (staker.amount.MUL16(totalStakes))/totalWinningStakes;
if (organizations[proposal.organizationId] == _beneficiary) {
//dao redeem it reward
rewards[0] = rewards[0].SUB37(proposal.daoBounty);
}
}
}
staker.amount = 0;
}
//as voter
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
//give back reputation for the voter
rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
uint256 preBoostedVotes = proposal.preBoostedVotes[yes52].ADD40(proposal.preBoostedVotes[no97]);
rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100)
.ADD40((voter.reputation.MUL16(lostReputation))/preBoostedVotes);
}
voter.reputation = 0;
}
//as proposer
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes52)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.SUB37(rewards[0]);
require(stakingToken.TRANSFER74(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit REDEEM77(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].ADD40(rewards[2]) != 0) {
votingmachinecallbacksinterface79(proposal.callbacks)
.MINTREPUTATION65(rewards[1].ADD40(rewards[2]), _beneficiary, _proposalId);
emit REDEEMREPUTATION31(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].ADD40(rewards[2])
);
}
}
function REDEEMDAOBOUNTY7(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == yes52)&&
(totalWinningStakes != 0)) {
//as staker
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(votingmachinecallbacksinterface79(proposal.callbacks)
.BALANCEOFSTAKINGTOKEN17(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.SUB37(potentialAmount);
require(
votingmachinecallbacksinterface79(proposal.callbacks)
.STAKINGTOKENTRANSFER23(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit REDEEMDAOBOUNTY80(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function SHOULDBOOST32(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING
Proposal memory proposal = proposals[_proposalId];
return (_SCORE65(_proposalId) > THRESHOLD35(proposal.paramsHash, proposal.organizationId));
}
function THRESHOLD35(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.POW66(power);
}
function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING
uint[11] memory _params,//use array here due to stack too deep issue.
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
//double call to keccak256 to avoid deep stack issue when call with too many params.
return keccak256(
abi.encodePacked(
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])
),
_voteOnBehalf
));
}
// solhint-disable-next-line function-max-lines,code-complexity
function _EXECUTE0(bytes32 _proposalId) internal VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
votingmachinecallbacksinterface79(proposal.callbacks).GETTOTALREPUTATIONSUPPLY93(_proposalId);
//first divide by 100 to prevent overflow
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = no97;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId);
if (_SCORE65(_proposalId) > confidenceThreshold) {
//change proposal mode to PreBoosted mode.
proposal.state = ProposalState.PreBoosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId);
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if ((_SCORE65(_proposalId) > confidenceThreshold) &&
(orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals66)) {
//change proposal mode to Boosted mode.
proposal.state = ProposalState.Boosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
//add a value to average -> average = average + ((value - average) / nbValues)
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
// solium-disable-next-line indentation
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[no97])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else { //check the Confidence level is stable
uint256 proposalScore = _SCORE65(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.MIN92(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].SUB37(1);
//remove a value from average = ((average * nbValues) - value) / (nbValues - 1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.MUL16(boostedProposals+1).SUB37(proposal.stakes[no97]))/boostedProposals;
}
}
emit EXECUTEPROPOSAL67(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPEXECUTEPROPOSAL49(_proposalId, executionState);
proposalexecuteinterface9(proposal.callbacks).EXECUTEPROPOSAL85(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit STATECHANGE55(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _STAKE17(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING
// 0 is not a valid vote.
require(_vote <= num_of_choices20 && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_EXECUTE0(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
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;
}
uint256 amount = _amount;
require(stakingToken.TRANSFERFROM94(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.ADD40(amount); //update totalRedeemableStakes
staker.amount = staker.amount.ADD40(amount);
//This is to prevent average downstakes calculation overflow
//Note that any how GEN cap is 100000000 ether.
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == yes52) {
staker.amount4Bounty = staker.amount4Bounty.ADD40(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.ADD40(proposal.stakes[_vote]);
emit STAKE61(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _EXECUTE0(_proposalId);
}
// solhint-disable-next-line function-max-lines,code-complexity
function INTERNALVOTE44(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING
require(_vote <= num_of_choices20 && _vote > 0, "0 < _vote <= 2");
if (_EXECUTE0(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
// Check voter has enough reputation:
uint256 reputation = votingmachinecallbacksinterface79(proposal.callbacks).REPUTATIONOF100(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 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.ADD40(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[no97] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == yes52)) {
if (proposal.state == ProposalState.Boosted &&
// solhint-disable-next-line not-rely-on-time
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
//quietEndingPeriod
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.ADD40(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.MUL16(rep))/100;
votingmachinecallbacksinterface79(proposal.callbacks).BURNREPUTATION8(reputationDeposit, _voter, _proposalId);
}
emit VOTEPROPOSAL81(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _EXECUTE0(_proposalId);
}
function _SCORE65(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
//proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal.
return proposal.stakes[yes52]/proposal.stakes[no97];
}
function _ISVOTABLE26(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
// File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol
contract genesisprotocol36 is intvoteinterface31, genesisprotocollogic61 { //inject NONSTANDARD NAMING
using ecdsa86 for bytes32;
// Digest describing the data the user signs according EIP 712.
// Needs to match what is passed to Metamask.
bytes32 public constant delegation_hash_eip71264 = //inject NONSTANDARD NAMING
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce; //stakes Nonce
constructor(ierc2016 _stakingToken)
public
// solhint-disable-next-line no-empty-blocks
genesisprotocollogic61(_stakingToken) {
}
function STAKE3(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING
return _STAKE17(_proposalId, _vote, _amount, msg.sender);
}
function STAKEWITHSIGNATURE10( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
// Recreate the digest the user signed
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
delegation_hash_eip71264, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).TOETHSIGNEDMESSAGEHASH91();
}
address staker = delegationDigest.RECOVER59(_signature);
//a garbage staker address due to wrong signature will revert due to lack of approval and funds.
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].ADD40(1);
return _STAKE17(_proposalId, _vote, _amount, staker);
}
function VOTE79(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING
external
VOTABLE14(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return INTERNALVOTE44(_proposalId, voter, _vote, _amount);
}
function CANCELVOTE62(bytes32 _proposalId) external VOTABLE14(_proposalId) { //inject NONSTANDARD NAMING
//this is not allowed
return;
}
function EXECUTE34(bytes32 _proposalId) external VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
return _EXECUTE0(_proposalId);
}
function GETNUMBEROFCHOICES23(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING
return num_of_choices20;
}
function GETPROPOSALTIMES43(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING
return proposals[_proposalId].times;
}
function VOTEINFO83(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].votes[_choice];
}
function ISVOTABLE72(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING
return _ISVOTABLE26(_proposalId);
}
function PROPOSALSTATUS51(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING
return (
proposals[_proposalId].preBoostedVotes[yes52],
proposals[_proposalId].preBoostedVotes[no97],
proposals[_proposalId].stakes[yes52],
proposals[_proposalId].stakes[no97]
);
}
function GETPROPOSALORGANIZATION83(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].organizationId);
}
function GETSTAKER73(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function VOTESTAKE72(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].stakes[_vote];
}
function WINNINGVOTE73(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].winningVote;
}
function STATE40(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING
return proposals[_proposalId].state;
}
function ISABSTAINALLOW86() external pure returns(bool) { //inject NONSTANDARD NAMING
return false;
}
function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING
return (yes52, no97);
}
function SCORE19(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING
return _SCORE65(_proposalId);
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/votingMachines/VotingMachineCallbacks.sol
contract votingmachinecallbacks93 is votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING
struct ProposalInfo {
uint256 blockNumber; // the proposal's block number
avatar70 avatar; // the proposal's avatar
address votingMachine;
}
modifier ONLYVOTINGMACHINE57(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(msg.sender == proposalsInfo[_proposalId].votingMachine, "only VotingMachine");
_;
}
//proposalId -> ProposalInfo
mapping(bytes32 => ProposalInfo ) public proposalsInfo;
function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool)
{
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (avatar == avatar70(0)) {
return false;
}
return controllerinterface59(avatar.OWNER8()).MINTREPUTATION65(_amount, _beneficiary, address(avatar));
}
function BURNREPUTATION8(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool)
{
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (avatar == avatar70(0)) {
return false;
}
return controllerinterface59(avatar.OWNER8()).BURNREPUTATION8(_amount, _beneficiary, address(avatar));
}
function STAKINGTOKENTRANSFER23( //inject NONSTANDARD NAMING
ierc2016 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool)
{
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (avatar == avatar70(0)) {
return false;
}
return controllerinterface59(avatar.OWNER8()).EXTERNALTOKENTRANSFER67(_stakingToken, _beneficiary, _amount, avatar);
}
function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (proposalsInfo[_proposalId].avatar == avatar70(0)) {
return 0;
}
return _stakingToken.BALANCEOF62(address(avatar));
}
function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[_proposalId];
if (proposal.avatar == avatar70(0)) {
return 0;
}
return proposal.avatar.nativeReputation().TOTALSUPPLYAT94(proposal.blockNumber);
}
function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[_proposalId];
if (proposal.avatar == avatar70(0)) {
return 0;
}
return proposal.avatar.nativeReputation().BALANCEOFAT72(_owner, proposal.blockNumber);
}
}
// File: contracts/universalSchemes/GenericScheme.sol
contract genericscheme3 is universalscheme48, votingmachinecallbacks93, proposalexecuteinterface9 { //inject NONSTANDARD NAMING
event NEWCALLPROPOSAL18( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _callData,
string _descriptionHash
);
event PROPOSALEXECUTED2( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _genericCallReturnValue
);
event PROPOSALEXECUTEDBYVOTINGMACHINE53( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
int256 _param
);
event PROPOSALDELETED34(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING
// Details of a voting proposal:
struct CallProposal {
bytes callData;
bool exist;
bool passed;
}
// A mapping from the organization (Avatar) address to the saved data of the organization:
mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals;
struct Parameters {
intvoteinterface31 intVote;
bytes32 voteParams;
address contractToCall;
}
// A mapping from hashes to parameters (use to store a particular configuration on the controller)
mapping(bytes32=>Parameters) public parameters;
function EXECUTEPROPOSAL85(bytes32 _proposalId, int256 _decision) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool) {
avatar70 avatar = proposalsInfo[_proposalId].avatar;
CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed == false, "cannot execute twice");
if (_decision == 1) {
proposal.passed = true;
EXECUTE34(_proposalId);
} else {
delete organizationsProposals[address(avatar)][_proposalId];
emit PROPOSALDELETED34(address(avatar), _proposalId);
}
emit PROPOSALEXECUTEDBYVOTINGMACHINE53(address(avatar), _proposalId, _decision);
return true;
}
function EXECUTE34(bytes32 _proposalId) public { //inject NONSTANDARD NAMING
avatar70 avatar = proposalsInfo[_proposalId].avatar;
Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(avatar)];
CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed, "proposal must passed by voting machine");
proposal.exist = false;
bytes memory genericCallReturnValue;
bool success;
controllerinterface59 controller = controllerinterface59(avatar70(avatar).OWNER8());
(success, genericCallReturnValue) = controller.GENERICCALL24(params.contractToCall, proposal.callData, avatar);
if (success) {
delete organizationsProposals[address(avatar)][_proposalId];
emit PROPOSALDELETED34(address(avatar), _proposalId);
emit PROPOSALEXECUTED2(address(avatar), _proposalId, genericCallReturnValue);
} else {
proposal.exist = true;
}
}
function SETPARAMETERS19( //inject NONSTANDARD NAMING
bytes32 _voteParams,
intvoteinterface31 _intVote,
address _contractToCall
) public returns(bytes32)
{
bytes32 paramsHash = GETPARAMETERSHASH35(_voteParams, _intVote, _contractToCall);
parameters[paramsHash].voteParams = _voteParams;
parameters[paramsHash].intVote = _intVote;
parameters[paramsHash].contractToCall = _contractToCall;
return paramsHash;
}
function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING
bytes32 _voteParams,
intvoteinterface31 _intVote,
address _contractToCall
) public pure returns(bytes32)
{
return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall));
}
function PROPOSECALL64(avatar70 _avatar, bytes memory _callData, string memory _descriptionHash) //inject NONSTANDARD NAMING
public
returns(bytes32)
{
Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)];
intvoteinterface31 intVote = params.intVote;
bytes32 proposalId = intVote.PROPOSE48(2, params.voteParams, msg.sender, address(_avatar));
organizationsProposals[address(_avatar)][proposalId] = CallProposal({
callData: _callData,
exist: true,
passed: false
});
proposalsInfo[proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar,
votingMachine:address(params.intVote)
});
emit NEWCALLPROPOSAL18(address(_avatar), proposalId, _callData, _descriptionHash);
return proposalId;
}
function GETCONTRACTTOCALL27(avatar70 _avatar) public view returns(address) { //inject NONSTANDARD NAMING
return parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)].contractToCall;
}
} | inject NONSTANDARD NAMING | function _BURNFROM86(address account, uint256 value) internal { | 12,775,726 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
//Interface
import { ITokenERC20 } from "../interfaces/token/ITokenERC20.sol";
// Token
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol";
// Security
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
// Signature utils
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol";
// Meta transactions
import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol";
// Utils
import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol";
import "../lib/CurrencyTransferLib.sol";
import "../lib/FeeType.sol";
// Thirdweb top-level
import "../interfaces/ITWFee.sol";
contract TokenERC20 is
Initializable,
ReentrancyGuardUpgradeable,
ERC2771ContextUpgradeable,
MulticallUpgradeable,
ERC20BurnableUpgradeable,
ERC20PausableUpgradeable,
ERC20VotesUpgradeable,
ITokenERC20,
AccessControlEnumerableUpgradeable
{
using ECDSAUpgradeable for bytes32;
bytes32 private constant MODULE_TYPE = bytes32("TokenERC20");
uint256 private constant VERSION = 1;
bytes32 private constant TYPEHASH =
keccak256(
"MintRequest(address to,address primarySaleRecipient,uint256 quantity,uint256 price,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)"
);
bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 internal constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 internal constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
/// @dev The thirdweb contract with fee related information.
ITWFee internal immutable thirdwebFee;
/// @dev Returns the URI for the storefront-level metadata of the contract.
string public contractURI;
/// @dev Max bps in the thirdweb system
uint128 internal constant MAX_BPS = 10_000;
/// @dev The % of primary sales collected by the contract as fees.
uint128 internal platformFeeBps;
/// @dev The adress that receives all primary sales value.
address internal platformFeeRecipient;
/// @dev The adress that receives all primary sales value.
address public primarySaleRecipient;
/// @dev Mapping from mint request UID => whether the mint request is processed.
mapping(bytes32 => bool) private minted;
constructor(address _thirdwebFee) initializer {
thirdwebFee = ITWFee(_thirdwebFee);
}
/// @dev Initiliazes the contract, like a constructor.
function initialize(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _primarySaleRecipient,
address _platformFeeRecipient,
uint256 _platformFeeBps
) external initializer {
__ERC2771Context_init_unchained(_trustedForwarders);
__ERC20Permit_init(_name);
__ERC20_init_unchained(_name, _symbol);
contractURI = _contractURI;
primarySaleRecipient = _primarySaleRecipient;
platformFeeRecipient = _platformFeeRecipient;
platformFeeBps = uint128(_platformFeeBps);
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, _defaultAdmin);
_setupRole(MINTER_ROLE, _defaultAdmin);
_setupRole(PAUSER_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, address(0));
}
/// @dev Returns the module type of the contract.
function contractType() external pure virtual returns (bytes32) {
return MODULE_TYPE;
}
/// @dev Returns the version of the contract.
function contractVersion() external pure virtual returns (uint8) {
return uint8(VERSION);
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._afterTokenTransfer(from, to, amount);
}
/// @dev Runs on every transfer.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) {
require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "transfers restricted.");
}
}
function _mint(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._mint(account, amount);
}
function _burn(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._burn(account, amount);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "not minter.");
_mintTo(to, amount);
}
/// @dev Verifies that a mint request is signed by an account holding MINTER_ROLE (at the time of the function call).
function verify(MintRequest calldata _req, bytes calldata _signature) public view returns (bool, address) {
address signer = recoverAddress(_req, _signature);
return (!minted[_req.uid] && hasRole(MINTER_ROLE, signer), signer);
}
/// @dev Mints tokens according to the provided mint request.
function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant {
address signer = verifyRequest(_req, _signature);
address receiver = _req.to == address(0) ? _msgSender() : _req.to;
address saleRecipient = _req.primarySaleRecipient == address(0)
? primarySaleRecipient
: _req.primarySaleRecipient;
collectPrice(saleRecipient, _req.currency, _req.price);
_mintTo(receiver, _req.quantity);
emit TokensMintedWithSignature(signer, receiver, _req);
}
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
primarySaleRecipient = _saleRecipient;
emit PrimarySaleRecipientUpdated(_saleRecipient);
}
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_platformFeeBps <= MAX_BPS, "bps <= 10000.");
platformFeeBps = uint64(_platformFeeBps);
platformFeeRecipient = _platformFeeRecipient;
emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps);
}
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address, uint16) {
return (platformFeeRecipient, uint16(platformFeeBps));
}
/// @dev Collects and distributes the primary sale value of tokens being claimed.
function collectPrice(
address _primarySaleRecipient,
address _currency,
uint256 _price
) internal {
if (_price == 0) {
return;
}
uint256 platformFees = (_price * platformFeeBps) / MAX_BPS;
(address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.PRIMARY_SALE);
uint256 twFee = (_price * twFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
require(msg.value == _price, "must send total price.");
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), twFeeRecipient, twFee);
CurrencyTransferLib.transferCurrency(
_currency,
_msgSender(),
_primarySaleRecipient,
_price - platformFees - twFee
);
}
/// @dev Mints `amount` of tokens to `to`
function _mintTo(address _to, uint256 _amount) internal {
_mint(_to, _amount);
emit TokensMinted(_to, _amount);
}
/// @dev Verifies that a mint request is valid.
function verifyRequest(MintRequest calldata _req, bytes calldata _signature) internal returns (address) {
(bool success, address signer) = verify(_req, _signature);
require(success, "invalid signature");
require(
_req.validityStartTimestamp <= block.timestamp && _req.validityEndTimestamp >= block.timestamp,
"request expired"
);
minted[_req.uid] = true;
return signer;
}
/// @dev Returns the address of the signer of the mint request.
function recoverAddress(MintRequest calldata _req, bytes calldata _signature) internal view returns (address) {
return _hashTypedDataV4(keccak256(_encodeRequest(_req))).recover(_signature);
}
/// @dev Resolves 'stack too deep' error in `recoverAddress`.
function _encodeRequest(MintRequest calldata _req) internal pure returns (bytes memory) {
return
abi.encode(
TYPEHASH,
_req.to,
_req.primarySaleRecipient,
_req.quantity,
_req.price,
_req.currency,
_req.validityStartTimestamp,
_req.validityEndTimestamp,
_req.uid
);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser.");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser.");
_unpause();
}
/// @dev Sets contract URI for the storefront-level metadata of the contract.
function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) {
contractURI = _uri;
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../IThirdwebContract.sol";
import "../IThirdwebPlatformFee.sol";
import "../IThirdwebPrimarySale.sol";
interface ITokenERC20 is IThirdwebContract, IThirdwebPrimarySale, IThirdwebPlatformFee, IERC20Upgradeable {
/**
* @notice The body of a request to mint tokens.
*
* @param to The receiver of the tokens to mint.
* @param primarySaleRecipient The receiver of the primary sale funds from the mint.
* @param quantity The quantity of tpkens to mint.
* @param price Price to pay for minting with the signature.
* @param currency The currency in which the price per token must be paid.
* @param validityStartTimestamp The unix timestamp after which the request is valid.
* @param validityEndTimestamp The unix timestamp after which the request expires.
* @param uid A unique identifier for the request.
*/
struct MintRequest {
address to;
address primarySaleRecipient;
uint256 quantity;
uint256 price;
address currency;
uint128 validityStartTimestamp;
uint128 validityEndTimestamp;
bytes32 uid;
}
/// @dev Emitted when an account with MINTER_ROLE mints an NFT.
event TokensMinted(address indexed mintedTo, uint256 quantityMinted);
/// @dev Emitted when tokens are minted.
event TokensMintedWithSignature(address indexed signer, address indexed mintedTo, MintRequest mintRequest);
/// @dev Emitted when a new sale recipient is set.
event PrimarySaleRecipientUpdated(address indexed recipient);
/// @dev Emitted when fee on primary sales is updated.
event PlatformFeeInfoUpdated(address platformFeeRecipient, uint256 platformFeeBps);
/**
* @notice Verifies that a mint request is signed by an account holding
* MINTER_ROLE (at the time of the function call).
*
* @param req The mint request.
* @param signature The signature produced by an account signing the mint request.
*
* returns (success, signer) Result of verification and the recovered address.
*/
function verify(MintRequest calldata req, bytes calldata signature)
external
view
returns (bool success, address signer);
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) external;
/**
* @notice Mints an NFT according to the provided mint request.
*
* @param req The mint request.
* @param signature he signature produced by an account signing the mint request.
*/
function mintWithSignature(MintRequest calldata req, bytes calldata signature) external payable;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.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 ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal onlyInitializing {
}
function __ERC20Burnable_init_unchained() internal onlyInitializing {
}
/**
* @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 {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../security/PausableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Votes.sol)
pragma solidity ^0.8.0;
import "./draft-ERC20PermitUpgradeable.sol";
import "../../../utils/math/MathUpgradeable.sol";
import "../../../governance/utils/IVotesUpgradeable.sol";
import "../../../utils/math/SafeCastUpgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
*
* _Available since v4.2._
*/
abstract contract ERC20VotesUpgradeable is Initializable, IVotesUpgradeable, ERC20PermitUpgradeable {
function __ERC20Votes_init() internal onlyInitializing {
}
function __ERC20Votes_init_unchained() internal onlyInitializing {
}
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCastUpgradeable.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual override returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view virtual override returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual override {
_delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSAUpgradeable.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(block.number), votes: SafeCastUpgradeable.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual 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 virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// 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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (metatx/ERC2771Context.sol)
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
mapping(address => bool) private _trustedForwarder;
function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing {
__Context_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
}
function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing {
for (uint256 i = 0; i < trustedForwarder.length; i++) {
_trustedForwarder[trustedForwarder[i]] = true;
}
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return _trustedForwarder[forwarder];
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./AddressUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract MulticallUpgradeable is Initializable {
function __Multicall_init() internal onlyInitializing {
}
function __Multicall_init_unchained() internal onlyInitializing {
}
/**
* @dev Receives and executes a batch of function calls on this contract.
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = _functionDelegateCall(address(this), data[i]);
}
return results;
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
// Helper interfaces
import { IWETH } from "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
library CurrencyTransferLib {
/// @dev The address interpreted as native token of the chain.
address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Transfers a given amount of currency.
function transferCurrency(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
safeTransferNativeToken(_to, _amount);
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Transfers a given amount of currency. (With native token wrapping)
function transferCurrencyWithWrapperAndBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount,
address _nativeTokenWrapper
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
// withdraw from weth then transfer withdrawn native token to recipient
IWETH(_nativeTokenWrapper).withdraw(_amount);
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
} else if (_to == address(this)) {
// store native currency in weth
require(_amount == msg.value, "msg.value != amount");
IWETH(_nativeTokenWrapper).deposit{ value: _amount }();
} else {
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
}
} else {
safeTransferERC20WithBalanceCheck(_currency, _from, _to, _amount);
}
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
bool success = _from == address(this)
? IERC20Upgradeable(_currency).transfer(_to, _amount)
: IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount);
require(success, "currency transfer failed.");
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20WithBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
uint256 balBefore = IERC20Upgradeable(_currency).balanceOf(_to);
bool success = _from == address(this)
? IERC20Upgradeable(_currency).transfer(_to, _amount)
: IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount);
uint256 balAfter = IERC20Upgradeable(_currency).balanceOf(_to);
require(success && (balAfter == balBefore + _amount), "currency transfer failed.");
}
/// @dev Transfers `amount` of native token to `to`.
function safeTransferNativeToken(address to, uint256 value) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
require(success, "native token transfer failed");
}
/// @dev Transfers `amount` of native token to `to`. (With native token wrapping)
function safeTransferNativeTokenWithWrapper(
address to,
uint256 value,
address _nativeTokenWrapper
) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
if (!success) {
IWETH(_nativeTokenWrapper).deposit{ value: value }();
require(IERC20Upgradeable(_nativeTokenWrapper).transfer(to, value), "transfer failed");
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
library FeeType {
uint256 internal constant PRIMARY_SALE = 0;
uint256 internal constant MARKET_SALE = 1;
uint256 internal constant SPLIT = 2;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface ITWFee {
function getFeeInfo(address _proxy, uint256 _type) external view returns (address recipient, uint256 bps);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebContract {
/// @dev Returns the module type of the contract.
function contractType() external pure returns (bytes32);
/// @dev Returns the version of the contract.
function contractVersion() external pure returns (uint8);
/// @dev Returns the metadata URI of the contract.
function contractURI() external view returns (string memory);
/**
* @dev Sets contract URI for the storefront-level metadata of the contract.
* Only module admin can call this function.
*/
function setContractURI(string calldata _uri) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPlatformFee {
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address platformFeeRecipient, uint16 platformFeeBps);
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPrimarySale {
/// @dev The adress that receives all primary sales value.
function primarySaleRecipient() external view returns (address);
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
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 Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// 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 {
}
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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
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 onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_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());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../utils/CountersUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*
* _Available since v4.5._
*/
interface IVotesUpgradeable {
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*/
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
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 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// 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 {
}
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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
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: Apache-2.0
pragma solidity ^0.8.11;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address to, uint256 value) external returns (bool);
} | Mints `amount` of tokens to `to` | function _mintTo(address _to, uint256 _amount) internal {
_mint(_to, _amount);
emit TokensMinted(_to, _amount);
}
| 409,469 |
pragma solidity ^0.4.24;
/**
* Version: 0.1.0
* The ERC-1384 is an Equity Agreement Standard used for smart contracts on Ethereum
* blockchain for project equity allocation.
* The current ERC-1384 agreement standard version is 0.1.0, which includes the basic
* information of the project query, equity creation, confirmation of equity validity,
* equity transfer, record of equity transfer and other functions.
*/
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a);
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b <= a);
c = a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0);
c = a / b;
}
}
contract ERC20 {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ERC1384Interface {
function name() external view returns (string _name);
function FasNum() external view returns (uint256 _FasNum);
function owner() external view returns (address _owner);
function createTime() external view returns (uint256 _createTime);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _FasId) public view returns (address _owner);
function exists(uint256 _FasId) public view returns (bool);
function allOwnedFas(address _owner) public view returns (uint256[] _allOwnedFasList);
function getTransferRecords(uint256 _FasId) public view returns (address[] _preOwners);
function transfer(address _to, uint256[] _FasId) public;
function createVote() public payable returns (uint256 _voteId);
function vote(uint256 _voteId, uint256 _vote_status_value) public;
function getVoteResult(uint256 _voteId) public payable returns (bool result);
function dividend(address _token_owner) public;
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _FasId
);
event Vote(
uint256 _voteId
);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address internal project_owner;
address internal new_project_owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
project_owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == project_owner);
_;
}
function transferOwnership(address _new_project_owner) public onlyOwner {
new_project_owner = _new_project_owner;
}
}
contract ERC1384BasicContract is ERC1384Interface, Owned {
using SafeMath for uint256;
// Project Name
string internal proejct_name;
// Project Fas Number
uint256 internal project_fas_number;
// Project Create Time
uint256 internal project_create_time;
// Owner Number
uint256 internal owners_num;
// Vote Number
uint256 internal votes_num;
address internal token_0x_address;
/**
* @dev Constructor function
*/
constructor(string _project_name, address _token_0x_address) public {
proejct_name = _project_name;
project_fas_number = 100;
project_create_time = block.timestamp;
token_0x_address = _token_0x_address;
for(uint i = 0; i < project_fas_number; i++)
{
FasOwner[i] = project_owner;
ownedFasCount[project_owner] = ownedFasCount[project_owner].add(1);
address[1] memory preOwnerList = [project_owner];
transferRecords[i] = preOwnerList;
}
owners_num = 0;
votes_num = 0;
ownerExists[project_owner] = true;
addOwnerNum(project_owner);
}
/**
* @dev Gets the project name
* @return string representing the project name
*/
function name() external view returns (string) {
return proejct_name;
}
/**
* @dev Gets the project Fas number
* @return uint256 representing the project Fas number
*/
function FasNum() external view returns (uint256) {
return project_fas_number;
}
/**
* @dev Gets the project owner
* @return address representing the project owner
*/
function owner() external view returns (address) {
return project_owner;
}
/**
* @dev Gets the project create time
* @return uint256 representing the project create time
*/
function createTime() external view returns (uint256) {
return project_create_time;
}
// Mapping from number of owner to owner
mapping (uint256 => address) internal ownerNum;
mapping (address => bool) internal ownerExists;
// Mapping from Fas ID to owner
mapping (uint256 => address) internal FasOwner;
// Mapping from owner to number of owned Fas
mapping (address => uint256) internal ownedFasCount;
// Mapping from Fas ID to approved address
mapping (uint256 => address) internal FasApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
// Mapping from Fas ID to previous owners
mapping (uint256 => address[]) internal transferRecords;
// Mapping from vote ID to vote result
mapping (uint256 => mapping (uint256 => uint256)) internal voteResult;
function acceptOwnership() public {
require(msg.sender == new_project_owner);
emit OwnershipTransferred(project_owner, new_project_owner);
transferForOwnerShip(project_owner, new_project_owner, allOwnedFas(project_owner));
project_owner = new_project_owner;
new_project_owner = address(0);
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedFasCount[_owner];
}
/**
* @dev Gets the owner of the specified Fas ID
* @param _FasId uint256 ID of the Fas to query the owner of
* @return owner address currently marked as the owner of the given Fas ID
*/
function ownerOf(uint256 _FasId) public view returns (address) {
address _owner = FasOwner[_FasId];
require(_owner != address(0));
return _owner;
}
/**
* @dev Returns whether the specified Fas exists
* @param _FasId uint256 ID of the Fas to query the existence of
* @return whether the Fas exists
*/
function exists(uint256 _FasId) public view returns (bool) {
address _owner = FasOwner[_FasId];
return _owner != address(0);
}
/**
* @dev Gets the owner of all owned Fas
* @param _owner address to query the balance of
* @return the FasId list of owners
*/
function allOwnedFas(address _owner) public view returns (uint256[]) {
uint256 _ownedFasCount = ownedFasCount[_owner];
uint256 j = 0;
uint256[] memory _allOwnedFasList = new uint256[](_ownedFasCount);
for(uint256 i = 0; i < project_fas_number; i++)
{
if(FasOwner[i] == _owner)
{
_allOwnedFasList[j] = i;
j = j.add(1);
}
}
return _allOwnedFasList;
}
/**
* @dev Internal function to add Owner Count to the list of a given address
* @param _owner address representing the new owner
*/
function addOwnerNum(address _owner) internal {
require(ownedFasCount[_owner] != 0);
if(ownerExists[_owner] == false)
{
ownerNum[owners_num] = _owner;
owners_num = owners_num.add(1);
ownerExists[_owner] = true;
}
}
/**
* @dev Internal function to add a Fas ID to the list of a given address
* @param _to address representing the new owner of the given Fas ID
* @param _FasId uint256 ID of the Fas to be added to the Fas list of the given address
*/
function addFasTo(address _to, uint256 _FasId) internal {
require(FasOwner[_FasId] == address(0));
FasOwner[_FasId] = _to;
ownedFasCount[_to] = ownedFasCount[_to].add(1);
}
/**
* @dev Internal function to remove a Fas ID from the list of a given address
* @param _from address representing the previous owner of the given Fas ID
* @param _FasId uint256 ID of the Fas to be removed from the Fas list of the given address
*/
function removeFasFrom(address _from, uint256 _FasId) internal {
require(ownerOf(_FasId) == _from);
ownedFasCount[_from] = ownedFasCount[_from].sub(1);
FasOwner[_FasId] = address(0);
}
/**
* @dev Returns whether the given spender can transfer a given Fas ID
* @param _spender address of the spender to query
* @param _FasId uint256 ID of the Fas to be transferred
* @return bool whether the msg.sender is approved for the given Fas ID,
* is an operator of the owner, or is the owner of the Fas
*/
function isOwner(address _spender, uint256 _FasId) internal view returns (bool){
address _owner = ownerOf(_FasId);
return (_spender == _owner);
}
/**
* @dev Record the transfer records for a Fas ID
* @param _FasId uint256 ID of the Fas
* @return bool record
*/
function transferRecord(address _nowOwner, uint256 _FasId) internal{
address[] memory preOwnerList = transferRecords[_FasId];
address[] memory _preOwnerList = new address[](preOwnerList.length + 1);
for(uint i = 0; i < _preOwnerList.length; ++i)
{
if(i != preOwnerList.length)
{
_preOwnerList[i] = preOwnerList[i];
}
else
{
_preOwnerList[i] = _nowOwner;
}
}
transferRecords[_FasId] = _preOwnerList;
}
/**
* @dev Gets the transfer records for a Fas ID
* @param _FasId uint256 ID of the Fas
* @return address of previous owners
*/
function getTransferRecords(uint256 _FasId) public view returns (address[]) {
return transferRecords[_FasId];
}
/**
* @dev Transfers the ownership of a given Fas ID to a specified address
* @param _project_owner the address of _project_owner
* @param _to address to receive the ownership of the given Fas ID
* @param _FasId uint256 ID of the Fas to be transferred
*/
function transferForOwnerShip(address _project_owner,address _to, uint256[] _FasId) internal{
for(uint i = 0; i < _FasId.length; i++)
{
require(isOwner(_project_owner, _FasId[i]));
require(_to != address(0));
transferRecord(_to, _FasId[i]);
removeFasFrom(_project_owner, _FasId[i]);
addFasTo(_to, _FasId[i]);
}
addOwnerNum(_to);
}
/**
* @dev Transfers the ownership of a given Fas ID to a specified address
* @param _to address to receive the ownership of the given Fas ID
* @param _FasId uint256 ID of the Fas to be transferred
*/
function transfer(address _to, uint256[] _FasId) public{
for(uint i = 0; i < _FasId.length; i++)
{
require(isOwner(msg.sender, _FasId[i]));
require(_to != address(0));
transferRecord(_to, _FasId[i]);
removeFasFrom(msg.sender, _FasId[i]);
addFasTo(_to, _FasId[i]);
emit Transfer(msg.sender, _to, _FasId[i]);
}
addOwnerNum(_to);
}
/**
* @dev Create a new vote
* @return the new vote of ID
*/
function createVote() public payable returns (uint256){
votes_num = votes_num.add(1);
// Vote Agree Number
voteResult[votes_num][0] = 0;
// Vote Disagree Number
voteResult[votes_num][1] = 0;
// Vote Abstain Number
voteResult[votes_num][2] = 0;
// Start Voting Time
voteResult[votes_num][3] = block.timestamp;
emit Vote(votes_num);
return votes_num;
}
/**
* @dev Voting for a given vote ID
* @param _voteId the given vote ID
* @param _vote_status_value uint256 the vote of status, 0 Agree, 1 Disagree, 2 Abstain
*/
function vote(uint256 _voteId, uint256 _vote_status_value) public{
require(_vote_status_value >= 0);
require(_vote_status_value <= 2);
require(block.timestamp <= (voteResult[_voteId][3] + 1 days));
uint256 temp_Fas_count = balanceOf(msg.sender);
if(_vote_status_value == 0)
{
voteResult[_voteId][0] = voteResult[_voteId][0].add(temp_Fas_count);
}
else if(_vote_status_value == 1)
{
voteResult[_voteId][1] = voteResult[_voteId][1].add(temp_Fas_count);
}
else
{
voteResult[_voteId][2] = voteResult[_voteId][2].add(temp_Fas_count);
}
}
/**
* @dev Gets the voting restult for a vote ID
* @param _voteId the given vote ID
* @return the voting restult, true success, false failure
*/
function getVoteResult(uint256 _voteId) public payable returns (bool){
require(block.timestamp > (voteResult[_voteId][3] + 1 days));
uint agree_num = voteResult[_voteId][0];
uint disagree_num = voteResult[_voteId][1];
uint abstain_num = voteResult[_voteId][2];
uint temp_abstain_num = 100 - agree_num - disagree_num;
if(temp_abstain_num != abstain_num)
{
voteResult[_voteId][2] = temp_abstain_num;
}
if(agree_num > disagree_num)
{
return true;
}
else
{
return false;
}
}
/**
* @dev Distribution of benefits
* @param _token_owner Divider's Token address
*/
function dividend(address _token_owner) public{
uint256 temp_allowance = ERC20(token_0x_address).allowance(_token_owner, address(this));
for(uint i = 0; i < owners_num; i++)
{
uint256 temp_Fas_count = balanceOf(ownerNum[i]);
uint256 _dividend = temp_allowance * temp_Fas_count / 100;
ERC20(token_0x_address).transferFrom(_token_owner, ownerNum[i], _dividend);
}
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
} | Distribution of benefits _token_owner Divider's Token address/ | function dividend(address _token_owner) public{
uint256 temp_allowance = ERC20(token_0x_address).allowance(_token_owner, address(this));
for(uint i = 0; i < owners_num; i++)
{
uint256 temp_Fas_count = balanceOf(ownerNum[i]);
uint256 _dividend = temp_allowance * temp_Fas_count / 100;
ERC20(token_0x_address).transferFrom(_token_owner, ownerNum[i], _dividend);
}
}
| 12,981,274 |
pragma solidity 0.8.6;
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);
}
abstract contract IERC20WithCheckpointing {
function balanceOf(address _owner) public view virtual returns (uint256);
function balanceOfAt(address _owner, uint256 _blockNumber)
public
view
virtual
returns (uint256);
function totalSupply() public view virtual returns (uint256);
function totalSupplyAt(uint256 _blockNumber) public view virtual returns (uint256);
}
abstract contract IIncentivisedVotingLockup is IERC20WithCheckpointing {
function getLastUserPoint(address _addr)
external
view
virtual
returns (
int128 bias,
int128 slope,
uint256 ts
);
function createLock(uint256 _value, uint256 _unlockTime) external virtual;
function withdraw() external virtual;
function increaseLockAmount(uint256 _value) external virtual;
function increaseLockLength(uint256 _unlockTime) external virtual;
function eject(address _user) external virtual;
function expireContract() external virtual;
function claimReward() public virtual;
function earned(address _account) public view virtual returns (uint256);
}
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
);
}
interface IBoostDirector {
function getBalance(address _user) external returns (uint256);
function setDirection(
address _old,
address _new,
bool _pokeNew
) external;
function whitelistVaults(address[] calldata _vaults) external;
}
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 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 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);
}
/**
* @dev Return Liquidator Module address from the Nexus
* @return Address of the Liquidator Module contract
*/
function _liquidator() internal view returns (address) {
return nexus.getModule(KEY_LIQUIDATOR);
}
/**
* @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);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
// Internal
/**
* @title BoostDirectorV2
* @author mStable
* @notice Supports the directing of balance from multiple StakedToken contracts up to X accounts
* @dev Uses a bitmap to store the id's of a given users chosen vaults in a gas efficient manner.
*/
contract BoostDirectorV2 is IBoostDirector, ImmutableModule {
event Directed(address user, address boosted);
event RedirectedBoost(address user, address boosted, address replaced);
event Whitelisted(address vaultAddress, uint8 vaultId);
event StakedTokenAdded(address token);
event StakedTokenRemoved(address token);
event BalanceDivisorChanged(uint256 newDivisor);
// Read the vMTA balance from here
IERC20[] public stakedTokenContracts;
// Whitelisted vaults set by governance (only these vaults can read balances)
uint8 private vaultCount;
// Vault address -> internal id for tracking
mapping(address => uint8) public _vaults;
// uint128 packed with up to 16 uint8's. Each uint is a vault ID
mapping(address => uint128) public _directedBitmap;
// Divisor for voting powers to make more reasonable in vault
uint256 private balanceDivisor;
/***************************************
ADMIN
****************************************/
// Simple constructor
constructor(address _nexus) ImmutableModule(_nexus) {
balanceDivisor = 12;
}
/**
* @dev Initialize function - simply sets the initial array of whitelisted vaults
*/
function initialize(address[] calldata _newVaults) external {
require(vaultCount == 0, "Already initialized");
_whitelistVaults(_newVaults);
}
/**
* @dev Adds a staked token to the list, if it does not yet exist
*/
function addStakedToken(address _stakedToken) external onlyGovernor {
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
require(address(stakedTokenContracts[i]) != _stakedToken, "StakedToken already added");
}
stakedTokenContracts.push(IERC20(_stakedToken));
emit StakedTokenAdded(_stakedToken);
}
/**
* @dev Removes a staked token from the list
*/
function removeStakedTkoen(address _stakedToken) external onlyGovernor {
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
// If we find it, then swap it with the last element and delete the end
if (address(stakedTokenContracts[i]) == _stakedToken) {
stakedTokenContracts[i] = stakedTokenContracts[len - 1];
stakedTokenContracts.pop();
emit StakedTokenRemoved(_stakedToken);
return;
}
}
}
/**
* @dev Sets the divisor, by which all balances will be scaled down
*/
function setBalanceDivisor(uint256 _newDivisor) external onlyGovernor {
require(_newDivisor != balanceDivisor, "No change in divisor");
require(_newDivisor < 15, "Divisor too large");
balanceDivisor = _newDivisor;
emit BalanceDivisorChanged(_newDivisor);
}
/**
* @dev Whitelist vaults - only callable by governance. Whitelists vaults, unless they
* have already been whitelisted
*/
function whitelistVaults(address[] calldata _newVaults) external override onlyGovernor {
_whitelistVaults(_newVaults);
}
/**
* @dev Takes an array of newVaults. For each, determines if it is already whitelisted.
* If not, then increment vaultCount and same the vault with new ID
*/
function _whitelistVaults(address[] calldata _newVaults) internal {
uint256 len = _newVaults.length;
require(len > 0, "Must be at least one vault");
for (uint256 i = 0; i < len; i++) {
uint8 id = _vaults[_newVaults[i]];
require(id == 0, "Vault already whitelisted");
vaultCount += 1;
_vaults[_newVaults[i]] = vaultCount;
emit Whitelisted(_newVaults[i], vaultCount);
}
}
/***************************************
Vault
****************************************/
/**
* @dev Gets the balance of a user that has been directed to the caller (a vault).
* If the user has not directed to this vault, or there are less than 6 directed,
* then add this to the list
* @param _user Address of the user for which to get balance
* @return bal Directed balance
*/
function getBalance(address _user) external override returns (uint256 bal) {
// Get vault details
uint8 id = _vaults[msg.sender];
// If vault has not been whitelisted, just return zero
if (id == 0) return 0;
// Get existing bitmap and balance
uint128 bitmap = _directedBitmap[_user];
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
bal += stakedTokenContracts[i].balanceOf(_user);
}
bal /= balanceDivisor;
(bool isWhitelisted, uint8 count, ) = _indexExists(bitmap, id);
if (isWhitelisted) return bal;
if (count < 6) {
_directedBitmap[_user] = _direct(bitmap, count, id);
emit Directed(_user, msg.sender);
return bal;
}
if (count >= 6) return 0;
}
/**
* @dev Directs rewards to a vault, and removes them from the old vault. Provided
* that old is active and the new vault is whitelisted.
* @param _old Address of the old vault that will no longer get boosted
* @param _new Address of the new vault that will get boosted
* @param _pokeNew Bool to say if we should poke the boost on the new vault
*/
function setDirection(
address _old,
address _new,
bool _pokeNew
) external override {
uint8 idOld = _vaults[_old];
uint8 idNew = _vaults[_new];
require(idOld > 0 && idNew > 0, "Vaults not whitelisted");
uint128 bitmap = _directedBitmap[msg.sender];
(bool isWhitelisted, uint8 count, uint8 pos) = _indexExists(bitmap, idOld);
require(isWhitelisted && count >= 6, "No need to replace old");
_directedBitmap[msg.sender] = _direct(bitmap, pos, idNew);
IBoostedVaultWithLockup(_old).pokeBoost(msg.sender);
if (_pokeNew) {
IBoostedVaultWithLockup(_new).pokeBoost(msg.sender);
}
emit RedirectedBoost(msg.sender, _new, _old);
}
/**
* @dev Resets the bitmap given the new _id for _pos. Takes each uint8 in seperate and re-compiles
*/
function _direct(
uint128 _bitmap,
uint8 _pos,
uint8 _id
) internal pure returns (uint128 newMap) {
// bitmap = ... 00000000 00000000 00000011 00001010
// pos = 1, id = 1 = 00000001
// step = ... 00000000 00000000 00000001 00000000
uint8 id;
uint128 step;
for (uint8 i = 0; i < 6; i++) {
unchecked {
// id is either the one that is passed, or existing
id = _pos == i ? _id : uint8(_bitmap >> (i * 8));
step = uint128(uint128(id) << (i * 8));
}
newMap |= step;
}
}
/**
* @dev Given a 128 bit bitmap packed with 8 bit ids, should be able to filter for specific ids by moving
* the bitmap gradually to the right and reading each 8 bit section as a uint8.
*/
function _indexExists(uint128 _bitmap, uint8 _target)
internal
pure
returns (
bool isWhitelisted,
uint8 count,
uint8 pos
)
{
// bitmap = ... 00000000 00000000 00000011 00001010 // positions 1 and 2 have ids 10 and 6 respectively
// e.g.
// i = 1: bitmap moves 8 bits to the right
// bitmap = ... 00000000 00000000 00000000 00000011 // reading uint8 should return 6
uint8 id;
for (uint8 i = 0; i < 6; i++) {
unchecked {
id = uint8(_bitmap >> (i * 8));
}
if (id > 0) count += 1;
if (id == _target) {
isWhitelisted = true;
pos = i;
}
}
}
} | Directs rewards to a vault, and removes them from the old vault. Provided that old is active and the new vault is whitelisted. _old Address of the old vault that will no longer get boosted _new Address of the new vault that will get boosted _pokeNew Bool to say if we should poke the boost on the new vault/ | function setDirection(
address _old,
address _new,
bool _pokeNew
) external override {
uint8 idOld = _vaults[_old];
uint8 idNew = _vaults[_new];
require(idOld > 0 && idNew > 0, "Vaults not whitelisted");
uint128 bitmap = _directedBitmap[msg.sender];
(bool isWhitelisted, uint8 count, uint8 pos) = _indexExists(bitmap, idOld);
require(isWhitelisted && count >= 6, "No need to replace old");
_directedBitmap[msg.sender] = _direct(bitmap, pos, idNew);
IBoostedVaultWithLockup(_old).pokeBoost(msg.sender);
if (_pokeNew) {
IBoostedVaultWithLockup(_new).pokeBoost(msg.sender);
}
emit RedirectedBoost(msg.sender, _new, _old);
}
| 638,722 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
/**
* @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 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);
}
}
}
}
/**
* @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");
}
}
}
library String {
/// @notice Convert a uint value to its decimal string representation
// solium-disable-next-line security/no-assign-params
function fromUint(uint256 _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
/// @notice Convert a bytes32 value to its hex string representation.
function fromBytes32(bytes32 _value) internal pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(32 * 2 + 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < 32; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(_value[i] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(_value[i] & 0x0f))];
}
return string(str);
}
/// @notice Convert an address to its hex string representation.
function fromAddress(address _addr) internal pure returns (string memory) {
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(20 * 2 + 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < 20; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(value[i + 12] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(value[i + 12] & 0x0f))];
}
return string(str);
}
/// @notice Append eight strings.
function add8(
string memory a,
string memory b,
string memory c,
string memory d,
string memory e,
string memory f,
string memory g,
string memory h
) internal pure returns (string memory) {
return string(abi.encodePacked(a, b, c, d, e, f, g, h));
}
}
contract ERC20BridgeGateway {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant BIPS_DENOMINATOR = 10000;
IERC20 public token;
address public owner;
address public admin; // adminAddress
address public feeRecipient; // feeRecipientAddress
mapping(bytes32 => bool) public status; /// @notice Each signature can only be seen once.
bool public safeFundMoving; /// send fund to safe wallet
address public safeFundWallet; /// safe place storing fund
uint16 public depositFee; /// @notice The deposit fee in bips.
uint16 public withdrawFee; /// @notice The withdraw fee in bips.
uint256 public minDepositAmount; /// @notice The deposit fee in bips.
uint256 public minWithdrawAmount; /// @notice The withdraw fee in bips.
uint256 public index = 0; /// index of each deposit/withdraw order
event Deposit(uint256 indexed _index, address indexed _to, uint256 _amount);
event Withdraw(uint256 indexed _index, address indexed _to, uint256 _amount, bytes32 indexed _signedMessageHash);
constructor(
address _token,
address _admin,
address _feeRecipient,
uint16 _depositFee,
uint16 _withdrawFee,
bool _safeFundMoving,
address _safeFundWallet,
uint256 _minDepositAmount,
uint256 _minWithdrawAmount
) public {
require(_token != address(0));
token = IERC20(_token);
admin = _admin;
depositFee = _depositFee;
withdrawFee = _withdrawFee;
feeRecipient = _feeRecipient;
safeFundMoving = _safeFundMoving;
if (_safeFundWallet != address(0)) {
safeFundWallet = _safeFundWallet;
}
minDepositAmount = _minDepositAmount;
minWithdrawAmount = _minWithdrawAmount;
owner = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin, "admin: wut?");
_;
}
modifier onlyOwner() {
require(msg.sender == owner, "!owner");
_;
}
function deposit(uint256 _amount) public {
require(_amount >= minDepositAmount, "Gateway: deposit amount to small");
uint256 feeAmount = _amount.mul(depositFee).div(BIPS_DENOMINATOR);
uint256 amountAfterFee = _amount.sub(feeAmount, "Gateway: fee exceeds amount");
require(token.transferFrom(msg.sender, address(this), _amount), "token transfer failed");
// transfer fee to feeRecipient
if (feeAmount > 0) {
token.safeTransfer(feeRecipient, feeAmount);
}
if (safeFundMoving && safeFundWallet != address(0)) {
token.safeTransfer(safeFundWallet, amountAfterFee);
}
emit Deposit(index, msg.sender, amountAfterFee);
index += 1;
}
function withdraw(
string calldata _symbol,
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) public {
require(_amount >= minDepositAmount, "Gateway: withdraw amount to small");
require(token.balanceOf(address(this)) >= _amount, "Gateway: insufficient balance");
bytes32 payloadHash = keccak256(abi.encode(_symbol, msg.sender));
// Verify signature
bytes32 signedMessageHash = hashForSignature(_symbol, msg.sender, _amount, _nHash);
require(status[signedMessageHash] == false, "Gateway: nonce hash already spent");
if (!verifySignature(signedMessageHash, _sig)) {
// Return a detailed string containing the hash and recovered
// signer. This is somewhat costly but is only run in the revert
// branch.
revert(
String.add8(
"Gateway: invalid signature. pHash: ",
String.fromBytes32(payloadHash),
", amount: ",
String.fromUint(_amount),
", msg.sender: ",
String.fromAddress(msg.sender),
", _nHash: ",
String.fromBytes32(_nHash)
)
);
}
status[signedMessageHash] = true;
// Send `amount - fee` for the recipient and send `fee` to the fee recipient
uint256 feeAmount = _amount.mul(withdrawFee).div(BIPS_DENOMINATOR);
uint256 receivedAmount = _amount.sub(feeAmount, "Gateway: fee exceeds amount");
// Mint amount minus the fee
token.safeTransfer(msg.sender, receivedAmount);
// Mint the fee
if (feeAmount > 0) {
token.safeTransfer(feeRecipient, feeAmount);
}
emit Withdraw(index, msg.sender, receivedAmount, signedMessageHash);
index += 1;
}
/// @notice Allow the owner to update the fee recipient.
/// @param _nextFeeRecipient The address to start paying fees to.
function updateFeeRecipient(address _nextFeeRecipient) public onlyOwner {
require(_nextFeeRecipient != address(0x0), "Gateway: fee recipient cannot be 0x0");
feeRecipient = _nextFeeRecipient;
}
/// @notice Allow the owner to update the admin.
/// @param _nextAdmin The address to start paying fees to.
function updateAdmin(address _nextAdmin) public onlyOwner {
require(_nextAdmin != address(0x0), "Gateway: admin cannot be 0x0");
admin = _nextAdmin;
}
/// @notice Allow the owner to update the token tracker.
/// @param _nextToken The address of the new tracking token.
function updateToken(address _nextToken) public onlyOwner {
require(_nextToken != address(0x0), "Gateway: token cannot be 0x0");
token = IERC20(_nextToken);
}
function updateDepositFee(uint16 _nextDepositFee) public onlyOwner {
depositFee = _nextDepositFee;
}
function updateWithdrawFee(uint16 _nextWithdrawFee) public onlyOwner {
withdrawFee = _nextWithdrawFee;
}
function updateSafeFundMoving(bool _safeFundMoving) public onlyOwner {
safeFundMoving = _safeFundMoving;
}
function updateSafeFundWallet(address _nextSafeFundWallet) public onlyOwner {
safeFundWallet = _nextSafeFundWallet;
}
function updateMinDepositAmount(uint256 _minDepositAmount) public onlyOwner {
minDepositAmount = _minDepositAmount;
}
function updateMinWithdrawAmount(uint256 _minWithdrawAmount) public onlyOwner {
minWithdrawAmount = _minWithdrawAmount;
}
/// @notice verifySignature checks the the provided signature matches the provided
/// parameters.
function verifySignature(bytes32 _signedMessageHash, bytes memory _sig) public view returns (bool) {
bytes32 ethSignedMessageHash = ECDSA.toEthSignedMessageHash(_signedMessageHash);
address signer = ECDSA.recover(ethSignedMessageHash, _sig);
return admin == signer;
}
/// @notice hashForSignature hashes the parameters so that they can be signed.
function hashForSignature(
string memory _symbol,
address _recipient,
uint256 _amount,
bytes32 _nHash
) public view returns (bytes32) {
bytes32 payloadHash = keccak256(abi.encode(_symbol, _recipient));
return keccak256(abi.encode(payloadHash, _amount, address(token), _nHash));
}
} | Allow the owner to update the token tracker. _nextToken The address of the new tracking token. | function updateToken(address _nextToken) public onlyOwner {
require(_nextToken != address(0x0), "Gateway: token cannot be 0x0");
token = IERC20(_nextToken);
}
| 1,641,531 |
Subsets and Splits