file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: 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/openzeppelin/ReentrancyGuard.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/EnumerableSet.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20Permit.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol";
import "./MultiDistributorAuthorization.sol";
import "./interfaces/IMultiDistributor.sol";
import "./interfaces/IDistributorCallback.sol";
// solhint-disable not-rely-on-time
/**
* @title MultiDistributor
* Based on Curve Finance's MultiRewards contract updated to be compatible with solc 0.7.0:
* https://github.com/curvefi/multi-rewards/blob/master/contracts/MultiRewards.sol commit #9947623
*/
contract MultiDistributor is IMultiDistributor, ReentrancyGuard, MultiDistributorAuthorization {
using Math for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.Bytes32Set;
/*
* Distribution accounting explanation:
*
* Distributors can start a distribution channel with a set amount of tokens to be distributed over a period,
* from this a `paymentRate` may be easily calculated.
*
* Two pieces of global information are stored for the amount of tokens paid out:
* `globalTokensPerStake` is a fixed point value of the number of tokens claimable from a single staking token
* staked from the start.
* `lastUpdateTime` represents the timestamp of the last time `globalTokensPerStake` was updated.
*
* `globalTokensPerStake` can be calculated by:
* 1. Calculating the amount of tokens distributed by multiplying `paymentRate` by the time since `lastUpdateTime`
* 2. Dividing this by the supply of staked tokens to get payment per staked token
* The existing `globalTokensPerStake` is then incremented by this amount.
*
* Updating these two values locks in the number of tokens that the current stakers can claim.
* This MUST be done whenever the total supply of staked tokens changes otherwise new stakers
* will gain a portion of rewards distributed before they staked.
*
* Each user tracks their own `userTokensPerStake` which determines how many tokens they can claim.
* This is done by comparing the global `globalTokensPerStake` with their own `userTokensPerStake`,
* the difference between these two values times their staked balance is their balance of rewards
* since `userTokensPerStake` was last updated.
*
* This calculation is only correct in the case where the user's staked balance does not change.
* Therefore before any stake/unstake/subscribe/unsubscribe they must sync their local rate to the global rate.
* Before `userTokensPerStake` is updated to match `globalTokensPerStake`, the unaccounted rewards
* which they have earned is stored in `unclaimedTokens` to be claimed later.
*
* If staking for the first time `userTokensPerStake` is set to `globalTokensPerStake` with zero `unclaimedTokens`
* to reflect that the user will only start accumulating tokens from that point on.
*
* After performing the above updates, claiming tokens is handled simply by just zeroing out the users
* `unclaimedTokens` and releasing that amount of tokens to them.
*/
mapping(bytes32 => Distribution) private _distributions;
mapping(IERC20 => mapping(address => UserStaking)) private _userStakings;
constructor(IVault vault) MultiDistributorAuthorization(vault) {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Returns the unique identifier used for a distribution
* @param stakingToken The staking token of the distribution
* @param distributionToken The token which is being distributed
* @param owner The owner of the distribution
*/
function getDistributionId(
IERC20 stakingToken,
IERC20 distributionToken,
address owner
) public pure override returns (bytes32) {
return keccak256(abi.encodePacked(stakingToken, distributionToken, owner));
}
/**
* @dev Returns the information of a distribution
* @param distributionId ID of the distribution being queried
*/
function getDistribution(bytes32 distributionId) external view override returns (Distribution memory) {
return _getDistribution(distributionId);
}
/**
* @dev Calculates the payment per token for a distribution
* @param distributionId ID of the distribution being queried
*/
function globalTokensPerStake(bytes32 distributionId) external view override returns (uint256) {
return _globalTokensPerStake(_getDistribution(distributionId));
}
/**
* @dev Returns the total supply of tokens subscribed to a distribution
* @param distributionId ID of the distribution being queried
*/
function totalSupply(bytes32 distributionId) external view override returns (uint256) {
return _getDistribution(distributionId).totalSupply;
}
/**
* @dev Returns if a user is subscribed to a distribution or not
* @param distributionId ID of the distribution being queried
* @param user The address of the user being queried
*/
function isSubscribed(bytes32 distributionId, address user) external view override returns (bool) {
IERC20 stakingToken = _getDistribution(distributionId).stakingToken;
return _userStakings[stakingToken][user].subscribedDistributions.contains(distributionId);
}
/**
* @dev Returns the information of a distribution for a user
* @param distributionId ID of the distribution being queried
* @param user Address of the user being queried
*/
function getUserDistribution(bytes32 distributionId, address user)
external
view
override
returns (UserDistribution memory)
{
IERC20 stakingToken = _getDistribution(distributionId).stakingToken;
return _userStakings[stakingToken][user].distributions[distributionId];
}
/**
* @dev Returns the total unclaimed payment for a user for a particular distribution
* @param distributionId ID of the distribution being queried
* @param user Address of the user being queried
*/
function getClaimableTokens(bytes32 distributionId, address user) external view override returns (uint256) {
Distribution storage distribution = _getDistribution(distributionId);
UserStaking storage userStaking = _userStakings[distribution.stakingToken][user];
UserDistribution storage userDistribution = userStaking.distributions[distributionId];
// If the user is not subscribed to the queried distribution, they don't have any unaccounted for tokens.
// Then we can just return the stored number of tokens which the user can claim.
if (!userStaking.subscribedDistributions.contains(distributionId)) {
return userDistribution.unclaimedTokens;
}
return _getUnclaimedTokens(userStaking, userDistribution, _globalTokensPerStake(distribution));
}
/**
* @dev Returns the staked balance of a user for a staking token
* @param stakingToken The staking token being queried
* @param user Address of the user being queried
*/
function balanceOf(IERC20 stakingToken, address user) external view override returns (uint256) {
return _userStakings[stakingToken][user].balance;
}
/**
* @dev Creates a new distribution
* @param stakingToken The staking token that will be eligible for this distribution
* @param distributionToken The token to be distributed to users
* @param duration The duration over which each distribution is spread
*/
function createDistribution(
IERC20 stakingToken,
IERC20 distributionToken,
uint256 duration
) external override returns (bytes32 distributionId) {
require(address(stakingToken) != address(0), "STAKING_TOKEN_ZERO_ADDRESS");
require(address(distributionToken) != address(0), "DISTRIBUTION_TOKEN_ZERO_ADDRESS");
distributionId = getDistributionId(stakingToken, distributionToken, msg.sender);
Distribution storage distribution = _getDistribution(distributionId);
require(distribution.duration == 0, "DISTRIBUTION_ALREADY_CREATED");
distribution.owner = msg.sender;
distribution.distributionToken = distributionToken;
distribution.stakingToken = stakingToken;
emit DistributionCreated(distributionId, stakingToken, distributionToken, msg.sender);
_setDistributionDuration(distributionId, distribution, duration);
}
/**
* @notice Sets the duration for a distribution
* @dev If the caller is not the owner of `distributionId`, it must be an authorized relayer for them.
* @param distributionId The ID of the distribution being modified
* @param duration Duration over which each distribution is spread
*/
function setDistributionDuration(bytes32 distributionId, uint256 duration) external override {
Distribution storage distribution = _getDistribution(distributionId);
// These values being guaranteed to be non-zero for created distributions means we can rely on zero as a
// sentinel value that marks non-existent distributions.
require(distribution.duration > 0, "DISTRIBUTION_DOES_NOT_EXIST");
require(distribution.periodFinish < block.timestamp, "DISTRIBUTION_STILL_ACTIVE");
// Check if msg.sender is authorised to fund this distribution
// This is required to allow distribution owners have contracts manage their distributions
_authenticateFor(distribution.owner);
_setDistributionDuration(distributionId, distribution, duration);
}
/**
* @notice Sets the duration for a distribution
* @param distributionId The ID of the distribution being modified
* @param distribution The distribution being modified
* @param duration Duration over which each distribution is spread
*/
function _setDistributionDuration(
bytes32 distributionId,
Distribution storage distribution,
uint256 duration
) private {
require(duration > 0, "DISTRIBUTION_DURATION_ZERO");
distribution.duration = duration;
emit DistributionDurationSet(distributionId, duration);
}
/**
* @notice Deposits tokens to be distributed to stakers subscribed to distribution channel `distributionId`
* @dev Starts a new distribution period for `duration` seconds from now.
* If the previous period is still active its undistributed tokens are rolled over into the new period.
*
* If the caller is not the owner of `distributionId`, it must be an authorized relayer for them.
* @param distributionId ID of the distribution to be funded
* @param amount The amount of tokens to deposit
*/
function fundDistribution(bytes32 distributionId, uint256 amount) external override nonReentrant {
Distribution storage distribution = _getDistribution(distributionId);
// These values being guaranteed to be non-zero for created distributions means we can rely on zero as a
// sentinel value that marks non-existent distributions.
require(distribution.duration > 0, "DISTRIBUTION_DOES_NOT_EXIST");
// Check if msg.sender is authorised to fund this distribution
// This is required to allow distribution owners have contracts manage their distributions
_authenticateFor(distribution.owner);
// Before receiving the tokens, we must sync the distribution up to the present as we are about to change
// its payment rate, which would otherwise affect the accounting of tokens distributed since the last update
_updateGlobalTokensPerStake(distribution);
// Get the tokens and deposit them in the Vault as this contract's internal balance, making claims to internal
// balance, joining pools, etc., use less gas.
IERC20 distributionToken = distribution.distributionToken;
distributionToken.safeTransferFrom(msg.sender, address(this), amount);
distributionToken.approve(address(getVault()), amount);
IVault.UserBalanceOp[] memory ops = new IVault.UserBalanceOp[](1);
ops[0] = IVault.UserBalanceOp({
asset: IAsset(address(distributionToken)),
amount: amount,
sender: address(this),
recipient: payable(address(this)),
kind: IVault.UserBalanceOpKind.DEPOSIT_INTERNAL
});
getVault().manageUserBalance(ops);
uint256 duration = distribution.duration;
uint256 periodFinish = distribution.periodFinish;
// The new payment rate will depend on whether or not there's already an ongoing period, in which case the two
// will be merged. In both scenarios we round down to avoid paying more tokens than were received.
if (block.timestamp >= periodFinish) {
// Current distribution period has ended so new period consists only of amount provided.
// By performing fixed point (FP) division of two non-FP values we get a FP result.
distribution.paymentRate = FixedPoint.divDown(amount, duration);
} else {
// Current distribution period is still in progress.
// Calculate number of tokens that haven't been distributed yet and apply to the new distribution period.
// This means that any previously pending tokens will be re-distributed over the extended duration, so if a
// constant rate is desired new funding should be applied close to the end date of a distribution.
// Checked arithmetic is not required due to the if
uint256 remainingTime = periodFinish - block.timestamp;
// Fixed point (FP) multiplication between a non-FP (time) and FP (rate) returns a non-FP result.
uint256 leftoverTokens = FixedPoint.mulDown(remainingTime, distribution.paymentRate);
// Fixed point (FP) division of two non-FP values we get a FP result.
distribution.paymentRate = FixedPoint.divDown(amount.add(leftoverTokens), duration);
}
distribution.lastUpdateTime = block.timestamp;
distribution.periodFinish = block.timestamp.add(duration);
emit DistributionFunded(distributionId, amount);
}
/**
* @dev Subscribes a user to a list of distributions
* @param distributionIds List of distributions to subscribe
*/
function subscribeDistributions(bytes32[] calldata distributionIds) external override {
bytes32 distributionId;
Distribution storage distribution;
for (uint256 i; i < distributionIds.length; i++) {
distributionId = distributionIds[i];
distribution = _getDistribution(distributionId);
IERC20 stakingToken = distribution.stakingToken;
require(stakingToken != IERC20(0), "DISTRIBUTION_DOES_NOT_EXIST");
UserStaking storage userStaking = _userStakings[stakingToken][msg.sender];
require(userStaking.subscribedDistributions.add(distributionId), "ALREADY_SUBSCRIBED_DISTRIBUTION");
uint256 amount = userStaking.balance;
if (amount > 0) {
// If subscribing to a distribution that uses a staking token for which the user has already staked,
// those tokens then immediately become part of the distribution's staked tokens
// (i.e. the user is staking for the new distribution).
// This means we need to update the distribution rate, as we are about to change its total
// staked tokens and decrease the global per token rate.
// The unclaimed tokens remain unchanged as the user was not subscribed to the distribution
// and therefore not eligible to receive any unaccounted-for tokens.
userStaking.distributions[distributionId].userTokensPerStake = _updateGlobalTokensPerStake(
distribution
);
distribution.totalSupply = distribution.totalSupply.add(amount);
emit Staked(distributionId, msg.sender, amount);
}
}
}
/**
* @dev Unsubscribes a user to a list of distributions
* @param distributionIds List of distributions to unsubscribe
*/
function unsubscribeDistributions(bytes32[] calldata distributionIds) external override {
bytes32 distributionId;
Distribution storage distribution;
for (uint256 i; i < distributionIds.length; i++) {
distributionId = distributionIds[i];
distribution = _getDistribution(distributionId);
IERC20 stakingToken = distribution.stakingToken;
require(stakingToken != IERC20(0), "DISTRIBUTION_DOES_NOT_EXIST");
UserStaking storage userStaking = _userStakings[stakingToken][msg.sender];
// If the user had tokens staked that applied to this distribution, we need to update their standing before
// unsubscribing, which is effectively an unstake.
uint256 amount = userStaking.balance;
if (amount > 0) {
_updateUserTokensPerStake(distribution, userStaking, userStaking.distributions[distributionId]);
// Safe to perform unchecked maths as `totalSupply` would be increased by `amount` when staking.
distribution.totalSupply -= amount;
emit Unstaked(distributionId, msg.sender, amount);
}
require(userStaking.subscribedDistributions.remove(distributionId), "DISTRIBUTION_NOT_SUBSCRIBED");
}
}
/**
* @notice Stakes tokens
* @dev If the caller is not `sender`, it must be an authorized relayer for them.
* @param stakingToken The token to be staked to be eligible for distributions
* @param amount Amount of tokens to be staked
*/
function stake(
IERC20 stakingToken,
uint256 amount,
address sender,
address recipient
) external override authenticateFor(sender) nonReentrant {
_stake(stakingToken, amount, sender, recipient, false);
}
/**
* @notice Stakes tokens using the user's token approval on the vault
* @dev If the caller is not `sender`, it must be an authorized relayer for them.
* @param stakingToken The token to be staked to be eligible for distributions
* @param amount Amount of tokens to be staked
* @param sender The address which provides tokens to stake
* @param recipient The address which receives the staked tokens
*/
function stakeUsingVault(
IERC20 stakingToken,
uint256 amount,
address sender,
address recipient
) external override authenticateFor(sender) nonReentrant {
_stake(stakingToken, amount, sender, recipient, true);
}
/**
* @notice Stakes tokens using a permit signature for approval
* @dev If the caller is not `sender`, it must be an authorized relayer for them.
* @param stakingToken The token to be staked to be eligible for distributions
* @param sender User staking tokens for
* @param amount Amount of tokens to be staked
* @param deadline The time at which this expires (unix time)
* @param v V of the signature
* @param r R of the signature
* @param s S of the signature
*/
function stakeWithPermit(
IERC20 stakingToken,
uint256 amount,
address sender,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override nonReentrant {
IERC20Permit(address(stakingToken)).permit(sender, address(this), amount, deadline, v, r, s);
_stake(stakingToken, amount, sender, sender, false);
}
/**
* @notice Unstake tokens
* @dev If the caller is not `sender`, it must be an authorized relayer for them.
* @param stakingToken The token to be unstaked
* @param amount Amount of tokens to be unstaked
* @param sender The address which is unstaking its tokens
* @param recipient The address which receives the unstaked tokens
*/
function unstake(
IERC20 stakingToken,
uint256 amount,
address sender,
address recipient
) external override authenticateFor(sender) nonReentrant {
_unstake(stakingToken, amount, sender, recipient);
}
/**
* @notice Claims earned distribution tokens for a list of distributions
* @dev If the caller is not `sender`, it must be an authorized relayer for them.
* @param distributionIds List of distributions to claim
* @param toInternalBalance Whether to send the claimed tokens to the recipient's internal balance
* @param sender The address which earned the tokens being claimed
* @param recipient The address which receives the claimed tokens
*/
function claim(
bytes32[] calldata distributionIds,
bool toInternalBalance,
address sender,
address recipient
) external override authenticateFor(sender) nonReentrant {
_claim(
distributionIds,
toInternalBalance ? IVault.UserBalanceOpKind.TRANSFER_INTERNAL : IVault.UserBalanceOpKind.WITHDRAW_INTERNAL,
sender,
recipient
);
}
/**
* @notice Claims earned tokens for a list of distributions to a callback contract
* @dev If the caller is not `sender`, it must be an authorized relayer for them.
* @param distributionIds List of distributions to claim
* @param sender The address which earned the tokens being claimed
* @param callbackContract The contract where tokens will be transferred
* @param callbackData The data that is used to call the callback contract's 'callback' method
*/
function claimWithCallback(
bytes32[] calldata distributionIds,
address sender,
IDistributorCallback callbackContract,
bytes calldata callbackData
) external override authenticateFor(sender) nonReentrant {
_claim(distributionIds, IVault.UserBalanceOpKind.TRANSFER_INTERNAL, sender, address(callbackContract));
callbackContract.distributorCallback(callbackData);
}
/**
* @dev Withdraws staking tokens and claims for a list of distributions
* @param stakingTokens The staking tokens to withdraw tokens from
* @param distributionIds The distributions to claim for
*/
function exit(IERC20[] memory stakingTokens, bytes32[] calldata distributionIds) external override nonReentrant {
for (uint256 i; i < stakingTokens.length; i++) {
IERC20 stakingToken = stakingTokens[i];
UserStaking storage userStaking = _userStakings[stakingToken][msg.sender];
_unstake(stakingToken, userStaking.balance, msg.sender, msg.sender);
}
_claim(distributionIds, IVault.UserBalanceOpKind.WITHDRAW_INTERNAL, msg.sender, msg.sender);
}
/**
* @dev Withdraws staking tokens and claims for a list of distributions to a callback contract
* @param stakingTokens The staking tokens to withdraw tokens from
* @param distributionIds The distributions to claim for
* @param callbackContract The contract where tokens will be transferred
* @param callbackData The data that is used to call the callback contract's 'callback' method
*/
function exitWithCallback(
IERC20[] calldata stakingTokens,
bytes32[] calldata distributionIds,
IDistributorCallback callbackContract,
bytes calldata callbackData
) external override nonReentrant {
for (uint256 i; i < stakingTokens.length; i++) {
IERC20 stakingToken = stakingTokens[i];
UserStaking storage userStaking = _userStakings[stakingToken][msg.sender];
_unstake(stakingToken, userStaking.balance, msg.sender, msg.sender);
}
_claim(distributionIds, IVault.UserBalanceOpKind.TRANSFER_INTERNAL, msg.sender, address(callbackContract));
callbackContract.distributorCallback(callbackData);
}
function _stake(
IERC20 stakingToken,
uint256 amount,
address sender,
address recipient,
bool useVaultApproval
) private {
require(amount > 0, "STAKE_AMOUNT_ZERO");
UserStaking storage userStaking = _userStakings[stakingToken][recipient];
// Before we increase the recipient's staked balance we need to update all of their subscriptions
_updateSubscribedDistributions(userStaking);
userStaking.balance = userStaking.balance.add(amount);
EnumerableSet.Bytes32Set storage distributions = userStaking.subscribedDistributions;
uint256 distributionsLength = distributions.length();
// We also need to update all distributions the recipient is subscribed to,
// adding the staked tokens to their totals.
bytes32 distributionId;
Distribution storage distribution;
for (uint256 i; i < distributionsLength; i++) {
distributionId = distributions.unchecked_at(i);
distribution = _getDistribution(distributionId);
distribution.totalSupply = distribution.totalSupply.add(amount);
emit Staked(distributionId, recipient, amount);
}
// We hold stakingTokens in an external balance as BPT needs to be external anyway
// in the case where a user is exiting the pool after unstaking.
if (useVaultApproval) {
IVault.UserBalanceOp[] memory ops = new IVault.UserBalanceOp[](1);
ops[0] = IVault.UserBalanceOp({
asset: IAsset(address(stakingToken)),
amount: amount,
sender: sender,
recipient: payable(address(this)),
kind: IVault.UserBalanceOpKind.TRANSFER_EXTERNAL
});
getVault().manageUserBalance(ops);
} else {
stakingToken.safeTransferFrom(sender, address(this), amount);
}
}
function _unstake(
IERC20 stakingToken,
uint256 amount,
address sender,
address recipient
) private {
require(amount > 0, "UNSTAKE_AMOUNT_ZERO");
UserStaking storage userStaking = _userStakings[stakingToken][sender];
// Before we reduce the sender's staked balance we need to update all of their subscriptions
_updateSubscribedDistributions(userStaking);
uint256 currentBalance = userStaking.balance;
require(currentBalance >= amount, "UNSTAKE_AMOUNT_UNAVAILABLE");
userStaking.balance = currentBalance - amount;
EnumerableSet.Bytes32Set storage distributions = userStaking.subscribedDistributions;
uint256 distributionsLength = distributions.length();
// We also need to update all distributions the sender was subscribed to,
// deducting the unstaked tokens from their totals.
bytes32 distributionId;
Distribution storage distribution;
for (uint256 i; i < distributionsLength; i++) {
distributionId = distributions.unchecked_at(i);
distribution = _getDistribution(distributionId);
// Safe to perform unchecked maths as `totalSupply` would be increased by `amount` when staking.
distribution.totalSupply -= amount;
emit Unstaked(distributionId, sender, amount);
}
stakingToken.safeTransfer(recipient, amount);
}
function _claim(
bytes32[] calldata distributionIds,
IVault.UserBalanceOpKind kind,
address sender,
address recipient
) private {
// It is expected that there will be multiple transfers of the same token
// so that the actual number of transfers needed is less than distributionIds.length
// We keep track of this number in numTokens to save gas later
uint256 numTokens;
IAsset[] memory tokens = new IAsset[](distributionIds.length);
uint256[] memory amounts = new uint256[](distributionIds.length);
bytes32 distributionId;
Distribution storage distribution;
for (uint256 i; i < distributionIds.length; i++) {
distributionId = distributionIds[i];
distribution = _getDistribution(distributionId);
UserStaking storage userStaking = _userStakings[distribution.stakingToken][sender];
UserDistribution storage userDistribution = userStaking.distributions[distributionId];
// Note that the user may have unsubscribed from the distribution but still be due tokens. We therefore only
// update the distribution if the user is subscribed to it (otherwise, it is already up to date).
if (userStaking.subscribedDistributions.contains(distributionId)) {
_updateUserTokensPerStake(distribution, userStaking, userDistribution);
}
uint256 unclaimedTokens = userDistribution.unclaimedTokens;
if (unclaimedTokens > 0) {
userDistribution.unclaimedTokens = 0;
IAsset distributionToken = IAsset(address(distribution.distributionToken));
// Iterate through all the tokens we've seen so far.
for (uint256 j; j < tokens.length; j++) {
// Check if we're already sending some of this token
// If so we just want to add to the existing transfer
if (tokens[j] == distributionToken) {
amounts[j] += unclaimedTokens;
break;
} else if (tokens[j] == IAsset(0)) {
// If it's the first time we've seen this token
// record both its address and amount to transfer
tokens[j] = distributionToken;
amounts[j] = unclaimedTokens;
numTokens += 1;
break;
}
}
emit DistributionClaimed(distributionId, sender, unclaimedTokens);
}
}
IVault.UserBalanceOp[] memory ops = new IVault.UserBalanceOp[](numTokens);
for (uint256 i; i < numTokens; i++) {
ops[i] = IVault.UserBalanceOp({
asset: tokens[i],
amount: amounts[i],
sender: address(this),
recipient: payable(recipient),
kind: kind
});
}
getVault().manageUserBalance(ops);
}
/**
* @dev Updates the payment rate for all the distributions that a user has signed up for a staking token
*/
function _updateSubscribedDistributions(UserStaking storage userStaking) private {
EnumerableSet.Bytes32Set storage distributions = userStaking.subscribedDistributions;
uint256 distributionsLength = distributions.length();
for (uint256 i; i < distributionsLength; i++) {
bytes32 distributionId = distributions.unchecked_at(i);
_updateUserTokensPerStake(
_getDistribution(distributionId),
userStaking,
userStaking.distributions[distributionId]
);
}
}
function _updateUserTokensPerStake(
Distribution storage distribution,
UserStaking storage userStaking,
UserDistribution storage userDistribution
) private {
uint256 updatedGlobalTokensPerStake = _updateGlobalTokensPerStake(distribution);
userDistribution.unclaimedTokens = _getUnclaimedTokens(
userStaking,
userDistribution,
updatedGlobalTokensPerStake
);
userDistribution.userTokensPerStake = updatedGlobalTokensPerStake;
}
/**
* @notice Updates the amount of distribution tokens paid per token staked for a distribution
* @dev This is expected to be called whenever a user's applicable staked balance changes,
* either through adding/removing tokens or subscribing/unsubscribing from the distribution.
* @param distribution The distribution being updated
* @return updatedGlobalTokensPerStake The updated number of distribution tokens paid per staked token
*/
function _updateGlobalTokensPerStake(Distribution storage distribution)
private
returns (uint256 updatedGlobalTokensPerStake)
{
updatedGlobalTokensPerStake = _globalTokensPerStake(distribution);
distribution.globalTokensPerStake = updatedGlobalTokensPerStake;
distribution.lastUpdateTime = _lastTimePaymentApplicable(distribution);
}
function _globalTokensPerStake(Distribution storage distribution) private view returns (uint256) {
uint256 supply = distribution.totalSupply;
if (supply == 0) {
return distribution.globalTokensPerStake;
}
// Underflow is impossible here because _lastTimePaymentApplicable(...) is always greater than last update time
uint256 unpaidDuration = _lastTimePaymentApplicable(distribution) - distribution.lastUpdateTime;
// Note `paymentRate` and `distribution.globalTokensPerStake` are both fixed point values
uint256 unpaidTokensPerStake = unpaidDuration.mul(distribution.paymentRate).divDown(supply);
return distribution.globalTokensPerStake.add(unpaidTokensPerStake);
}
/**
* @dev Returns the timestamp up to which a distribution has been distributing tokens
* @param distribution The distribution being queried
*/
function _lastTimePaymentApplicable(Distribution storage distribution) private view returns (uint256) {
return Math.min(block.timestamp, distribution.periodFinish);
}
/**
* @notice Returns the total unclaimed tokens for a user for a particular distribution
* @dev Only returns correct results when the user is subscribed to the distribution
* @param userStaking Storage pointer to user's staked position information
* @param userDistribution Storage pointer to user specific information on distribution
* @param updatedGlobalTokensPerStake The updated number of distribution tokens paid per staked token
*/
function _getUnclaimedTokens(
UserStaking storage userStaking,
UserDistribution storage userDistribution,
uint256 updatedGlobalTokensPerStake
) private view returns (uint256) {
return
_unaccountedUnclaimedTokens(userStaking, userDistribution, updatedGlobalTokensPerStake).add(
userDistribution.unclaimedTokens
);
}
/**
* @notice Returns the tokens earned for a particular distribution between
* the last time the user updated their position and now
* @dev Only returns correct results when the user is subscribed to the distribution
* @param userStaking Storage pointer to user's staked position information
* @param userDistribution Storage pointer to user specific information on distribution
* @param updatedGlobalTokensPerStake The updated number of distribution tokens paid per staked token
*/
function _unaccountedUnclaimedTokens(
UserStaking storage userStaking,
UserDistribution storage userDistribution,
uint256 updatedGlobalTokensPerStake
) private view returns (uint256) {
// `userDistribution.userTokensPerStake` cannot exceed `updatedGlobalTokensPerStake`
// Both `updatedGlobalTokensPerStake` and `userDistribution.userTokensPerStake` are fixed point values
uint256 unaccountedTokensPerStake = updatedGlobalTokensPerStake - userDistribution.userTokensPerStake;
// Fixed point (FP) multiplication between a non-FP (balance) and FP (tokensPerStake) returns a non-FP result.
return FixedPoint.mulDown(userStaking.balance, unaccountedTokensPerStake);
}
function _getDistribution(
IERC20 stakingToken,
IERC20 distributionToken,
address owner
) private view returns (Distribution storage) {
return _getDistribution(getDistributionId(stakingToken, distributionToken, owner));
}
function _getDistribution(bytes32 id) private view returns (Distribution storage) {
return _distributions[id];
}
}
| Withdraws staking tokens and claims for a list of distributions to a callback contract stakingTokens The staking tokens to withdraw tokens from distributionIds The distributions to claim for callbackContract The contract where tokens will be transferred callbackData The data that is used to call the callback contract's 'callback' method/ | function exitWithCallback(
IERC20[] calldata stakingTokens,
bytes32[] calldata distributionIds,
IDistributorCallback callbackContract,
bytes calldata callbackData
) external override nonReentrant {
for (uint256 i; i < stakingTokens.length; i++) {
IERC20 stakingToken = stakingTokens[i];
UserStaking storage userStaking = _userStakings[stakingToken][msg.sender];
_unstake(stakingToken, userStaking.balance, msg.sender, msg.sender);
}
_claim(distributionIds, IVault.UserBalanceOpKind.TRANSFER_INTERNAL, msg.sender, address(callbackContract));
callbackContract.distributorCallback(callbackData);
}
| 14,039,103 |
// SPDX-License-Identifier: MIT
/**
* @title A LIT Invitation To Kindness
* @author Transient Labs, Copyright (C) 2022
* @notice ERC 1155 contract, single owner, merkle claim
* @dev includes the public parameter `name` so it works with OS
*/
/*
( ( ( )
( )\ ) )\ ) * ) )\ ) ) ) * ) ( /( (
)\ (()/( (()/( ` ) /( (()/( ) ( ( /( ) ( /( ( ` ) /( )\()) ( )\ ) (
((((_)( /(_)) /(_)) ( )(_)) /(_)) ( /(( )\ )\()) ( /( )\()) )\ ( ( ( )(_)) ( |((_)\ )\ ( (()/( ( ))\ ( (
)\ _ )\ (_)) (_)) (_(_()) (_)) )\ ) (_))\ ((_) (_))/ )(_)) (_))/ ((_) )\ )\ ) (_(_()) )\ |_ ((_) ((_) )\ ) ((_)) )\ ) /((_) )\ )\
(_)_\(_) | | |_ _| |_ _| |_ _| _(_/( _)((_) (_) | |_ ((_)_ | |_ (_) ((_) _(_/( |_ _| ((_) | |/ / (_) _(_/( _| | _(_/( (_)) ((_) ((_)
/ _ \ | |__ | | | | | | | ' \)) \ V / | | | _| / _` | | _| | | / _ \ | ' \)) | | / _ \ ' < | | | ' \)) / _` | | ' \)) / -_) (_-< (_-<
/_/ \_\ |____| |___| |_| |___| |_||_| \_/ |_| \__| \__,_| \__| |_| \___/ |_||_| |_| \___/ _|\_\ |_| |_||_| \__,_| |_||_| \___| /__/ /__/
___ __ ___ ______ _ __ __ __
/ _ \___ _ _____ _______ ___/ / / _ )__ __ /_ __/______ ____ ___ (_)__ ___ / /_ / / ___ _/ / ___
/ ___/ _ \ |/|/ / -_) __/ -_) _ / / _ / // / / / / __/ _ `/ _ \(_-</ / -_) _ \/ __/ / /__/ _ `/ _ \(_-<
/_/ \___/__,__/\__/_/ \__/\_,_/ /____/\_, / /_/ /_/ \_,_/_//_/___/_/\__/_//_/\__/ /____/\_,_/_.__/___/
/___/
*/
pragma solidity ^0.8.0;
import "ERC1155.sol";
import "Ownable.sol";
import "Strings.sol";
import "MerkleProof.sol";
import "EIP2981.sol";
contract InvitationToKindness is ERC1155, EIP2981, Ownable {
using Strings for uint256;
bytes32 private litRiderMerkleRoot;
bytes32 private rareRiderMerkleRoot;
uint256 constant LIT_RIDER = 0;
uint256 constant LIT_PAMP = 1;
uint256 constant LIT_CDM = 2;
mapping(address => bool) private hasMinted;
bool public claimOpen;
uint256[] private availableRareRiderIds;
uint256[] private rareRiderSupply;
string public name = "A LIT Invitation to Kindness";
constructor(bytes32 _litRiderMerkleRoot, bytes32 _rareRiderMerkleRoot, address _royaltyRecipient, uint256 _royaltyAmount) EIP2981(_royaltyRecipient, _royaltyAmount) ERC1155("") Ownable() {
availableRareRiderIds = [LIT_PAMP, LIT_CDM];
rareRiderSupply = [334, 30];
litRiderMerkleRoot = _litRiderMerkleRoot;
rareRiderMerkleRoot = _rareRiderMerkleRoot;
}
/**
* @notice overrides supportsInterface function
* @param _interfaceId is supplied from anyone/contract calling this function, as defined in ERC 165
* @return a boolean saying if this contract supports the interface or not
*/
function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC1155, EIP2981) returns (bool) {
return super.supportsInterface(_interfaceId);
}
/**
* @notice function to update allowlist merkle root if needed
* @dev requires owner
* @param _litRiderRoot is the new lit rider merkle root
* @param _rareRiderRoot is the new rare rider merkle root*/
function updateAllowlistRoots(bytes32 _litRiderRoot, bytes32 _rareRiderRoot) public onlyOwner {
litRiderMerkleRoot = _litRiderRoot;
rareRiderMerkleRoot = _rareRiderRoot;
}
/**
* @notice sets the baseURI for the tokens
* @dev requires owner
* @param _uri is the base URI set for each token
*/
function setBaseURI(string memory _uri) public onlyOwner {
_setURI(_uri);
}
/**
* @notice function to change the royalty recipient
* @dev requires owner
* @dev this is useful if an account gets compromised or anything like that
* @param _newRecipient is the new royalty recipient
*/
function changeRoyaltyRecipient(address _newRecipient) public onlyOwner {
require(_newRecipient != address(0), "Error: new recipient is the zero address");
royaltyAddr = _newRecipient;
}
/**
* @notice function to change the royalty percentage
* @dev requires owner
* @dev this is useful if the amount was set improperly at contract creation. This can in fact happen... humans are prone to mistakes :)
* @param _newPerc is the new royalty percentage, in basis points (out of 10,000)
*/
function changeRoyaltyPercentage(uint256 _newPerc) public onlyOwner {
require(_newPerc <= 10000, "Error: new percentage is greater than 10,0000");
royaltyPerc = _newPerc;
}
/**
* @notice getter function for if an address has minted
* @param _address is the address to check
* @return boolean
*/
function getHasMinted(address _address) public returns (bool){
return hasMinted[_address];
}
/**
* @notice function to return uri for a specific token type
* @param _tokenId is the uint256 representation of a token ID
* @return string representing the uri for the token id
*/
function uri(uint256 _tokenId) public view virtual override returns (string memory) {
require(_tokenId == LIT_RIDER || _tokenId == LIT_CDM || _tokenId == LIT_PAMP, "Error: non-existent token id");
return string(abi.encodePacked(ERC1155.uri(_tokenId), _tokenId.toString()));
}
/**
* @notice function to set the claim status
* @dev requires owner
* @param _status is the status to set the claim to
*/
function setClaimStatus(bool _status) public onlyOwner {
claimOpen = _status;
}
/**
* @notice function for minting riders
* @dev requires owner
* @param _litRiderMerkleProof is the proof for lit riders
* @param _rareRiderMerkleProof is the proof for rare riders
*/
function mint(bytes32[] calldata _litRiderMerkleProof, bytes32[] calldata _rareRiderMerkleProof) public {
require(claimOpen, "Error: claim not open");
require(!hasMinted[msg.sender], "Error: already claimed");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
bool isLitRider = MerkleProof.verify(_litRiderMerkleProof, litRiderMerkleRoot, leaf);
require(isLitRider, "Error: not on the allowlist for the claim");
bool isRareRider = MerkleProof.verify(_rareRiderMerkleProof, rareRiderMerkleRoot, leaf);
if (isRareRider && availableRareRiderIds.length != 0) {
_mint(msg.sender, LIT_RIDER, 1, "");
uint256 rider = _getRandomNum(availableRareRiderIds.length);
_mint(msg.sender, availableRareRiderIds[rider], 1, "");
rareRiderSupply[rider]--;
if (rareRiderSupply[rider] == 0) {
availableRareRiderIds[rider] = availableRareRiderIds[availableRareRiderIds.length - 1];
availableRareRiderIds.pop();
rareRiderSupply[rider] = rareRiderSupply[rareRiderSupply.length - 1];
rareRiderSupply.pop();
}
}
else {
_mint(msg.sender, LIT_RIDER, 2, "");
}
hasMinted[msg.sender] = true;
}
/**
* @notice function for minting specific rider to address
* @dev only owner
* @dev only used as backup
* @param _tokenId is the token id to mint
* @param _address is the address to mint to
*/
function adminMint(address _address, uint256 _tokenId) public onlyOwner {
require(_tokenId == LIT_RIDER || _tokenId == LIT_CDM || _tokenId == LIT_PAMP, "Error: invalid token id");
_mint(_address, _tokenId, 1, "");
}
/**
* @dev Generates a pseudo-random number
* @param _upper is a uint256 meant to be the upper bound of the random number generation
*/
function _getRandomNum(uint256 _upper) private view returns (uint256) {
uint256 random = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), block.coinbase, block.difficulty, msg.sender)));
return random % _upper;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "IERC1155.sol";
import "IERC1155Receiver.sol";
import "IERC1155MetadataURI.sol";
import "Address.sol";
import "Context.sol";
import "ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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/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 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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
/**
* @title EIP 2981 base contract
* @author Transient Labs, Copyright (C) 2021
* @notice contract implementation of EIP 2981
*/
/*
####### #
# ##### ## # # #### # ###### # # ##### # ## ##### ####
# # # # # ## # # # # ## # # # # # # # #
# # # # # # # # #### # ##### # # # # # # # ##### ####
# ##### ###### # # # # # # # # # # # ###### # # #
# # # # # # ## # # # # # ## # # # # # # # #
# # # # # # # #### # ###### # # # ####### # # ##### ####
0101010011100101100000110111011100101101000110010011011101110100 01001100110000011000101110011
*/
pragma solidity ^0.8.0;
import "ERC165.sol";
import "IEIP2981.sol";
contract EIP2981 is IEIP2981, ERC165 {
address internal royaltyAddr;
uint256 internal royaltyPerc; // percentage in basis (out of 10,000)
/**
* @notice constructor
* @dev need inheriting contracts to accept the parameters in their constructor
* @param addr is the royalty payout address
* @param perc is the royalty percentage, multiplied by 10000. Ex: 7.5% => 750
*/
constructor(address addr, uint256 perc) {
royaltyAddr = addr;
royaltyPerc = perc;
}
/**
* @notice override ERC 165 implementation of this function
* @dev if using this contract with another contract that suppports ERC 265, will have to override in the inheriting contract
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) {
return interfaceId == type(IEIP2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice EIP 2981 royalty support
* @dev royalty payout made to the owner of the contract and the owner can't be the 0 address
* @dev royalty amount determined when contract is deployed, and then divided by 10000 in this function
* @dev royalty amount not dependent on _tokenId
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
require(royaltyAddr != address(0));
return (royaltyAddr, royaltyPerc * _salePrice / 10000);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
///
/// @dev Interface for the NFT Royalty Standard
///
interface IEIP2981 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver,uint256 royaltyAmount);
} | overrides supportsInterface function _interfaceId is supplied from anyone/contract calling this function, as defined in ERC 165 return a boolean saying if this contract supports the interface or not/ | function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC1155, EIP2981) returns (bool) {
return super.supportsInterface(_interfaceId);
}
| 1,204,633 |
pragma solidity ^0.5.10;
/** @title OnDemandSPV */
/** @author Summa (https://summa.one) */
import {Relay} from "./Relay.sol";
import {ISPVRequestManager, ISPVConsumer} from "./Interfaces.sol";
import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol";
import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol";
import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol";
import {SafeMath} from "@summa-tx/bitcoin-spv-sol/contracts/SafeMath.sol";
contract OnDemandSPV is ISPVRequestManager, Relay {
using SafeMath for uint256;
using BytesLib for bytes;
using BTCUtils for bytes;
struct ProofRequest {
bytes32 spends;
bytes32 pays;
uint256 notBefore;
address consumer;
uint64 paysValue;
uint8 numConfs;
address owner;
RequestStates state;
}
enum RequestStates { NONE, ACTIVE, CLOSED }
mapping (bytes32 => bool) internal validatedTxns; // authenticated tx store
mapping (uint256 => ProofRequest) internal requests; // request info
uint256 public constant BASE_COST = 24 * 60 * 60; // 1 day
uint256 public nextID;
bytes32 public latestValidatedTx;
uint256 public remoteGasAllowance = 500000; // maximum gas for callback call
/// @notice Gives a starting point for the relay
/// @dev We don't check this AT ALL really. Don't use relays with bad genesis
/// @param _genesisHeader The starting header
/// @param _height The starting height
/// @param _periodStart The hash of the first header in the genesis epoch
constructor(
bytes memory _genesisHeader,
uint256 _height,
bytes32 _periodStart,
uint256 _firstID
) Relay(
_genesisHeader,
_height,
_periodStart
) public {
nextID = _firstID;
}
/// @notice Cancel a bitcoin event request.
/// @dev Prevents the relay from forwarding tx infromation
/// @param _requestID The ID of the request to be cancelled
/// @return True if succesful, error otherwise
function cancelRequest(uint256 _requestID) external returns (bool) {
ProofRequest storage _req = requests[_requestID];
require(_req.state == RequestStates.ACTIVE, "Request not active");
require(msg.sender == _req.consumer || msg.sender == _req.owner, "Can only be cancelled by owner or consumer");
_req.state = RequestStates.CLOSED;
emit RequestClosed(_requestID);
return true;
}
function getLatestValidatedTx() external view returns (bytes32) {
return latestValidatedTx;
}
/// @notice Retrieve info about a request
/// @dev Requests ids are numerical
/// @param _requestID The numerical ID of the request
/// @return A tuple representation of the request struct
function getRequest(
uint256 _requestID
) external view returns (
bytes32 spends,
bytes32 pays,
uint64 paysValue,
uint8 state,
address consumer,
address owner,
uint8 numConfs,
uint256 notBefore
) {
ProofRequest storage _req = requests[_requestID];
spends = _req.spends;
pays = _req.pays;
paysValue = _req.paysValue;
state = uint8(_req.state);
consumer = _req.consumer;
owner = _req.owner;
numConfs = _req.numConfs;
notBefore = _req.notBefore;
}
/// @notice Subscribe to a feed of Bitcoin txns matching a request
/// @dev The request can be a spent utxo and/or a created utxo
/// @param _spends An outpoint that must be spent in acceptable txns (optional)
/// @param _pays An output script that must be paid in acceptable txns (optional)
/// @param _paysValue A minimum value that must be paid to the output script (optional)
/// @param _consumer The address of a ISPVConsumer exposing spv
/// @param _numConfs The minimum number of Bitcoin confirmations to accept
/// @param _notBefore A timestamp before which proofs are not accepted
/// @return A unique request ID.
function request(
bytes calldata _spends,
bytes calldata _pays,
uint64 _paysValue,
address _consumer,
uint8 _numConfs,
uint256 _notBefore
) external returns (uint256) {
return _request(_spends, _pays, _paysValue, _consumer, _numConfs, _notBefore);
}
/// @notice Subscribe to a feed of Bitcoin txns matching a request
/// @dev The request can be a spent utxo and/or a created utxo
/// @param _spends An outpoint that must be spent in acceptable txns (optional)
/// @param _pays An output script that must be paid in acceptable txns (optional)
/// @param _paysValue A minimum value that must be paid to the output script (optional)
/// @param _consumer The address of a ISPVConsumer exposing spv
/// @param _numConfs The minimum number of Bitcoin confirmations to accept
/// @param _notBefore A timestamp before which proofs are not accepted
/// @return A unique request ID
function _request(
bytes memory _spends,
bytes memory _pays,
uint64 _paysValue,
address _consumer,
uint8 _numConfs,
uint256 _notBefore
) internal returns (uint256) {
uint256 _requestID = nextID;
nextID = nextID + 1;
bytes memory pays = _pays;
require(_spends.length == 36 || _spends.length == 0, "Not a valid UTXO");
/* NB: This will fail if the output is not p2pkh, p2sh, p2wpkh, or p2wsh*/
uint256 _paysLen = pays.length;
// if it's not length-prefixed, length-prefix it
if (_paysLen > 0 && uint8(pays[0]) != _paysLen - 1) {
pays = abi.encodePacked(uint8(_paysLen), pays);
_paysLen += 1; // update the length because we made it longer
}
bytes memory _p = abi.encodePacked(bytes8(0), pays);
require(
_paysLen == 0 || // no request OR
_p.extractHash().length > 0 || // standard output OR
_p.extractOpReturnData().length > 0, // OP_RETURN output
"Not a standard output type");
require(_spends.length > 0 || _paysLen > 0, "No request specified");
ProofRequest storage _req = requests[_requestID];
_req.owner = msg.sender;
if (_spends.length > 0) {
_req.spends = keccak256(_spends);
}
if (_paysLen > 0) {
_req.pays = keccak256(pays);
}
if (_paysValue > 0) {
_req.paysValue = _paysValue;
}
if (_numConfs > 0 && _numConfs < 241) { //241 is arbitray. 40 hours
_req.numConfs = _numConfs;
}
if (_notBefore > 0) {
_req.notBefore = _notBefore;
}
_req.consumer = _consumer;
_req.state = RequestStates.ACTIVE;
emit NewProofRequest(msg.sender, _requestID, _paysValue, _spends, pays);
return _requestID;
}
/// @notice Provide a proof of a tx that satisfies some request
/// @dev The caller must specify which inputs, which outputs, and which request
/// @param _header The header containing the merkleroot committing to the tx
/// @param _proof The merkle proof intermediate nodes
/// @param _version The tx version, always the first 4 bytes of the tx
/// @param _locktime The tx locktime, always the last 4 bytes of the tx
/// @param _index The index of the tx in the merkle tree's leaves
/// @param _reqIndices The input and output index to check against the request, packed
/// @param _vin The tx input vector
/// @param _vout The tx output vector
/// @param _requestID The id of the request that has been triggered
/// @return True if succesful, error otherwise
function provideProof(
bytes calldata _header,
bytes calldata _proof,
bytes4 _version,
bytes4 _locktime,
uint256 _index,
uint16 _reqIndices,
bytes calldata _vin,
bytes calldata _vout,
uint256 _requestID
) external returns (bool) {
bytes32 _txid = abi.encodePacked(_version, _vin, _vout, _locktime).hash256();
/*
NB: this shortcuts validation of any txn we've seen before
repeats can omit header, proof, and index
*/
if (!validatedTxns[_txid]) {
_checkInclusion(
_header,
_proof,
_index,
_txid,
_requestID);
validatedTxns[_txid] = true;
latestValidatedTx = _txid;
}
_checkRequests(_reqIndices, _vin, _vout, _requestID);
_callCallback(_txid, _reqIndices, _vin, _vout, _requestID);
return true;
}
/// @notice Notify a consumer that one of its requests has been triggered
/// @dev We include information about the tx that triggered it, so the consumer can take actions
/// @param _vin The tx input vector
/// @param _vout The tx output vector
/// @param _txid The transaction ID
/// @param _requestID The id of the request that has been triggered
function _callCallback(
bytes32 _txid,
uint16 _reqIndices,
bytes memory _vin,
bytes memory _vout,
uint256 _requestID
) internal returns (bool) {
ProofRequest storage _req = requests[_requestID];
ISPVConsumer c = ISPVConsumer(_req.consumer);
uint8 _inputIndex = uint8(_reqIndices >> 8);
uint8 _outputIndex = uint8(_reqIndices & 0xff);
/*
NB:
We want to make the remote call, but we don't care about results
We use the low-level call so that we can ignore reverts and set gas
*/
address(c).call.gas(remoteGasAllowance)(
abi.encodePacked(
c.spv.selector,
abi.encode(_txid, _vin, _vout, _requestID, _inputIndex, _outputIndex)
)
);
emit RequestFilled(_txid, _requestID);
return true;
}
/// @notice Verifies inclusion of a tx in a header, and that header in the Relay chain
/// @dev Specifically we check that both the best tip and the heaviest common header confirm it
/// @param _header The header containing the merkleroot committing to the tx
/// @param _proof The merkle proof intermediate nodes
/// @param _index The index of the tx in the merkle tree's leaves
/// @param _txid The txid that is the proof leaf
/// @param _requestID The ID of the request to check against
function _checkInclusion(
bytes memory _header,
bytes memory _proof,
uint256 _index,
bytes32 _txid,
uint256 _requestID
) internal view returns (bool) {
require(
ValidateSPV.prove(
_txid,
_header.extractMerkleRootLE().toBytes32(),
_proof,
_index),
"Bad inclusion proof");
bytes32 _headerHash = _header.hash256();
bytes32 _GCD = getLastReorgCommonAncestor();
require(
_isAncestor(
_headerHash,
_GCD,
240),
"GCD does not confirm header");
uint8 _numConfs = requests[_requestID].numConfs;
require(
_getConfs(_headerHash) >= _numConfs,
"Insufficient confirmations");
return true;
}
/// @notice Finds the number of headers on top of the argument
/// @dev Bounded to 6400 gas (8 looksups) max
/// @param _headerHash The LE double-sha2 header hash
/// @return The number of headers on top
function _getConfs(bytes32 _headerHash) internal view returns (uint8) {
return uint8(_findHeight(bestKnownDigest) - _findHeight(_headerHash));
}
/// @notice Verifies that a tx meets the requester's request
/// @dev Requests can be specify an input, and output, and/or an output value
/// @param _reqIndices The input and output index to check against the request, packed
/// @param _vin The tx input vector
/// @param _vout The tx output vector
/// @param _requestID The id of the request to check
function _checkRequests (
uint16 _reqIndices,
bytes memory _vin,
bytes memory _vout,
uint256 _requestID
) internal view returns (bool) {
require(_vin.validateVin(), "Vin is malformatted");
require(_vout.validateVout(), "Vout is malformatted");
uint8 _inputIndex = uint8(_reqIndices >> 8);
uint8 _outputIndex = uint8(_reqIndices & 0xff);
ProofRequest storage _req = requests[_requestID];
require(_req.notBefore <= block.timestamp, "Request is submitted too early");
require(_req.state == RequestStates.ACTIVE, "Request is not active");
bytes32 _pays = _req.pays;
bool _hasPays = _pays != bytes32(0);
if (_hasPays) {
bytes memory _out = _vout.extractOutputAtIndex(uint8(_outputIndex));
bytes memory _scriptPubkey = _out.slice(8, _out.length - 8);
require(
keccak256(_scriptPubkey) == _pays,
"Does not match pays request");
uint64 _paysValue = _req.paysValue;
require(
_paysValue == 0 ||
_out.extractValue() >= _paysValue,
"Does not match value request");
}
bytes32 _spends = _req.spends;
bool _hasSpends = _spends != bytes32(0);
if (_hasSpends) {
bytes memory _in = _vin.extractInputAtIndex(uint8(_inputIndex));
require(
!_hasSpends ||
keccak256(_in.extractOutpoint()) == _spends,
"Does not match spends request");
}
return true;
}
}
pragma solidity ^0.5.10;
/// @title ISPVConsumer
/// @author Summa (https://summa.one)
/// @notice This interface consumes validated transaction information.
/// It is the primary way that user contracts accept
/// @dev Implement this interface to process transactions provided by
/// the Relay system.
interface ISPVConsumer {
/// @notice A consumer for Bitcoin transaction information.
/// @dev Users must implement this function. It handles Bitcoin
/// events that have been validated by the Relay contract.
/// It is VERY IMPORTANT that this function validates the
/// msg.sender. The callee must check the origin of the data
/// or risk accepting spurious information.
/// @param _txid The LE(!) txid of the bitcoin transaction that
/// triggered the notification.
/// @param _vin The length-prefixed input vector of the bitcoin tx
/// that triggered the notification.
/// @param _vout The length-prefixed output vector of the bitcoin tx
/// that triggered the notification.
/// @param _requestID The ID of the event request that this notification
/// satisfies. The ID is returned by
/// OnDemandSPV.request and should be locally stored by
/// any contract that makes more than one request.
/// @param _inputIndex The index of the input in the _vin that triggered
/// the notification.
/// @param _outputIndex The index of the output in the _vout that triggered
/// the notification. Useful for subscribing to transactions
/// that spend the newly-created UTXO.
function spv(
bytes32 _txid,
bytes calldata _vin,
bytes calldata _vout,
uint256 _requestID,
uint8 _inputIndex,
uint8 _outputIndex) external;
}
/// @title ISPVRequestManager
/// @author Summa (https://summa.one)
/// @notice The interface for using the OnDemandSPV system. This interface
/// allows you to subscribe to Bitcoin events.
/// @dev Manage subscriptions to Bitcoin events. Register callbacks to
/// be called whenever specific Bitcoin transactions are made.
interface ISPVRequestManager {
event NewProofRequest (
address indexed _requester,
uint256 indexed _requestID,
uint64 _paysValue,
bytes _spends,
bytes _pays
);
event RequestClosed(uint256 indexed _requestID);
event RequestFilled(bytes32 indexed _txid, uint256 indexed _requestID);
/// @notice Subscribe to a feed of Bitcoin transactions matching a request
/// @dev The request can be a spent utxo and/or a created utxo.
///
/// The contract allows users to register a "consumer" contract
/// that implements ISPVConsumer to handle Bitcoin events.
///
/// Bitcoin transactions are composed of a vector of inputs,
/// and a vector of outputs. The `_spends` parameter allows consumers
/// to watch a specific UTXO, and receive an event when it is spent.
///
/// The `_pays` and `_paysValue` param allow the user to watch specific
/// Bitcoin output scripts. An output script is typically encoded
/// as an address, but an address is not an in-protocol construction.
/// In other words, consumers will receive an event whenever a specific
/// address receives funds, or when a specific OP_RETURN is created.
///
/// Either `_spends` or `_pays` MUST be set. Both MAY be set.
/// If both are set, only notifications meeting both criteria
/// will be triggered.
///
/// @param _spends An outpoint that must be spent in acceptable transactions.
/// The outpoint must be exactly 36 bytes, and composed of a
/// LE txid (32 bytes), and an 4-byte LE-encoded index integer.
/// In other words, the precise serialization format used in a
/// serialized Bitcoin TxIn.
///
/// Note that while we might expect a `_spends` event to fire at most
/// one time, that expectation becomes invalid in long Bitcoin reorgs
/// if there is a double-spend or a disconfirmation followed by
/// reconfirmation.
///
/// @param _pays An output script to watch for events. A filter with `_pays` set will
/// validate any number of events that create new UTXOs with a specific
/// output script.
///
/// This is useful for watching an address and responding to incoming
/// payments.
///
/// @param _paysValue A minimum value in satoshi that must be paid to the output script.
/// If this is set no any non-0 number, the Relay will only forward
/// `_pays` notifications to the consumer if the value of the new UTXO is
/// at least `_paysValue`.
///
/// @param _consumer The address of a contract that implements the `ISPVConsumer` interface.
/// Whenever events are available, the Relay will validate inclusion
/// and confirmation, then call the `spv` function on the consumer.
///
/// @param _numConfs The number of headers that must confirm the block
/// containing the transaction. Used as a security parameter.
/// More confirmations means less likely to revert due to a
/// chain reorganization. Note that 1 confirmation is required,
/// so the general "6 confirmation" rule would be expressed
/// as `5` when calling this function
///
/// @param _notBefore An Ethereum timestamp before which proofs will not be accepted.
/// Used to control app flow for specific users.
///
/// @return A unique request ID.
function request(
bytes calldata _spends,
bytes calldata _pays,
uint64 _paysValue,
address _consumer,
uint8 _numConfs,
uint256 _notBefore
) external returns (uint256);
/// @notice Cancel an active bitcoin event request.
/// @dev Prevents the relay from forwarding tx information
/// @param _requestID The ID of the request to be cancelled
/// @return True if succesful, error otherwise
function cancelRequest(uint256 _requestID) external returns (bool);
/// @notice Retrieve info about a request
/// @dev Requests ids are numerical
/// @param _requestID The numerical ID of the request
/// @return A tuple representation of the request struct.
/// To save space`spends` and `pays` are stored as keccak256
/// hashes of the original information. The `state` is
/// `0` for "does not exist", `1` for "active" and `2` for
/// "cancelled."
function getRequest(
uint256 _requestID
) external view returns (
bytes32 spends,
bytes32 pays,
uint64 paysValue,
uint8 state,
address consumer,
address owner,
uint8 numConfs,
uint256 notBefore
);
}
interface IRelay {
event Extension(bytes32 indexed _first, bytes32 indexed _last);
event NewTip(bytes32 indexed _from, bytes32 indexed _to, bytes32 indexed _gcd);
function getCurrentEpochDifficulty() external view returns (uint256);
function getPrevEpochDifficulty() external view returns (uint256);
function getRelayGenesis() external view returns (bytes32);
function getBestKnownDigest() external view returns (bytes32);
function getLastReorgCommonAncestor() external view returns (bytes32);
function findHeight(bytes32 _digest) external view returns (uint256);
function findAncestor(bytes32 _digest, uint256 _offset) external view returns (bytes32);
function isAncestor(bytes32 _ancestor, bytes32 _descendant, uint256 _limit) external view returns (bool);
function addHeaders(bytes calldata _anchor, bytes calldata _headers) external returns (bool);
function addHeadersWithRetarget(
bytes calldata _oldPeriodStartHeader,
bytes calldata _oldPeriodEndHeader,
bytes calldata _headers
) external returns (bool);
function markNewHeaviest(
bytes32 _ancestor,
bytes calldata _currentBest,
bytes calldata _newBest,
uint256 _limit
) external returns (bool);
}
pragma solidity ^0.5.10;
/** @title Relay */
/** @author Summa (https://summa.one) */
import {SafeMath} from "@summa-tx/bitcoin-spv-sol/contracts/SafeMath.sol";
import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol";
import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol";
import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol";
import {IRelay} from "./Interfaces.sol";
contract Relay is IRelay {
using SafeMath for uint256;
using BytesLib for bytes;
using BTCUtils for bytes;
using ValidateSPV for bytes;
// How often do we store the height?
// A higher number incurs less storage cost, but more lookup cost
uint32 public constant HEIGHT_INTERVAL = 4;
bytes32 internal relayGenesis;
bytes32 internal bestKnownDigest;
bytes32 internal lastReorgCommonAncestor;
mapping (bytes32 => bytes32) internal previousBlock;
mapping (bytes32 => uint256) internal blockHeight;
uint256 internal currentEpochDiff;
uint256 internal prevEpochDiff;
/// @notice Gives a starting point for the relay
/// @dev We don't check this AT ALL really. Don't use relays with bad genesis
/// @param _genesisHeader The starting header
/// @param _height The starting height
/// @param _periodStart The hash of the first header in the genesis epoch
constructor(bytes memory _genesisHeader, uint256 _height, bytes32 _periodStart) public {
require(_genesisHeader.length == 80, "Stop being dumb");
bytes32 _genesisDigest = _genesisHeader.hash256();
require(
_periodStart & bytes32(0x0000000000000000000000000000000000000000000000000000000000ffffff) == bytes32(0),
"Period start hash does not have work. Hint: wrong byte order?");
relayGenesis = _genesisDigest;
bestKnownDigest = _genesisDigest;
lastReorgCommonAncestor = _genesisDigest;
blockHeight[_genesisDigest] = _height;
blockHeight[_periodStart] = _height.sub(_height % 2016);
currentEpochDiff = _genesisHeader.extractDifficulty();
}
/// @notice Getter for currentEpochDiff
/// @dev This is updated when a new heavist header has a new diff
/// @return The difficulty of the bestKnownDigest
function getCurrentEpochDifficulty() external view returns (uint256) {
return currentEpochDiff;
}
/// @notice Getter for prevEpochDiff
/// @dev This is updated when a difficulty change is accepted
/// @return The difficulty of the previous epoch
function getPrevEpochDifficulty() external view returns (uint256) {
return prevEpochDiff;
}
/// @notice Getter for relayGenesis
/// @dev This is an initialization parameter
/// @return The hash of the first block of the relay
function getRelayGenesis() public view returns (bytes32) {
return relayGenesis;
}
/// @notice Getter for bestKnownDigest
/// @dev This updated only by calling markNewHeaviest
/// @return The hash of the best marked chain tip
function getBestKnownDigest() public view returns (bytes32) {
return bestKnownDigest;
}
/// @notice Getter for relayGenesis
/// @dev This is updated only by calling markNewHeaviest
/// @return The hash of the shared ancestor of the most recent fork
function getLastReorgCommonAncestor() public view returns (bytes32) {
return lastReorgCommonAncestor;
}
/// @notice Finds the height of a header by its digest
/// @dev Will fail if the header is unknown
/// @param _digest The header digest to search for
/// @return The height of the header, or error if unknown
function findHeight(bytes32 _digest) external view returns (uint256) {
return _findHeight(_digest);
}
/// @notice Finds an ancestor for a block by its digest
/// @dev Will fail if the header is unknown
/// @param _digest The header digest to search for
/// @return The height of the header, or error if unknown
function findAncestor(bytes32 _digest, uint256 _offset) external view returns (bytes32) {
return _findAncestor(_digest, _offset);
}
/// @notice Checks if a digest is an ancestor of the current one
/// @dev Limit the amount of lookups (and thus gas usage) with _limit
/// @param _ancestor The prospective ancestor
/// @param _descendant The descendant to check
/// @param _limit The maximum number of blocks to check
/// @return true if ancestor is at most limit blocks lower than descendant, otherwise false
function isAncestor(bytes32 _ancestor, bytes32 _descendant, uint256 _limit) external view returns (bool) {
return _isAncestor(_ancestor, _descendant, _limit);
}
/// @notice Adds headers to storage after validating
/// @dev We check integrity and consistency of the header chain
/// @param _anchor The header immediately preceeding the new chain
/// @param _headers A tightly-packed list of 80-byte Bitcoin headers
/// @return True if successfully written, error otherwise
function addHeaders(bytes calldata _anchor, bytes calldata _headers) external returns (bool) {
return _addHeaders(_anchor, _headers, false);
}
/// @notice Adds headers to storage, performs additional validation of retarget
/// @dev Checks the retarget, the heights, and the linkage
/// @param _oldPeriodStartHeader The first header in the difficulty period being closed
/// @param _oldPeriodEndHeader The last header in the difficulty period being closed
/// @param _headers A tightly-packed list of 80-byte Bitcoin headers
/// @return True if successfully written, error otherwise
function addHeadersWithRetarget(
bytes calldata _oldPeriodStartHeader,
bytes calldata _oldPeriodEndHeader,
bytes calldata _headers
) external returns (bool) {
return _addHeadersWithRetarget(_oldPeriodStartHeader, _oldPeriodEndHeader, _headers);
}
/// @notice Gives a starting point for the relay
/// @dev We don't check this AT ALL really. Don't use relays with bad genesis
/// @param _ancestor The digest of the most recent common ancestor
/// @param _currentBest The 80-byte header referenced by bestKnownDigest
/// @param _newBest The 80-byte header to mark as the new best
/// @param _limit Limit the amount of traversal of the chain
/// @return True if successfully updates bestKnownDigest, error otherwise
function markNewHeaviest(
bytes32 _ancestor,
bytes calldata _currentBest,
bytes calldata _newBest,
uint256 _limit
) external returns (bool) {
return _markNewHeaviest(_ancestor, _currentBest, _newBest, _limit);
}
/// @notice Adds headers to storage after validating
/// @dev We check integrity and consistency of the header chain
/// @param _anchor The header immediately preceeding the new chain
/// @param _headers A tightly-packed list of new 80-byte Bitcoin headers to record
/// @param _internal True if called internally from addHeadersWithRetarget, false otherwise
/// @return True if successfully written, error otherwise
function _addHeaders(bytes memory _anchor, bytes memory _headers, bool _internal) internal returns (bool) {
uint256 _height;
bytes memory _header;
bytes32 _currentDigest;
bytes32 _previousDigest = _anchor.hash256();
uint256 _target = _headers.slice(0, 80).extractTarget();
uint256 _anchorHeight = _findHeight(_previousDigest); /* NB: errors if unknown */
require(
_internal || _anchor.extractTarget() == _target,
"Unexpected retarget on external call");
require(_headers.length % 80 == 0, "Header array length must be divisible by 80");
/*
NB:
1. check that the header has sufficient work
2. check that headers are in a coherent chain (no retargets, hash links good)
3. Store the block connection
4. Store the height
*/
for (uint256 i = 0; i < _headers.length / 80; i = i.add(1)) {
_header = _headers.slice(i.mul(80), 80);
_height = _anchorHeight.add(i + 1);
_currentDigest = _header.hash256();
/*
NB:
if the block is already authenticated, we don't need to a work check
Or write anything to state. This saves gas
*/
if (previousBlock[_currentDigest] == bytes32(0)) {
require(
abi.encodePacked(_currentDigest).reverseEndianness().bytesToUint() <= _target,
"Header work is insufficient");
previousBlock[_currentDigest] = _previousDigest;
if (_height % HEIGHT_INTERVAL == 0) {
/*
NB: We store the height only every 4th header to save gas
*/
blockHeight[_currentDigest] = _height;
}
}
/* NB: we do still need to make chain level checks tho */
require(_header.extractTarget() == _target, "Target changed unexpectedly");
require(_header.validateHeaderPrevHash(_previousDigest), "Headers do not form a consistent chain");
_previousDigest = _currentDigest;
}
emit Extension(
_anchor.hash256(),
_currentDigest);
return true;
}
/// @notice Adds headers to storage, performs additional validation of retarget
/// @dev Checks the retarget, the heights, and the linkage
/// @param _oldPeriodStartHeader The first header in the difficulty period being closed
/// @param _oldPeriodEndHeader The last header in the difficulty period being closed
/// @param _headers A tightly-packed list of 80-byte Bitcoin headers
/// @return True if successfully written, error otherwise
function _addHeadersWithRetarget(
bytes memory _oldPeriodStartHeader,
bytes memory _oldPeriodEndHeader,
bytes memory _headers
) internal returns (bool) {
/* NB: requires that both blocks are known */
uint256 _startHeight = _findHeight(_oldPeriodStartHeader.hash256());
uint256 _endHeight = _findHeight(_oldPeriodEndHeader.hash256());
/* NB: retargets should happen at 2016 block intervals */
require(
_endHeight % 2016 == 2015,
"Must provide the last header of the closing difficulty period");
require(
_endHeight == _startHeight.add(2015),
"Must provide exactly 1 difficulty period");
require(
_oldPeriodStartHeader.extractDifficulty() == _oldPeriodEndHeader.extractDifficulty(),
"Period header difficulties do not match");
/* NB: This comparison looks weird because header nBits encoding truncates targets */
bytes memory _newPeriodStart = _headers.slice(0, 80);
uint256 _actualTarget = _newPeriodStart.extractTarget();
uint256 _expectedTarget = BTCUtils.retargetAlgorithm(
_oldPeriodStartHeader.extractTarget(),
_oldPeriodStartHeader.extractTimestamp(),
_oldPeriodEndHeader.extractTimestamp()
);
require(
(_actualTarget & _expectedTarget) == _actualTarget,
"Invalid retarget provided");
// If the current known prevEpochDiff doesn't match, and this old period is near the chaintip/
// update the stored prevEpochDiff
// Don't update if this is a deep past epoch
uint256 _oldDiff = _oldPeriodStartHeader.extractDifficulty();
if (prevEpochDiff != _oldDiff && _endHeight > _findHeight(bestKnownDigest).sub(2016)) {
prevEpochDiff = _oldDiff;
}
// Pass all but the first through to be added
return _addHeaders(_oldPeriodEndHeader, _headers, true);
}
/// @notice Finds the height of a header by its digest
/// @dev Will fail if the header is unknown
/// @param _digest The header digest to search for
/// @return The height of the header
function _findHeight(bytes32 _digest) internal view returns (uint256) {
uint256 _height = 0;
bytes32 _current = _digest;
for (uint256 i = 0; i < HEIGHT_INTERVAL + 1; i = i.add(1)) {
_height = blockHeight[_current];
if (_height == 0) {
_current = previousBlock[_current];
} else {
return _height.add(i);
}
}
revert("Unknown block");
}
/// @notice Finds an ancestor for a block by its digest
/// @dev Will fail if the header is unknown
/// @param _digest The header digest to search for
/// @return The height of the header, or error if unknown
function _findAncestor(bytes32 _digest, uint256 _offset) internal view returns (bytes32) {
bytes32 _current = _digest;
for (uint256 i = 0; i < _offset; i = i.add(1)) {
_current = previousBlock[_current];
}
require(_current != bytes32(0), "Unknown ancestor");
return _current;
}
/// @notice Checks if a digest is an ancestor of the current one
/// @dev Limit the amount of lookups (and thus gas usage) with _limit
/// @param _ancestor The prospective ancestor
/// @param _descendant The descendant to check
/// @param _limit The maximum number of blocks to check
/// @return true if ancestor is at most limit blocks lower than descendant, otherwise false
function _isAncestor(bytes32 _ancestor, bytes32 _descendant, uint256 _limit) internal view returns (bool) {
bytes32 _current = _descendant;
/* NB: 200 gas/read, so gas is capped at ~200 * limit */
for (uint256 i = 0; i < _limit; i = i.add(1)) {
if (_current == _ancestor) {
return true;
}
_current = previousBlock[_current];
}
return false;
}
/// @notice Marks the new best-known chain tip
/// @param _ancestor The digest of the most recent common ancestor
/// @param _currentBest The 80-byte header referenced by bestKnownDigest
/// @param _newBest The 80-byte header to mark as the new best
/// @param _limit Limit the amount of traversal of the chain
/// @return True if successfully updates bestKnownDigest, error otherwise
function _markNewHeaviest(
bytes32 _ancestor,
bytes memory _currentBest,
bytes memory _newBest,
uint256 _limit
) internal returns (bool) {
require(_limit <= 2016, "Requested limit is greater than 1 difficulty period");
bytes32 _newBestDigest = _newBest.hash256();
bytes32 _currentBestDigest = _currentBest.hash256();
require(_currentBestDigest == bestKnownDigest, "Passed in best is not best known");
require(
previousBlock[_newBestDigest] != bytes32(0),
"New best is unknown");
require(
_isMostRecentAncestor(_ancestor, bestKnownDigest, _newBestDigest, _limit),
"Ancestor must be heaviest common ancestor");
require(
_heaviestFromAncestor(_ancestor, _currentBest, _newBest) == _newBestDigest,
"New best hash does not have more work than previous");
bestKnownDigest = _newBestDigest;
lastReorgCommonAncestor = _ancestor;
uint256 _newDiff = _newBest.extractDifficulty();
if (_newDiff != currentEpochDiff) {
currentEpochDiff = _newDiff;
}
emit NewTip(
_currentBestDigest,
_newBestDigest,
_ancestor);
return true;
}
/// @notice Checks if a digest is an ancestor of the current one
/// @dev Limit the amount of lookups (and thus gas usage) with _limit
/// @param _ancestor The prospective shared ancestor
/// @param _left A chain tip
/// @param _right A chain tip
/// @param _limit The maximum number of blocks to check
/// @return true if it is the most recent common ancestor within _limit, false otherwise
function _isMostRecentAncestor(
bytes32 _ancestor,
bytes32 _left,
bytes32 _right,
uint256 _limit
) internal view returns (bool) {
/* NB: sure why not */
if (_ancestor == _left && _ancestor == _right) {
return true;
}
bytes32 _leftCurrent = _left;
bytes32 _rightCurrent = _right;
bytes32 _leftPrev = _left;
bytes32 _rightPrev = _right;
for(uint256 i = 0; i < _limit; i = i.add(1)) {
if (_leftPrev != _ancestor) {
_leftCurrent = _leftPrev; // cheap
_leftPrev = previousBlock[_leftPrev]; // expensive
}
if (_rightPrev != _ancestor) {
_rightCurrent = _rightPrev; // cheap
_rightPrev = previousBlock[_rightPrev]; // expensive
}
}
if (_leftCurrent == _rightCurrent) {return false;} /* NB: If the same, they're a nearer ancestor */
if (_leftPrev != _rightPrev) {return false;} /* NB: Both must be ancestor */
return true;
}
/// @notice Decides which header is heaviest from the ancestor
/// @dev Does not support reorgs above 2017 blocks (:
/// @param _ancestor The prospective shared ancestor
/// @param _left A chain tip
/// @param _right A chain tip
/// @return true if it is the most recent common ancestor within _limit, false otherwise
function _heaviestFromAncestor(
bytes32 _ancestor,
bytes memory _left,
bytes memory _right
) internal view returns (bytes32) {
uint256 _ancestorHeight = _findHeight(_ancestor);
uint256 _leftHeight = _findHeight(_left.hash256());
uint256 _rightHeight = _findHeight(_right.hash256());
require(
_leftHeight >= _ancestorHeight && _rightHeight >= _ancestorHeight,
"A descendant height is below the ancestor height");
/* NB: we can shortcut if one block is in a new difficulty window and the other isn't */
uint256 _nextPeriodStartHeight = _ancestorHeight.add(2016).sub(_ancestorHeight % 2016);
bool _leftInPeriod = _leftHeight < _nextPeriodStartHeight;
bool _rightInPeriod = _rightHeight < _nextPeriodStartHeight;
/*
NB:
1. Left is in a new window, right is in the old window. Left is heavier
2. Right is in a new window, left is in the old window. Right is heavier
3. Both are in the same window, choose the higher one
4. They're in different new windows. Choose the heavier one
*/
if (!_leftInPeriod && _rightInPeriod) {return _left.hash256();}
if (_leftInPeriod && !_rightInPeriod) {return _right.hash256();}
if (_leftInPeriod && _rightInPeriod) {
return _leftHeight >= _rightHeight ? _left.hash256() : _right.hash256();
} else { // if (!_leftInPeriod && !_rightInPeriod) {
if (((_leftHeight % 2016).mul(_left.extractDifficulty())) <
(_rightHeight % 2016).mul(_right.extractDifficulty())) {
return _right.hash256();
} else {
return _left.hash256();
}
}
}
}
// For unittests
contract TestRelay is Relay {
/// @notice Gives a starting point for the relay
/// @dev We don't check this AT ALL really. Don't use relays with bad genesis
/// @param _genesisHeader The starting header
/// @param _height The starting height
/// @param _periodStart The hash of the first header in the genesis epoch
constructor(bytes memory _genesisHeader, uint256 _height, bytes32 _periodStart)
Relay(_genesisHeader, _height, _periodStart)
public {}
function heaviestFromAncestor(
bytes32 _ancestor,
bytes calldata _left,
bytes calldata _right
) external view returns (bytes32) {
return _heaviestFromAncestor(_ancestor, _left, _right);
}
function isMostRecentAncestor(
bytes32 _ancestor,
bytes32 _left,
bytes32 _right,
uint256 _limit
) external view returns (bool) {
return _isMostRecentAncestor(_ancestor, _left, _right, _limit);
}
}
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;
}
}
pragma solidity ^0.5.10;
/*
https://github.com/GNSPS/solidity-bytes-utils/
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <https://unlicense.org>
*/
/** @title BytesLib **/
/** @author https://github.com/GNSPS **/
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {
if (_length == 0) {
return hex"";
}
uint _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
// Alloc bytes array with additional 32 bytes afterspace and assign it's size
res := mload(0x40)
mstore(0x40, add(add(res, 64), _length))
mstore(res, _length)
// Compute distance between source and destination pointers
let diff := sub(res, add(_bytes, _start))
for {
let src := add(add(_bytes, 32), _start)
let end := add(src, _length)
} lt(src, end) {
src := add(src, 32)
} {
mstore(add(src, diff), mload(src))
}
}
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
uint _totalLen = _start + 20;
require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds.");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
uint _totalLen = _start + 32;
require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds.");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function toBytes32(bytes memory _source) pure internal returns (bytes32 result) {
if (_source.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_source, 32))
}
}
function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {
uint _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
result := keccak256(add(add(_bytes, 32), _start), _length)
}
}
}
pragma solidity ^0.5.10;
/** @title BitcoinSPV */
/** @author Summa (https://summa.one) */
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
library BTCUtils {
using BytesLib for bytes;
using SafeMath for uint256;
// The target at minimum Difficulty. Also the target of the genesis block
uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;
uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds
uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks
uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/* ***** */
/* UTILS */
/* ***** */
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _flag The first byte of a VarInt
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {
if (uint8(_flag[0]) == 0xff) {
return 8; // one-byte flag, 8 bytes data
}
if (uint8(_flag[0]) == 0xfe) {
return 4; // one-byte flag, 4 bytes data
}
if (uint8(_flag[0]) == 0xfd) {
return 2; // one-byte flag, 2 bytes data
}
return 0; // flag is data
}
/// @notice Parse a VarInt into its data length and the number it represents
/// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.
/// Caller SHOULD explicitly handle this case (or bubble it up)
/// @param _b A byte-string starting with a VarInt
/// @return number of bytes in the encoding (not counting the tag), the encoded int
function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {
uint8 _dataLen = determineVarIntDataLength(_b);
if (_dataLen == 0) {
return (0, uint8(_b[0]));
}
if (_b.length < 1 + _dataLen) {
return (ERR_BAD_ARG, 0);
}
uint256 _number = bytesToUint(reverseEndianness(_b.slice(1, _dataLen)));
return (_dataLen, _number);
}
/// @notice Changes the endianness of a byte array
/// @dev Returns a new, backwards, bytes
/// @param _b The bytes to reverse
/// @return The reversed bytes
function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {
bytes memory _newValue = new bytes(_b.length);
for (uint i = 0; i < _b.length; i++) {
_newValue[_b.length - i - 1] = _b[i];
}
return _newValue;
}
/// @notice Changes the endianness of a uint256
/// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
/// @param _b The unsigned integer to reverse
/// @return 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 Converts big-endian bytes to a uint
/// @dev Traverses the byte array and sums the bytes
/// @param _b The big-endian bytes-encoded integer
/// @return The integer representation
function bytesToUint(bytes memory _b) internal pure returns (uint256) {
uint256 _number;
for (uint i = 0; i < _b.length; i++) {
_number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));
}
return _number;
}
/// @notice Get the last _num bytes from a byte array
/// @param _b The byte array to slice
/// @param _num The number of bytes to extract from the end
/// @return The last _num bytes of _b
function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {
uint256 _start = _b.length.sub(_num);
return _b.slice(_start, _num);
}
/// @notice Implements bitcoin's hash160 (rmd160(sha2()))
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash160(bytes memory _b) internal pure returns (bytes memory) {
return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash256(bytes memory _b) internal pure returns (bytes32) {
return sha256(abi.encodePacked(sha256(_b)));
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _b The pre-image
/// @return The digest
function hash256View(bytes memory _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
let ptr := mload(0x40)
pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32))
pop(staticcall(gas, 2, ptr, 32, ptr, 32))
res := mload(ptr)
}
}
/* ************ */
/* Legacy Input */
/* ************ */
/// @notice Extracts the nth input from the vin (0-indexed)
/// @dev Iterates over the vin. If you need to extract several, write a custom function
/// @param _vin The vin as a tightly-packed byte array
/// @param _index The 0-indexed location of the input to extract
/// @return The input as a byte array
function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nIns, "Vin read overrun");
bytes memory _remaining;
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i ++) {
_remaining = _vin.slice(_offset, _vin.length - _offset);
_len = determineInputLength(_remaining);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
_offset = _offset + _len;
}
_remaining = _vin.slice(_offset, _vin.length - _offset);
_len = determineInputLength(_remaining);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _vin.slice(_offset, _len);
}
/// @notice Determines whether an input is legacy
/// @dev False if no scriptSig, otherwise True
/// @param _input The input
/// @return True for legacy, False for witness
function isLegacyInput(bytes memory _input) internal pure returns (bool) {
return _input.keccak256Slice(36, 1) != keccak256(hex"00");
}
/// @notice Determines the length of a scriptSig in an input
/// @dev Will return 0 if passed a witness input.
/// @param _input The LEGACY input
/// @return The length of the script sig
function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {
if (_input.length < 37) {
return (ERR_BAD_ARG, 0);
}
bytes memory _afterOutpoint = _input.slice(36, _input.length - 36);
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = parseVarInt(_afterOutpoint);
return (_varIntDataLen, _scriptSigLen);
}
/// @notice Determines the length of an input from its scriptSig
/// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence
/// @param _input The input
/// @return The length of the input in bytes
function determineInputLength(bytes memory _input) internal pure returns (uint256) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;
}
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The LEGACY input
/// @return The sequence bytes (LE uint)
function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice(36 + 1 + _varIntDataLen + _scriptSigLen, 4);
}
/// @notice Extracts the sequence from the input
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The LEGACY input
/// @return The sequence number (big-endian uint)
function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {
bytes memory _leSeqence = extractSequenceLELegacy(_input);
bytes memory _beSequence = reverseEndianness(_leSeqence);
return uint32(bytesToUint(_beSequence));
}
/// @notice Extracts the VarInt-prepended scriptSig from the input in a tx
/// @dev Will return hex"00" if passed a witness input
/// @param _input The LEGACY input
/// @return The length-prepended scriptSig
function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);
}
/* ************* */
/* Witness Input */
/* ************* */
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The WITNESS input
/// @return The sequence bytes (LE uint)
function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes memory) {
return _input.slice(37, 4);
}
/// @notice Extracts the sequence from the input in a tx
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The WITNESS input
/// @return The sequence number (big-endian uint)
function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {
bytes memory _leSeqence = extractSequenceLEWitness(_input);
bytes memory _inputeSequence = reverseEndianness(_leSeqence);
return uint32(bytesToUint(_inputeSequence));
}
/// @notice Extracts the outpoint from the input in a tx
/// @dev 32-byte tx id with 4-byte index
/// @param _input The input
/// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)
function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {
return _input.slice(0, 36);
}
/// @notice Extracts the outpoint tx id from an input
/// @dev 32-byte tx id
/// @param _input The input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {
return _input.slice(0, 32).toBytes32();
}
/// @notice Extracts the LE tx input index from the input in a tx
/// @dev 4-byte tx index
/// @param _input The input
/// @return The tx index (little-endian bytes)
function extractTxIndexLE(bytes memory _input) internal pure returns (bytes memory) {
return _input.slice(32, 4);
}
/* ****** */
/* Output */
/* ****** */
/// @notice Determines the length of an output
/// @dev Works with any properly formatted output
/// @param _output The output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLength(bytes memory _output) internal pure returns (uint256) {
if (_output.length < 9) {
return ERR_BAD_ARG;
}
bytes memory _afterValue = _output.slice(8, _output.length - 8);
uint256 _varIntDataLen;
uint256 _scriptPubkeyLength;
(_varIntDataLen, _scriptPubkeyLength) = parseVarInt(_afterValue);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
// 8-byte value, 1-byte for tag itself
return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;
}
/// @notice Extracts the output at a given index in the TxOuts vector
/// @dev Iterates over the vout. If you need to extract multiple, write a custom function
/// @param _vout The _vout to extract from
/// @param _index The 0-indexed location of the output to extract
/// @return The specified output
function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nOuts, "Vout read overrun");
bytes memory _remaining;
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i ++) {
_remaining = _vout.slice(_offset, _vout.length - _offset);
_len = determineOutputLength(_remaining);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
_offset += _len;
}
_remaining = _vout.slice(_offset, _vout.length - _offset);
_len = determineOutputLength(_remaining);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
return _vout.slice(_offset, _len);
}
/// @notice Extracts the value bytes from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value as LE bytes
function extractValueLE(bytes memory _output) internal pure returns (bytes memory) {
return _output.slice(0, 8);
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value
function extractValue(bytes memory _output) internal pure returns (uint64) {
bytes memory _leValue = extractValueLE(_output);
bytes memory _beValue = reverseEndianness(_leValue);
return uint64(bytesToUint(_beValue));
}
/// @notice Extracts the data from an op return output
/// @dev Returns hex"" if no data or not an op return
/// @param _output The output
/// @return Any data contained in the opreturn output, null if not an op return
function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {
if (_output.keccak256Slice(9, 1) != keccak256(hex"6a")) {
return hex"";
}
bytes memory _dataLen = _output.slice(10, 1);
return _output.slice(11, bytesToUint(_dataLen));
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix and validates format
/// @param _output The output
/// @return The hash committed to by the pk_script, or null for errors
function extractHash(bytes memory _output) internal pure returns (bytes memory) {
uint8 _scriptLen = uint8(_output[8]);
// don't have to worry about overflow here.
// if _scriptLen + 9 overflows, then output.length would have to be < 9
// for this check to pass. if it's < 9, then we errored when assigning
// _scriptLen
if (_scriptLen + 9 != _output.length) {
return hex"";
}
if (uint8(_output[9]) == 0) {
if (_scriptLen < 2) {
return hex"";
}
uint256 _payloadLen = uint8(_output[10]);
// Check for maliciously formatted witness outputs.
// No need to worry about underflow as long b/c of the `< 2` check
if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {
return hex"";
}
return _output.slice(11, _payloadLen);
} else {
bytes32 _tag = _output.keccak256Slice(8, 3);
// p2pkh
if (_tag == keccak256(hex"1976a9")) {
// Check for maliciously formatted p2pkh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[11]) != 0x14 ||
_output.keccak256Slice(_output.length - 2, 2) != keccak256(hex"88ac")) {
return hex"";
}
return _output.slice(12, 20);
//p2sh
} else if (_tag == keccak256(hex"17a914")) {
// Check for maliciously formatted p2sh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[_output.length - 1]) != 0x87) {
return hex"";
}
return _output.slice(11, 20);
}
}
return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */
}
/* ********** */
/* Witness TX */
/* ********** */
/// @notice Checks that the vin passed up is properly formatted
/// @dev Consider a vin with a valid vout in its scriptsig
/// @param _vin Raw bytes length-prefixed input vector
/// @return True if it represents a validly formatted vin
function validateVin(bytes memory _vin) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
// Not valid if it says there are too many or no inputs
if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nIns; i++) {
// If we're at the end, but still expect more
if (_offset >= _vin.length) {
return false;
}
// Grab the next input and determine its length.
bytes memory _next = _vin.slice(_offset, _vin.length - _offset);
uint256 _nextLen = determineInputLength(_next);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
// Increase the offset by that much
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vin.length;
}
/// @notice Checks that the vout passed up is properly formatted
/// @dev Consider a vout with a valid scriptpubkey
/// @param _vout Raw bytes length-prefixed output vector
/// @return True if it represents a validly formatted vout
function validateVout(bytes memory _vout) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
// Not valid if it says there are too many or no outputs
if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nOuts; i++) {
// If we're at the end, but still expect more
if (_offset >= _vout.length) {
return false;
}
// Grab the next output and determine its length.
// Increase the offset by that much
bytes memory _next = _vout.slice(_offset, _vout.length - _offset);
uint256 _nextLen = determineOutputLength(_next);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vout.length;
}
/* ************ */
/* Block Header */
/* ************ */
/// @notice Extracts the transaction merkle root from a block header
/// @dev Use verifyHash256Merkle to verify proofs with this root
/// @param _header The header
/// @return The merkle root (little-endian)
function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes memory) {
return _header.slice(36, 32);
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _header The header
/// @return The target threshold
function extractTarget(bytes memory _header) internal pure returns (uint256) {
bytes memory _m = _header.slice(72, 3);
uint8 _e = uint8(_header[75]);
uint256 _mantissa = bytesToUint(reverseEndianness(_m));
uint _exponent = _e - 3;
return _mantissa * (256 ** _exponent);
}
/// @notice Calculate difficulty from the difficulty 1 target and current target
/// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet
/// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _target The current target
/// @return The block difficulty (bdiff)
function calculateDifficulty(uint256 _target) internal pure returns (uint256) {
// Difficulty 1 calculated from 0x1d00ffff
return DIFF1_TARGET.div(_target);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) {
return _header.slice(4, 32);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (little-endian bytes)
function extractTimestampLE(bytes memory _header) internal pure returns (bytes memory) {
return _header.slice(68, 4);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (uint)
function extractTimestamp(bytes memory _header) internal pure returns (uint32) {
return uint32(bytesToUint(reverseEndianness(extractTimestampLE(_header))));
}
/// @notice Extracts the expected difficulty from a block header
/// @dev Does NOT verify the work
/// @param _header The header
/// @return The difficulty as an integer
function extractDifficulty(bytes memory _header) internal pure returns (uint256) {
return calculateDifficulty(extractTarget(_header));
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal pure returns (bytes32) {
return hash256(abi.encodePacked(_a, _b));
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed.
/// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(bytes memory _proof, uint _index) internal pure returns (bool) {
// Not an even number of hashes
if (_proof.length % 32 != 0) {
return false;
}
// Special case for coinbase-only blocks
if (_proof.length == 32) {
return true;
}
// Should never occur
if (_proof.length == 64) {
return false;
}
uint _idx = _index;
bytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32();
bytes32 _current = _proof.slice(0, 32).toBytes32();
for (uint i = 1; i < (_proof.length.div(32)) - 1; i++) {
if (_idx % 2 == 1) {
_current = _hash256MerkleStep(_proof.slice(i * 32, 32), abi.encodePacked(_current));
} else {
_current = _hash256MerkleStep(abi.encodePacked(_current), _proof.slice(i * 32, 32));
}
_idx = _idx >> 1;
}
return _current == _root;
}
/*
NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72
NB: We get a full-bitlength target from this. For comparison with
header-encoded targets we need to mask it with the header target
e.g. (full & truncated) == truncated
*/
/// @notice performs the bitcoin difficulty retarget
/// @dev implements the Bitcoin algorithm precisely
/// @param _previousTarget the target of the previous period
/// @param _firstTimestamp the timestamp of the first block in the difficulty period
/// @param _secondTimestamp the timestamp of the last block in the difficulty period
/// @return the new period's target threshold
function retargetAlgorithm(
uint256 _previousTarget,
uint256 _firstTimestamp,
uint256 _secondTimestamp
) internal pure returns (uint256) {
uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);
// Normalize ratio to factor of 4 if very long or very short
if (_elapsedTime < RETARGET_PERIOD.div(4)) {
_elapsedTime = RETARGET_PERIOD.div(4);
}
if (_elapsedTime > RETARGET_PERIOD.mul(4)) {
_elapsedTime = RETARGET_PERIOD.mul(4);
}
/*
NB: high targets e.g. ffff0020 can cause overflows here
so we divide it by 256**2, then multiply by 256**2 later
we know the target is evenly divisible by 256**2, so this isn't an issue
*/
uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);
return _adjusted.div(RETARGET_PERIOD).mul(65536);
}
}
pragma solidity ^0.5.10;
/** @title ValidateSPV*/
/** @author Summa (https://summa.one) */
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
import {BTCUtils} from "./BTCUtils.sol";
library ValidateSPV {
using BTCUtils for bytes;
using BTCUtils for uint256;
using BytesLib for bytes;
using SafeMath for uint256;
enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS }
enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD }
uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;
uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;
function getErrBadLength() internal pure returns (uint256) {
return ERR_BAD_LENGTH;
}
function getErrInvalidChain() internal pure returns (uint256) {
return ERR_INVALID_CHAIN;
}
function getErrLowWork() internal pure returns (uint256) {
return ERR_LOW_WORK;
}
/// @notice Validates a tx inclusion in the block
/// @dev `index` is not a reliable indicator of location within a block
/// @param _txid The txid (LE)
/// @param _merkleRoot The merkle root (as in the block header)
/// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root)
/// @param _index The leaf's index in the tree (0-indexed)
/// @return true if fully valid, false otherwise
function prove(
bytes32 _txid,
bytes32 _merkleRoot,
bytes memory _intermediateNodes,
uint _index
) internal pure returns (bool) {
// Shortcut the empty-block case
if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) {
return true;
}
bytes memory _proof = abi.encodePacked(_txid, _intermediateNodes, _merkleRoot);
// If the Merkle proof failed, bubble up error
return _proof.verifyHash256Merkle(_index);
}
/// @notice Hashes transaction to get txid
/// @dev Supports Legacy and Witness
/// @param _version 4-bytes version
/// @param _vin Raw bytes length-prefixed input vector
/// @param _vout Raw bytes length-prefixed output vector
/// @param _locktime 4-byte tx locktime
/// @return 32-byte transaction id, little endian
function calculateTxId(
bytes memory _version,
bytes memory _vin,
bytes memory _vout,
bytes memory _locktime
) internal pure returns (bytes32) {
// Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime)
return abi.encodePacked(_version, _vin, _vout, _locktime).hash256();
}
/// @notice Checks validity of header chain
/// @notice Compares the hash of each header to the prevHash in the next header
/// @param _headers Raw byte array of header chain
/// @return The total accumulated difficulty of the header chain, or an error code
function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) {
// Check header chain length
if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;}
// Initialize header start index
bytes32 _digest;
_totalDifficulty = 0;
for (uint256 _start = 0; _start < _headers.length; _start += 80) {
// ith header start index and ith header
bytes memory _header = _headers.slice(_start, 80);
// After the first header, check that headers are in a chain
if (_start != 0) {
if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;}
}
// ith header target
uint256 _target = _header.extractTarget();
// Require that the header has sufficient work
_digest = _header.hash256View();
if(uint256(_digest).reverseUint256() > _target) {
return ERR_LOW_WORK;
}
// Add ith header difficulty to difficulty sum
_totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty());
}
}
/// @notice Checks validity of header work
/// @param _digest Header digest
/// @param _target The target threshold
/// @return true if header work is valid, false otherwise
function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) {
if (_digest == bytes32(0)) {return false;}
return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() < _target);
}
/// @notice Checks validity of header chain
/// @dev Compares current header prevHash to previous header's digest
/// @param _header The raw bytes header
/// @param _prevHeaderDigest The previous header's digest
/// @return true if the connect is valid, false otherwise
function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) {
// Extract prevHash of current header
bytes32 _prevHash = _header.extractPrevBlockLE().toBytes32();
// Compare prevHash of current header to previous header's digest
if (_prevHash != _prevHeaderDigest) {return false;}
return true;
}
}
pragma solidity ^0.5.10;
/** @title OnDemandSPV */
/** @author Summa (https://summa.one) */
import {ISPVConsumer} from "../Interfaces.sol";
import {OnDemandSPV} from "../OnDemandSPV.sol";
contract DummyConsumer is ISPVConsumer {
event Consumed(bytes32 indexed _txid, uint256 indexed _requestID, uint256 _gasLeft);
bool broken = false;
function setBroken(bool _b) external {
broken = _b;
}
function spv(
bytes32 _txid,
bytes calldata,
bytes calldata,
uint256 _requestID,
uint8,
uint8
) external {
emit Consumed(_txid, _requestID, gasleft());
if (broken) {
revert("BORKED");
}
}
function cancel(
uint256 _requestID,
address payable _odspv
) external returns (bool) {
return OnDemandSPV(_odspv).cancelRequest(_requestID);
}
}
contract DummyOnDemandSPV is OnDemandSPV {
constructor(
bytes memory _genesisHeader,
uint256 _height,
bytes32 _periodStart,
uint256 _firstID
) OnDemandSPV(
_genesisHeader,
_height,
_periodStart,
_firstID
) public {return ;}
bool callResult = false;
function requestTest(
uint256 _requestID,
bytes calldata _spends,
bytes calldata _pays,
uint64 _paysValue,
address _consumer,
uint8 _numConfs,
uint256 _notBefore
) external returns (uint256) {
nextID = _requestID;
return _request(_spends, _pays, _paysValue, _consumer, _numConfs, _notBefore);
}
function setCallResult(bool _r) external {
callResult = _r;
}
function _isAncestor(bytes32, bytes32, uint256) internal view returns (bool) {
return callResult;
}
function getValidatedTx(bytes32 _txid) public view returns (bool) {
return validatedTxns[_txid];
}
function setValidatedTx(bytes32 _txid) public {
validatedTxns[_txid] = true;
}
function unsetValidatedTx(bytes32 _txid) public {
validatedTxns[_txid] = false;
}
function callCallback(
bytes32 _txid,
uint16 _reqIndices,
bytes calldata _vin,
bytes calldata _vout,
uint256 _requestID
) external returns (bool) {
return _callCallback(_txid, _reqIndices, _vin, _vout, _requestID);
}
function checkInclusion(
bytes calldata _header,
bytes calldata _proof,
uint256 _index,
bytes32 _txid,
uint256 _requestID
) external view returns (bool) {
return _checkInclusion(_header, _proof, _index, _txid, _requestID);
}
function _getConfs(bytes32 _header) internal view returns (uint8){
if (_header == bytes32(0)) {
return OnDemandSPV._getConfs(lastReorgCommonAncestor);
}
return 8;
}
function getConfsTest() external view returns (uint8) {
return _getConfs(bytes32(0));
}
function checkRequests(
uint16 _requestIndices,
bytes calldata _vin,
bytes calldata _vout,
uint256 _requestID
) external view returns (bool) {
return _checkRequests(_requestIndices, _vin, _vout, _requestID);
}
function whatTimeIsItRightNowDotCom() external view returns (uint256) {
return block.timestamp;
}
}
| Subscribe to a feed of Bitcoin txns matching a request The request can be a spent utxo and/or a created utxo _spends An outpoint that must be spent in acceptable txns (optional) _pays An output script that must be paid in acceptable txns (optional) _paysValue A minimum value that must be paid to the output script (optional) _consumer The address of a ISPVConsumer exposing spv _numConfs The minimum number of Bitcoin confirmations to accept _notBefore A timestamp before which proofs are not accepted return A unique request ID if it's not length-prefixed, length-prefix it | function _request(
bytes memory _spends,
bytes memory _pays,
uint64 _paysValue,
address _consumer,
uint8 _numConfs,
uint256 _notBefore
) internal returns (uint256) {
uint256 _requestID = nextID;
nextID = nextID + 1;
bytes memory pays = _pays;
require(_spends.length == 36 || _spends.length == 0, "Not a valid UTXO");
uint256 _paysLen = pays.length;
if (_paysLen > 0 && uint8(pays[0]) != _paysLen - 1) {
pays = abi.encodePacked(uint8(_paysLen), pays);
}
bytes memory _p = abi.encodePacked(bytes8(0), pays);
require(
"Not a standard output type");
require(_spends.length > 0 || _paysLen > 0, "No request specified");
ProofRequest storage _req = requests[_requestID];
_req.owner = msg.sender;
if (_spends.length > 0) {
_req.spends = keccak256(_spends);
}
if (_paysLen > 0) {
_req.pays = keccak256(pays);
}
if (_paysValue > 0) {
_req.paysValue = _paysValue;
}
_req.numConfs = _numConfs;
}
| 12,594,018 |
pragma solidity ^0.4.23;
// Copyright 2017 OpenST Ltd.
//
// 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.
//
// ----------------------------------------------------------------------------
// Common: Core
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
import "./CoreInterface.sol";
import "./MerklePatriciaProof.sol";
import "./ProofLib.sol";
import "./WorkersInterface.sol";
import "./RLP.sol";
import "./SafeMath.sol";
/**
* @title Core contract which implements CoreInterface.
*
* @notice Core is a minimal stub that will become the anchoring and consensus point for
* the utility chain to validate itself against.
*/
contract Core is CoreInterface {
using SafeMath for uint256;
/** Events */
event StateRootCommitted(uint256 blockHeight, bytes32 stateRoot);
/** wasAlreadyProved parameter differentiates between first call and replay call of proveOpenST method for same block height */
event OpenSTProven(uint256 blockHeight, bytes32 storageRoot, bool wasAlreadyProved);
/** Storage */
mapping (uint256 /* block height */ => bytes32) private stateRoots;
mapping (uint256 /* block height */ => bytes32) private storageRoots;
/** chainIdOrigin is the origin chain id where core contract is deployed. */
uint256 public coreChainIdOrigin;
/** chainIdRemote is the remote chain id where core contract is deployed. */
uint256 private coreChainIdRemote;
/** It is the address of the openSTUtility/openSTValue contract on the remote chain. */
address private coreOpenSTRemote;
address private coreRegistrar;
/** Latest block height of block for which state root was committed. */
uint256 private latestStateRootBlockHeight;
/** Workers contract address. */
WorkersInterface public workers;
/**
* OpenSTRemote encoded path. Constructed with below flow:
* coreOpenSTRemote => sha3 => bytes32 => bytes
*/
bytes private encodedOpenSTRemotePath;
/** Modifiers */
/**
* @notice Modifier onlyWorker.
*
* @dev Checks if msg.sender is whitelisted worker address to proceed.
*/
modifier onlyWorker() {
// msg.sender should be worker only
require(workers.isWorker(msg.sender), "Worker address is not whitelisted");
_;
}
// time that is safe to execute confirmStakingIntent and confirmRedemptionIntent from the time the
// stake and redemption was initiated
// 5Days in seconds
uint256 private constant TIME_TO_WAIT = 432000;
uint256 public remoteChainBlockGenerationTime;
uint256 public remoteChainBlocksToWait;
/* Public functions */
/**
* @notice Contract constructor.
*
* @dev bytes32ToBytes is ProofLib contract method.
*
* @param _registrar Address of the registrar which registers for utility tokens.
* @param _chainIdOrigin Chain id where current core contract is deployed since core contract can be deployed on remote chain also.
* @param _chainIdRemote If current chain is value then _chainIdRemote is chain id of utility chain.
* @param _openSTRemote If current chain is value then _openSTRemote is address of openSTUtility contract address.
* @param _remoteChainBlockGenerationTime block generation time of remote chain.
* @param _blockHeight Block height at which _stateRoot needs to store.
* @param _stateRoot State root hash of given _blockHeight.
* @param _workers Workers contract address.
*/
constructor(
address _registrar,
uint256 _chainIdOrigin,
uint256 _chainIdRemote,
address _openSTRemote,
uint256 _remoteChainBlockGenerationTime,
uint256 _blockHeight,
bytes32 _stateRoot,
WorkersInterface _workers)
public
{
require(_registrar != address(0), "Registrar address is 0");
require(_chainIdOrigin != 0, "Origin chain Id is 0");
require(_chainIdRemote != 0, "Remote chain Id is 0");
require(_openSTRemote != address(0), "OpenSTRemote address is 0");
require(_workers != address(0), "Workers contract address is 0");
require(_remoteChainBlockGenerationTime != uint256(0), "Remote block time is 0");
coreRegistrar = _registrar;
coreChainIdOrigin = _chainIdOrigin;
coreChainIdRemote = _chainIdRemote;
coreOpenSTRemote = _openSTRemote;
workers = _workers;
remoteChainBlockGenerationTime = _remoteChainBlockGenerationTime;
remoteChainBlocksToWait = TIME_TO_WAIT.div(_remoteChainBlockGenerationTime);
// Encoded remote path.
encodedOpenSTRemotePath = ProofLib.bytes32ToBytes(keccak256(abi.encodePacked(coreOpenSTRemote)));
latestStateRootBlockHeight = _blockHeight;
stateRoots[latestStateRootBlockHeight] = _stateRoot;
}
/** Public functions */
/**
* @notice Public view function registrar.
*
* @return address coreRegistrar.
*/
function registrar()
public
view
returns (address /* registrar */)
{
return coreRegistrar;
}
/**
* @notice Public view function chainIdRemote.
*
* @return uint256 coreChainIdRemote.
*/
function chainIdRemote()
public
view
returns (uint256 /* chainIdRemote */)
{
return coreChainIdRemote;
}
/**
* @notice Public view function openSTRemote.
*
* @return address coreOpenSTRemote.
*/
function openSTRemote()
public
view
returns (address /* OpenSTRemote */)
{
return coreOpenSTRemote;
}
/**
* @notice Get safe unlock height
*
* @dev block height that is safe to execute confirmStakingIntent and confirmRedemptionIntent,
* else there will be possibility that there is not much time left for executing processStaking
* and processRedeeming respectively
*
* @return uint256 safeUnlockHeight
*/
function safeUnlockHeight()
external
view
returns (uint256 /* safeUnlockHeight */)
{
return remoteChainBlocksToWait.add(latestStateRootBlockHeight);
}
/**
* @notice Public view function getStateRoot.
*
* @param _blockHeight Block height for which state root is needed.
*
* @return bytes32 State root.
*/
function getStateRoot(
uint256 _blockHeight)
public
view
returns (bytes32 /* state root */)
{
return stateRoots[_blockHeight];
}
/**
* @notice Public view function getStorageRoot.
*
* @param _blockHeight Block height for which storage root is needed.
*
* @return bytes32 Storage root.
*/
function getStorageRoot(
uint256 _blockHeight)
public
view
returns (bytes32 /* storage root */)
{
return storageRoots[_blockHeight];
}
/**
* @notice Public function getLatestStateRootBlockHeight.
*
* @return uint256 Latest state root block height.
*/
function getLatestStateRootBlockHeight()
public
view
returns (uint256 /* block height */)
{
return latestStateRootBlockHeight;
}
/** External functions */
/**
* @notice External function commitStateRoot.
*
* @dev commitStateRoot Called from game process.
* Commit new state root for a block height.
*
* @param _blockHeight Block height for which stateRoots mapping needs to update.
* @param _stateRoot State root of input block height.
*
* @return bytes32 stateRoot
*/
function commitStateRoot(
uint256 _blockHeight,
bytes32 _stateRoot)
external
onlyWorker
returns(bytes32 /* stateRoot */)
{
// State root should be valid
require(_stateRoot != bytes32(0), "State root is 0");
// Input block height should be valid
require(_blockHeight > latestStateRootBlockHeight, "Given block height is lower or equal to highest committed state root block height.");
stateRoots[_blockHeight] = _stateRoot;
latestStateRootBlockHeight = _blockHeight;
emit StateRootCommitted(_blockHeight, _stateRoot);
return _stateRoot;
}
/**
* @notice External function proveOpenST.
*
* @dev proveOpenST can be called by anyone to verify merkle proof of OpenSTRemote contract address. OpenSTRemote is OpenSTUtility
* contract address on utility chain and OpenSTValue contract address on value chain.
* Trust factor is brought by stateRoots mapping. stateRoot is committed in commitStateRoot function by mosaic process
* which is a trusted decentralized system running separately.
* It's important to note that in replay calls of proveOpenST bytes _rlpParentNodes variable is not validated. In this case
* input storage root derived from merkle proof account nodes is verified with stored storage root of given blockHeight.
* OpenSTProven event has parameter wasAlreadyProved to differentiate between first call and replay calls.
*
* @param _blockHeight Block height at which OpenST is to be proven.
* @param _rlpEncodedAccount RLP encoded account node object.
* @param _rlpParentNodes RLP encoded value of account proof parent nodes.
*
* @return bool Status.
*/
function proveOpenST(
uint256 _blockHeight,
bytes _rlpEncodedAccount,
bytes _rlpParentNodes)
external
returns(bool /* success */)
{
// _rlpEncodedAccount should be valid
require(_rlpEncodedAccount.length != 0, "Length of RLP encoded account is 0");
// _rlpParentNodes should be valid
require(_rlpParentNodes.length != 0, "Length of RLP parent nodes is 0");
bytes32 stateRoot = stateRoots[_blockHeight];
// State root should be present for the block height
require(stateRoot != bytes32(0), "State root is 0");
// Decode RLP encoded account value
RLP.RLPItem memory accountItem = RLP.toRLPItem(_rlpEncodedAccount);
// Convert to list
RLP.RLPItem[] memory accountArray = RLP.toList(accountItem);
// Array 3rd position is storage root
bytes32 storageRoot = RLP.toBytes32(accountArray[2]);
// Hash the rlpEncodedValue value
bytes32 hashedAccount = keccak256(abi.encodePacked(_rlpEncodedAccount));
// If account already proven for block height
bytes32 provenStorageRoot = storageRoots[_blockHeight];
if (provenStorageRoot != bytes32(0)) {
// Check extracted storage root is matching with existing stored storage root
require(provenStorageRoot == storageRoot, "Storage root mismatch when account is already proven");
// wasAlreadyProved is true here since proveOpenST is replay call for same block height
emit OpenSTProven(_blockHeight, storageRoot, true);
// return true
return true;
}
// Verify the remote OpenST contract against the committed state root with the state trie Merkle proof
require(MerklePatriciaProof.verify(hashedAccount, encodedOpenSTRemotePath, _rlpParentNodes, stateRoot), "Account proof is not verified.");
// After verification update storageRoots mapping
storageRoots[_blockHeight] = storageRoot;
// wasAlreadyProved is false since proveOpenST is called for the first time for a block height
emit OpenSTProven(_blockHeight, storageRoot, false);
return true;
}
} | External function commitStateRoot. commitStateRoot Called from game process. Commit new state root for a block height. _blockHeight Block height for which stateRoots mapping needs to update. _stateRoot State root of input block height. return bytes32 stateRoot/ State root should be valid Input block height should be valid | function commitStateRoot(
uint256 _blockHeight,
bytes32 _stateRoot)
external
onlyWorker
returns(bytes32 /* stateRoot */)
{
require(_stateRoot != bytes32(0), "State root is 0");
require(_blockHeight > latestStateRootBlockHeight, "Given block height is lower or equal to highest committed state root block height.");
stateRoots[_blockHeight] = _stateRoot;
latestStateRootBlockHeight = _blockHeight;
emit StateRootCommitted(_blockHeight, _stateRoot);
return _stateRoot;
}
| 15,810,764 |
./partial_match/1/0x2845f0f85c1AfC937Dc214b5dF34f03b71F062E8/sources/Kilroy.sol | sell half the tokens for ETH and add liquidity sell tokens for ETH and send to project fund | function swapAndLiquify(uint256 tAmount) private lockTheSwap {
uint256 totalFee = _liquidityFee.add( _projectFee );
uint256 forLiquidity = tAmount.mul(_liquidityFee).div(totalFee);
uint256 forFund = tAmount.sub(forLiquidity);
if(forLiquidity > 0 && _liquidityFee > 0)
{
uint256 half = forLiquidity.div(2);
uint256 otherHalf = forLiquidity.sub(half);
uint256 initialBalance = address(this).balance;
swapTokensForETH(half, address(this) );
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
if(forFund > 0 && _projectFee > 0)
{
uint256 initialBalance = address(this).balance;
swapTokensForETH(forFund, fundAddress);
uint256 newBalance = address(this).balance.sub(initialBalance);
emit SwapAndFundProject(newBalance);
}
}
| 2,763,590 |
/**
*Submitted for verification at Etherscan.io on 2022-04-12
*/
/**
*Submitted for verification at BscScan.com on 2022-04-06
*/
// File: contracts/interfaces/IAggregationExecutor.sol
pragma solidity >=0.6.12;
interface IAggregationExecutor {
function callBytes(bytes calldata data) external payable; // 0xd9c45357
// callbytes per swap sequence
function swapSingleSequence(
bytes calldata data
) external;
function finalTransactionProcessing(
address tokenIn,
address tokenOut,
address to,
bytes calldata destTokenFeeData
) external;
}
// File: contracts/AggregationRouter.sol
// SPDX-License-Identifier: MIT
// Copyright (c) 2019-2021 1inch
// 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.6;
pragma abicoder v2;
interface IERC20 {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper: APPROVE_FAILED"
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper: TRANSFER_FAILED"
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper: TRANSFER_FROM_FAILED"
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0, "ds-math-division-by-zero");
c = a / b;
}
}
interface IERC20Permit {
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
library RevertReasonParser {
function parse(bytes memory data, string memory prefix)
internal
pure
returns (string memory)
{
// https://solidity.readthedocs.io/en/latest/control-structures.html#revert
// We assume that revert reason is abi-encoded as Error(string)
// 68 = 4-byte selector 0x08c379a0 + 32 bytes offset + 32 bytes length
if (
data.length >= 68 &&
data[0] == "\x08" &&
data[1] == "\xc3" &&
data[2] == "\x79" &&
data[3] == "\xa0"
) {
string memory reason;
// solhint-disable no-inline-assembly
assembly {
// 68 = 32 bytes data length + 4-byte selector + 32 bytes offset
reason := add(data, 68)
}
/*
revert reason is padded up to 32 bytes with ABI encoder: Error(string)
also sometimes there is extra 32 bytes of zeros padded in the end:
https://github.com/ethereum/solidity/issues/10170
because of that we can't check for equality and instead check
that string length + extra 68 bytes is less than overall data length
*/
require(
data.length >= 68 + bytes(reason).length,
"Invalid revert reason"
);
return string(abi.encodePacked(prefix, "Error(", reason, ")"));
}
// 36 = 4-byte selector 0x4e487b71 + 32 bytes integer
else if (
data.length == 36 &&
data[0] == "\x4e" &&
data[1] == "\x48" &&
data[2] == "\x7b" &&
data[3] == "\x71"
) {
uint256 code;
// solhint-disable no-inline-assembly
assembly {
// 36 = 32 bytes data length + 4-byte selector
code := mload(add(data, 36))
}
return
string(abi.encodePacked(prefix, "Panic(", _toHex(code), ")"));
}
return string(abi.encodePacked(prefix, "Unknown(", _toHex(data), ")"));
}
function _toHex(uint256 value) private pure returns (string memory) {
return _toHex(abi.encodePacked(value));
}
function _toHex(bytes memory data) private pure returns (string memory) {
bytes16 alphabet = 0x30313233343536373839616263646566;
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 * i + 2] = alphabet[uint8(data[i] >> 4)];
str[2 * i + 3] = alphabet[uint8(data[i] & 0x0f)];
}
return string(str);
}
}
contract Permitable {
event Error(string reason);
function _permit(
IERC20 token,
uint256 amount,
bytes calldata permit
) internal {
if (permit.length == 32 * 7) {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory result) =
address(token).call(
abi.encodePacked(IERC20Permit.permit.selector, permit)
);
if (!success) {
string memory reason =
RevertReasonParser.parse(result, "Permit call failed: ");
if (token.allowance(msg.sender, address(this)) < amount) {
revert(reason);
} else {
emit Error(reason);
}
}
}
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address 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;
}
}
contract AggregationRouter is Permitable, Ownable {
using SafeMath for uint256;
address public immutable WETH;
address private constant ETH_ADDRESS =
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
uint256 private constant _PARTIAL_FILL = 0x01;
uint256 private constant _REQUIRES_EXTRA_ETH = 0x02;
uint256 private constant _SHOULD_CLAIM = 0x04;
uint256 private constant _BURN_FROM_MSG_SENDER = 0x08;
uint256 private constant _BURN_FROM_TX_ORIGIN = 0x10;
uint256 private constant _SIMPLE_SWAP = 0x20;
struct SwapDescription {
IERC20 srcToken;
IERC20 dstToken;
address[] srcReceivers;
uint[] srcAmounts;
address dstReceiver;
uint256 amount;
uint256 minReturnAmount;
uint256 flags;
bytes permit;
}
struct SimpleSwapData {
address[] firstPools;
uint256[] firstSwapAmounts;
bytes[] swapDatas;
uint256 deadline;
bytes destTokenFeeData;
}
event Swapped(
address sender,
IERC20 srcToken,
IERC20 dstToken,
address dstReceiver,
uint256 spentAmount,
uint256 returnAmount
);
event ClientData(
bytes clientData
);
event Exchange(address pair, uint256 amountOut, address output);
constructor(address _WETH) public {
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH);
// only accept ETH via fallback from the WETH contract
}
function rescueFunds(address token, uint256 amount) external onlyOwner {
if (_isETH(IERC20(token))) {
TransferHelper.safeTransferETH(msg.sender, amount);
} else {
TransferHelper.safeTransfer(token, msg.sender, amount);
}
}
function swap(
IAggregationExecutor caller,
SwapDescription calldata desc,
bytes calldata executorData,
bytes calldata clientData
) external payable returns (uint256 returnAmount) {
require(desc.minReturnAmount > 0, "Min return should not be 0");
require(executorData.length > 0, "executorData should be not zero");
uint256 flags = desc.flags;
// simple mode swap
if (flags & _SIMPLE_SWAP != 0) return swapSimpleMode(caller, desc, executorData, clientData);
IERC20 srcToken = desc.srcToken;
IERC20 dstToken = desc.dstToken;
if (flags & _REQUIRES_EXTRA_ETH != 0) {
require(
msg.value > (_isETH(srcToken) ? desc.amount : 0),
"Invalid msg.value"
);
} else {
require(
msg.value == (_isETH(srcToken) ? desc.amount : 0),
"Invalid msg.value"
);
}
require(
desc.srcReceivers.length == desc.srcAmounts.length,
"Invalid lengths for receiving src tokens"
);
if (flags & _SHOULD_CLAIM != 0) {
require(!_isETH(srcToken), "Claim token is ETH");
_permit(srcToken, desc.amount, desc.permit);
for (uint i = 0; i < desc.srcReceivers.length; i++) {
TransferHelper.safeTransferFrom(
address(srcToken),
msg.sender,
desc.srcReceivers[i],
desc.srcAmounts[i]
);
}
}
if (_isETH(srcToken)) {
// normally in case taking fee in srcToken and srcToken is the native token
for (uint i = 0; i < desc.srcReceivers.length; i++) {
TransferHelper.safeTransferETH(
desc.srcReceivers[i],
desc.srcAmounts[i]
);
}
}
address dstReceiver =
(desc.dstReceiver == address(0)) ? msg.sender : desc.dstReceiver;
uint256 initialSrcBalance =
(flags & _PARTIAL_FILL != 0) ? _getBalance(srcToken, msg.sender) : 0;
uint256 initialDstBalance = _getBalance(dstToken, dstReceiver);
_callWithEth(caller, executorData);
uint256 spentAmount = desc.amount;
returnAmount = _getBalance(dstToken, dstReceiver).sub(initialDstBalance);
if (flags & _PARTIAL_FILL != 0) {
spentAmount = initialSrcBalance.add(desc.amount).sub(
_getBalance(srcToken, msg.sender)
);
require(
returnAmount.mul(desc.amount) >=
desc.minReturnAmount.mul(spentAmount),
"Return amount is not enough"
);
} else {
require(
returnAmount >= desc.minReturnAmount,
"Return amount is not enough"
);
}
emit Swapped(
msg.sender,
srcToken,
dstToken,
dstReceiver,
spentAmount,
returnAmount
);
emit Exchange(
address(caller),
returnAmount,
_isETH(dstToken) ? WETH : address(dstToken)
);
emit ClientData(
clientData
);
}
function swapSimpleMode(
IAggregationExecutor caller,
SwapDescription calldata desc,
bytes calldata executorData,
bytes calldata clientData
) public returns (uint256 returnAmount) {
IERC20 srcToken = desc.srcToken;
IERC20 dstToken = desc.dstToken;
require(!_isETH(srcToken), "src is eth, should use normal swap");
_permit(srcToken, desc.amount, desc.permit);
uint256 totalSwapAmount = desc.amount;
if (desc.srcReceivers.length > 0) {
// take fee in tokenIn
require(
desc.srcReceivers.length == 1 &&
desc.srcReceivers.length == desc.srcAmounts.length,
"Wrong number of src receivers"
);
TransferHelper.safeTransferFrom(
address(srcToken),
msg.sender,
desc.srcReceivers[0],
desc.srcAmounts[0]
);
require(desc.srcAmounts[0] <= totalSwapAmount, "invalid fee amount in src token");
totalSwapAmount -= desc.srcAmounts[0];
}
address dstReceiver =
(desc.dstReceiver == address(0)) ? msg.sender : desc.dstReceiver;
uint256 initialDstBalance = _getBalance(dstToken, dstReceiver);
_swapMultiSequencesWithSimpleMode(
caller,
address(srcToken),
totalSwapAmount,
address(dstToken),
dstReceiver,
executorData
);
returnAmount = _getBalance(dstToken, dstReceiver).sub(initialDstBalance);
require(
returnAmount >= desc.minReturnAmount,
"Return amount is not enough"
);
emit Swapped(
msg.sender,
srcToken,
dstToken,
dstReceiver,
desc.amount,
returnAmount
);
emit Exchange(
address(caller),
returnAmount,
_isETH(dstToken) ? WETH : address(dstToken)
);
emit ClientData(
clientData
);
}
// Only use this mode if the first pool of each sequence can receive tokenIn directly into the pool
function _swapMultiSequencesWithSimpleMode(
IAggregationExecutor caller,
address tokenIn,
uint256 totalSwapAmount,
address tokenOut,
address dstReceiver,
bytes calldata executorData
) internal {
SimpleSwapData memory swapData = abi.decode(executorData, (SimpleSwapData));
require(swapData.deadline >= block.timestamp, "ROUTER: Expired");
require(
swapData.firstPools.length == swapData.firstSwapAmounts.length
&& swapData.firstPools.length == swapData.swapDatas.length,
"invalid swap data length"
);
uint256 numberSeq = swapData.firstPools.length;
for (uint256 i = 0; i < numberSeq; i++) {
// collect amount to the first pool
TransferHelper.safeTransferFrom(
tokenIn,
msg.sender,
swapData.firstPools[i],
swapData.firstSwapAmounts[i]
);
require(swapData.firstSwapAmounts[i] <= totalSwapAmount, "invalid swap amount");
totalSwapAmount -= swapData.firstSwapAmounts[i];
{
// solhint-disable-next-line avoid-low-level-calls
// may take some native tokens for commission fee
(bool success, bytes memory result) =
address(caller).call(
abi.encodeWithSelector(
caller.swapSingleSequence.selector,
swapData.swapDatas[i]
)
);
if (!success) {
revert(RevertReasonParser.parse(result, "swapSingleSequence failed: "));
}
}
}
{
// solhint-disable-next-line avoid-low-level-calls
// may take some native tokens for commission fee
(bool success, bytes memory result) =
address(caller).call(
abi.encodeWithSelector(
caller.finalTransactionProcessing.selector,
tokenIn,
tokenOut,
dstReceiver,
swapData.destTokenFeeData
)
);
if (!success) {
revert(RevertReasonParser.parse(result, "finalTransactionProcessing failed: "));
}
}
}
function _getBalance(IERC20 token, address account)
internal
view
returns (uint256)
{
if (_isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function _isETH(IERC20 token) internal pure returns (bool) {
return (address(token) == ETH_ADDRESS);
}
function _callWithEth(IAggregationExecutor caller, bytes calldata executorData) internal {
// solhint-disable-next-line avoid-low-level-calls
// may take some native tokens for commission fee
uint256 ethAmount = _getBalance(IERC20(ETH_ADDRESS), address(this));
if (ethAmount > msg.value) ethAmount = msg.value;
(bool success, bytes memory result) =
address(caller).call{value: ethAmount}(
abi.encodeWithSelector(caller.callBytes.selector, executorData)
);
if (!success) {
revert(RevertReasonParser.parse(result, "callBytes failed: "));
}
}
} | Only use this mode if the first pool of each sequence can receive tokenIn directly into the pool collect amount to the first pool solhint-disable-next-line avoid-low-level-calls may take some native tokens for commission fee solhint-disable-next-line avoid-low-level-calls may take some native tokens for commission fee | function _swapMultiSequencesWithSimpleMode(
IAggregationExecutor caller,
address tokenIn,
uint256 totalSwapAmount,
address tokenOut,
address dstReceiver,
bytes calldata executorData
) internal {
SimpleSwapData memory swapData = abi.decode(executorData, (SimpleSwapData));
require(swapData.deadline >= block.timestamp, "ROUTER: Expired");
require(
swapData.firstPools.length == swapData.firstSwapAmounts.length
&& swapData.firstPools.length == swapData.swapDatas.length,
"invalid swap data length"
);
uint256 numberSeq = swapData.firstPools.length;
for (uint256 i = 0; i < numberSeq; i++) {
TransferHelper.safeTransferFrom(
tokenIn,
msg.sender,
swapData.firstPools[i],
swapData.firstSwapAmounts[i]
);
require(swapData.firstSwapAmounts[i] <= totalSwapAmount, "invalid swap amount");
totalSwapAmount -= swapData.firstSwapAmounts[i];
{
(bool success, bytes memory result) =
address(caller).call(
abi.encodeWithSelector(
caller.swapSingleSequence.selector,
swapData.swapDatas[i]
)
);
if (!success) {
revert(RevertReasonParser.parse(result, "swapSingleSequence failed: "));
}
}
}
{
(bool success, bytes memory result) =
address(caller).call(
abi.encodeWithSelector(
caller.finalTransactionProcessing.selector,
tokenIn,
tokenOut,
dstReceiver,
swapData.destTokenFeeData
)
);
if (!success) {
revert(RevertReasonParser.parse(result, "finalTransactionProcessing failed: "));
}
}
}
| 7,619,886 |
// 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 "../../solidity-utils/contracts/math/FixedPoint.sol";
import "../../solidity-utils/contracts/helpers/InputHelpers.sol";
import "../../pool-utils/contracts/LegacyBaseMinimalSwapInfoPool.sol";
import "./WeightedPoolUserData.sol";
import "./WeightedMath.sol";
/**
* @dev Base class for WeightedPools containing swap, join and exit logic, but leaving storage and management of
* the weights to subclasses. Derived contracts can choose to make weights immutable, mutable, or even dynamic
* based on local or external logic.
*/
abstract contract BaseWeightedPool is LegacyBaseMinimalSwapInfoPool {
using FixedPoint for uint256;
using WeightedPoolUserData for bytes;
uint256 private _lastInvariant;
constructor(
IVault vault,
string memory name,
string memory symbol,
IERC20[] memory tokens,
address[] memory assetManagers,
uint256 swapFeePercentage,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration,
address owner
)
LegacyBasePool(
vault,
// Given LegacyBaseMinimalSwapInfoPool supports both of these specializations, and this Pool never registers
// or deregisters any tokens after construction, picking Two Token when the Pool only has two tokens is free
// gas savings.
tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.MINIMAL_SWAP_INFO,
name,
symbol,
tokens,
assetManagers,
swapFeePercentage,
pauseWindowDuration,
bufferPeriodDuration,
owner
)
{
// solhint-disable-previous-line no-empty-blocks
}
// Virtual functions
/**
* @dev Returns the normalized weight of `token`. Weights are fixed point numbers that sum to FixedPoint.ONE.
*/
function _getNormalizedWeight(IERC20 token) internal view virtual returns (uint256);
/**
* @dev Returns all normalized weights, in the same order as the Pool's tokens.
*/
function _getNormalizedWeights() internal view virtual returns (uint256[] memory);
/**
* @dev Returns all normalized weights, in the same order as the Pool's tokens, along with the index of the token
* with the highest weight.
*/
function _getNormalizedWeightsAndMaxWeightIndex() internal view virtual returns (uint256[] memory, uint256);
function getLastInvariant() public view virtual returns (uint256) {
return _lastInvariant;
}
/**
* @dev Returns the current value of the invariant.
*/
function getInvariant() public view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
// Since the Pool hooks always work with upscaled balances, we manually
// upscale here for consistency
_upscaleArray(balances, _scalingFactors());
(uint256[] memory normalizedWeights, ) = _getNormalizedWeightsAndMaxWeightIndex();
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
function getNormalizedWeights() external view returns (uint256[] memory) {
return _getNormalizedWeights();
}
// Base Pool handlers
// Swap
function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) internal virtual override whenNotPaused returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcOutGivenIn(
currentBalanceTokenIn,
_getNormalizedWeight(swapRequest.tokenIn),
currentBalanceTokenOut,
_getNormalizedWeight(swapRequest.tokenOut),
swapRequest.amount
);
}
function _onSwapGivenOut(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) internal virtual override whenNotPaused returns (uint256) {
// Swaps are disabled while the contract is paused.
return
WeightedMath._calcInGivenOut(
currentBalanceTokenIn,
_getNormalizedWeight(swapRequest.tokenIn),
currentBalanceTokenOut,
_getNormalizedWeight(swapRequest.tokenOut),
swapRequest.amount
);
}
// Initialize
function _onInitializePool(
bytes32,
address,
address,
uint256[] memory scalingFactors,
bytes memory userData
) internal virtual override whenNotPaused returns (uint256, uint256[] memory) {
// It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent
// initialization in this case.
WeightedPoolUserData.JoinKind kind = userData.joinKind();
_require(kind == WeightedPoolUserData.JoinKind.INIT, Errors.UNINITIALIZED);
uint256[] memory amountsIn = userData.initialAmountsIn();
InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length);
_upscaleArray(amountsIn, scalingFactors);
(uint256[] memory normalizedWeights, ) = _getNormalizedWeightsAndMaxWeightIndex();
uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn);
// Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more
// consistent in Pools with similar compositions but different number of tokens.
uint256 bptAmountOut = Math.mul(invariantAfterJoin, _getTotalTokens());
_lastInvariant = invariantAfterJoin;
return (bptAmountOut, amountsIn);
}
// Join
function _onJoinPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
override
whenNotPaused
returns (
uint256,
uint256[] memory,
uint256[] memory
)
{
// All joins are disabled while the contract is paused.
(uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex) = _getNormalizedWeightsAndMaxWeightIndex();
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join
// or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas
// computing them on each individual swap
uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances);
uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
maxWeightTokenIndex,
_lastInvariant,
invariantBeforeJoin,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
(uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(
balances,
normalizedWeights,
scalingFactors,
userData
);
// Update the invariant with the balances the Pool will have after the join, in order to compute the
// protocol swap fee amounts due in future joins and exits.
_lastInvariant = _invariantAfterJoin(balances, amountsIn, normalizedWeights);
return (bptAmountOut, amountsIn, dueProtocolFeeAmounts);
}
function _doJoin(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory scalingFactors,
bytes memory userData
) internal returns (uint256, uint256[] memory) {
WeightedPoolUserData.JoinKind kind = userData.joinKind();
if (kind == WeightedPoolUserData.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) {
return _joinExactTokensInForBPTOut(balances, normalizedWeights, scalingFactors, userData);
} else if (kind == WeightedPoolUserData.JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) {
return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData);
} else if (kind == WeightedPoolUserData.JoinKind.ALL_TOKENS_IN_FOR_EXACT_BPT_OUT) {
return _joinAllTokensInForExactBPTOut(balances, userData);
} else {
_revert(Errors.UNHANDLED_JOIN_KIND);
}
}
function _joinExactTokensInForBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory scalingFactors,
bytes memory userData
) private returns (uint256, uint256[] memory) {
(uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut();
InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length);
_upscaleArray(amountsIn, scalingFactors);
(uint256 bptAmountOut, uint256[] memory swapFees) = WeightedMath._calcBptOutGivenExactTokensIn(
balances,
normalizedWeights,
amountsIn,
totalSupply(),
getSwapFeePercentage()
);
// Note that swapFees is already upscaled
_processSwapFeeAmounts(swapFees);
_require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT);
return (bptAmountOut, amountsIn);
}
function _joinTokenInForExactBPTOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private returns (uint256, uint256[] memory) {
(uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut();
// Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`.
_require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS);
(uint256 amountIn, uint256 swapFee) = WeightedMath._calcTokenInGivenExactBptOut(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountOut,
totalSupply(),
getSwapFeePercentage()
);
// Note that swapFee is already upscaled
_processSwapFeeAmount(tokenIndex, swapFee);
// We join in a single token, so we initialize amountsIn with zeros
uint256[] memory amountsIn = new uint256[](_getTotalTokens());
// And then assign the result to the selected token
amountsIn[tokenIndex] = amountIn;
return (bptAmountOut, amountsIn);
}
function _joinAllTokensInForExactBPTOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
uint256 bptAmountOut = userData.allTokensInForExactBptOut();
// Note that there is no maximum amountsIn parameter: this is handled by `IVault.joinPool`.
uint256[] memory amountsIn = WeightedMath._calcAllTokensInGivenExactBptOut(
balances,
bptAmountOut,
totalSupply()
);
return (bptAmountOut, amountsIn);
}
// Exit
function _onExitPool(
bytes32,
address,
address,
uint256[] memory balances,
uint256,
uint256 protocolSwapFeePercentage,
uint256[] memory scalingFactors,
bytes memory userData
)
internal
virtual
override
returns (
uint256 bptAmountIn,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
)
{
(uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex) = _getNormalizedWeightsAndMaxWeightIndex();
// Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens
// out) remain functional.
if (_isNotPaused()) {
// Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous
// join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids
// spending gas calculating the fees on each individual swap.
uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances);
dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(
balances,
normalizedWeights,
maxWeightTokenIndex,
_lastInvariant,
invariantBeforeExit,
protocolSwapFeePercentage
);
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub);
} else {
// If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and
// reduce the potential for errors.
dueProtocolFeeAmounts = new uint256[](_getTotalTokens());
}
(bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, scalingFactors, userData);
// Update the invariant with the balances the Pool will have after the exit, in order to compute the
// protocol swap fees due in future joins and exits.
_setLastInvariantAfterExit(balances, amountsOut, normalizedWeights);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
}
// Introduced to keep _lastInvariant private
function _setLastInvariantAfterExit(
uint256[] memory balances,
uint256[] memory amountsOut,
uint256[] memory normalizedWeights
) internal {
_lastInvariant = _invariantAfterExit(balances, amountsOut, normalizedWeights);
}
function _doExit(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory scalingFactors,
bytes memory userData
) internal returns (uint256, uint256[] memory) {
WeightedPoolUserData.ExitKind kind = userData.exitKind();
if (kind == WeightedPoolUserData.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) {
return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData);
} else if (kind == WeightedPoolUserData.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) {
return _exitExactBPTInForTokensOut(balances, userData);
} else if (kind == WeightedPoolUserData.ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT) {
return _exitBPTInForExactTokensOut(balances, normalizedWeights, scalingFactors, userData);
} else {
_revert(Errors.UNHANDLED_EXIT_KIND);
}
}
function _exitExactBPTInForTokenOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
bytes memory userData
) private whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
_require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS);
(uint256 amountOut, uint256 swapFee) = WeightedMath._calcTokenOutGivenExactBptIn(
balances[tokenIndex],
normalizedWeights[tokenIndex],
bptAmountIn,
totalSupply(),
getSwapFeePercentage()
);
// This is an exceptional situation in which the fee is charged on a token out instead of a token in.
// Note that swapFee is already upscaled.
_processSwapFeeAmount(tokenIndex, swapFee);
// We exit in a single token, so we initialize amountsOut with zeros
uint256[] memory amountsOut = new uint256[](_getTotalTokens());
// And then assign the result to the selected token
amountsOut[tokenIndex] = amountOut;
return (bptAmountIn, amountsOut);
}
function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData)
private
view
returns (uint256, uint256[] memory)
{
// This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted
// in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency.
// This particular exit function is the only one that remains available because it is the simplest one, and
// therefore the one with the lowest likelihood of errors.
uint256 bptAmountIn = userData.exactBptInForTokensOut();
// Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`.
uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply());
return (bptAmountIn, amountsOut);
}
function _exitBPTInForExactTokensOut(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256[] memory scalingFactors,
bytes memory userData
) private whenNotPaused returns (uint256, uint256[] memory) {
// This exit function is disabled if the contract is paused.
(uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut();
InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens());
_upscaleArray(amountsOut, scalingFactors);
(uint256 bptAmountIn, uint256[] memory swapFees) = WeightedMath._calcBptInGivenExactTokensOut(
balances,
normalizedWeights,
amountsOut,
totalSupply(),
getSwapFeePercentage()
);
_require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT);
// This is an exceptional situation in which the fee is charged on a token out instead of a token in.
// Note that swapFee is already upscaled.
_processSwapFeeAmounts(swapFees);
return (bptAmountIn, amountsOut);
}
// Helpers
function _getDueProtocolFeeAmounts(
uint256[] memory balances,
uint256[] memory normalizedWeights,
uint256 maxWeightTokenIndex,
uint256 previousInvariant,
uint256 currentInvariant,
uint256 protocolSwapFeePercentage
) internal view returns (uint256[] memory) {
// Initialize with zeros
uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens());
// Early return if the protocol swap fee percentage is zero, saving gas.
if (protocolSwapFeePercentage == 0) {
return dueProtocolFeeAmounts;
}
// The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the
// token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool.
dueProtocolFeeAmounts[maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount(
balances[maxWeightTokenIndex],
normalizedWeights[maxWeightTokenIndex],
previousInvariant,
currentInvariant,
protocolSwapFeePercentage
);
return dueProtocolFeeAmounts;
}
/**
* @dev Returns the value of the invariant given `balances`, assuming they are increased by `amountsIn`. All
* amounts are expected to be upscaled.
*/
function _invariantAfterJoin(
uint256[] memory balances,
uint256[] memory amountsIn,
uint256[] memory normalizedWeights
) private view returns (uint256) {
_mutateAmounts(balances, amountsIn, FixedPoint.add);
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
function _invariantAfterExit(
uint256[] memory balances,
uint256[] memory amountsOut,
uint256[] memory normalizedWeights
) internal view returns (uint256) {
_mutateAmounts(balances, amountsOut, FixedPoint.sub);
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
/**
* @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`.
*
* Equivalent to `amounts = amounts.map(mutation)`.
*/
function _mutateAmounts(
uint256[] memory toMutate,
uint256[] memory arguments,
function(uint256, uint256) pure returns (uint256) mutation
) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
toMutate[i] = mutation(toMutate[i], arguments[i]);
}
}
/**
* @dev This function returns the appreciation of one BPT relative to the
* underlying tokens. This starts at 1 when the pool is created and grows over time
*/
function getRate() public view returns (uint256) {
// The initial BPT supply is equal to the invariant times the number of tokens.
return Math.mul(getInvariant(), _getTotalTokens()).divDown(totalSupply());
}
}
| Mutates `amounts` by applying `mutation` with each entry in `arguments`. Equivalent to `amounts = amounts.map(mutation)`./ | function _mutateAmounts(
uint256[] memory toMutate,
uint256[] memory arguments,
function(uint256, uint256) pure returns (uint256) mutation
) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
toMutate[i] = mutation(toMutate[i], arguments[i]);
}
}
| 12,850,304 |
pragma solidity 0.4.25;
// File: contracts/sogur/interfaces/IPaymentHandler.sol
/**
* @title Payment Handler Interface.
*/
interface IPaymentHandler {
/**
* @dev Get the amount of available ETH.
* @return The amount of available ETH.
*/
function getEthBalance() external view returns (uint256);
/**
* @dev Transfer ETH to an SGR holder.
* @param _to The address of the SGR holder.
* @param _value The amount of ETH to transfer.
*/
function transferEthToSgrHolder(address _to, uint256 _value) external;
}
// File: contracts/sogur/interfaces/IMintListener.sol
/**
* @title Mint Listener Interface.
*/
interface IMintListener {
/**
* @dev Mint SGR for SGN holders.
* @param _value The amount of SGR to mint.
*/
function mintSgrForSgnHolders(uint256 _value) external;
}
// File: contracts/sogur/interfaces/ISGRTokenManager.sol
/**
* @title SGR Token Manager Interface.
*/
interface ISGRTokenManager {
/**
* @dev Exchange ETH for SGR.
* @param _sender The address of the sender.
* @param _ethAmount The amount of ETH received.
* @return The amount of SGR that the sender is entitled to.
*/
function exchangeEthForSgr(address _sender, uint256 _ethAmount) external returns (uint256);
/**
* @dev Handle after the ETH for SGR exchange operation.
* @param _sender The address of the sender.
* @param _ethAmount The amount of ETH received.
* @param _sgrAmount The amount of SGR given.
*/
function afterExchangeEthForSgr(address _sender, uint256 _ethAmount, uint256 _sgrAmount) external;
/**
* @dev Exchange SGR for ETH.
* @param _sender The address of the sender.
* @param _sgrAmount The amount of SGR received.
* @return The amount of ETH that the sender is entitled to.
*/
function exchangeSgrForEth(address _sender, uint256 _sgrAmount) external returns (uint256);
/**
* @dev Handle after the SGR for ETH exchange operation.
* @param _sender The address of the sender.
* @param _sgrAmount The amount of SGR received.
* @param _ethAmount The amount of ETH given.
* @return The is success result.
*/
function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool);
/**
* @dev Handle direct SGR transfer.
* @param _sender The address of the sender.
* @param _to The address of the destination account.
* @param _value The amount of SGR to be transferred.
*/
function uponTransfer(address _sender, address _to, uint256 _value) external;
/**
* @dev Handle after direct SGR transfer operation.
* @param _sender The address of the sender.
* @param _to The address of the destination account.
* @param _value The SGR transferred amount.
* @param _transferResult The transfer result.
* @return is success result.
*/
function afterTransfer(address _sender, address _to, uint256 _value, bool _transferResult) external returns (bool);
/**
* @dev Handle custodian SGR transfer.
* @param _sender The address of the sender.
* @param _from The address of the source account.
* @param _to The address of the destination account.
* @param _value The amount of SGR to be transferred.
*/
function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external;
/**
* @dev Handle after custodian SGR transfer operation.
* @param _sender The address of the sender.
* @param _from The address of the source account.
* @param _to The address of the destination account.
* @param _value The SGR transferred amount.
* @param _transferFromResult The transferFrom result.
* @return is success result.
*/
function afterTransferFrom(address _sender, address _from, address _to, uint256 _value, bool _transferFromResult) external returns (bool);
/**
* @dev Handle the operation of ETH deposit into the SGRToken contract.
* @param _sender The address of the account which has issued the operation.
* @param _balance The amount of ETH in the SGRToken contract.
* @param _amount The deposited ETH amount.
* @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract.
*/
function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external returns (address, uint256);
/**
* @dev Handle the operation of ETH withdrawal from the SGRToken contract.
* @param _sender The address of the account which has issued the operation.
* @param _balance The amount of ETH in the SGRToken contract prior the withdrawal.
* @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract.
*/
function uponWithdraw(address _sender, uint256 _balance) external returns (address, uint256);
/**
* @dev Handle after ETH withdrawal from the SGRToken contract operation.
* @param _sender The address of the account which has issued the operation.
* @param _wallet The address of the withdrawal wallet.
* @param _amount The ETH withdraw amount.
* @param _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal.
* @param _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal.
*/
function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external;
/**
* @dev Upon SGR mint for SGN holders.
* @param _value The amount of SGR to mint.
*/
function uponMintSgrForSgnHolders(uint256 _value) external;
/**
* @dev Handle after SGR mint for SGN holders.
* @param _value The minted amount of SGR.
*/
function afterMintSgrForSgnHolders(uint256 _value) external;
/**
* @dev Upon SGR transfer to an SGN holder.
* @param _to The address of the SGN holder.
* @param _value The amount of SGR to transfer.
*/
function uponTransferSgrToSgnHolder(address _to, uint256 _value) external;
/**
* @dev Handle after SGR transfer to an SGN holder.
* @param _to The address of the SGN holder.
* @param _value The transferred amount of SGR.
*/
function afterTransferSgrToSgnHolder(address _to, uint256 _value) external;
/**
* @dev Upon ETH transfer to an SGR holder.
* @param _to The address of the SGR holder.
* @param _value The amount of ETH to transfer.
* @param _status The operation's completion-status.
*/
function postTransferEthToSgrHolder(address _to, uint256 _value, bool _status) external;
/**
* @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract.
* @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract.
*/
function getDepositParams() external view returns (address, uint256);
/**
* @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract.
* @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract.
*/
function getWithdrawParams() external view returns (address, uint256);
}
// File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol
/**
* @title Contract Address Locator Interface.
*/
interface IContractAddressLocator {
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) external view returns (address);
/**
* @dev Determine whether or not a contract address relates to one of the identifiers.
* @param _contractAddress The contract address to look for.
* @param _identifiers The identifiers.
* @return A boolean indicating if the contract address relates to one of the identifiers.
*/
function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
}
// File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol
/**
* @title Contract Address Locator Holder.
* @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system.
* @dev Any contract which inherits from this contract can retrieve the address of any contract in the system.
* @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system.
* @dev In addition to that, any function in any contract can be restricted to a specific caller.
*/
contract ContractAddressLocatorHolder {
bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource";
bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ;
bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ;
bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ;
bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ;
bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ;
bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ;
bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ;
bytes32 internal constant _IMintHandler_ = "IMintHandler" ;
bytes32 internal constant _IMintListener_ = "IMintListener" ;
bytes32 internal constant _IMintManager_ = "IMintManager" ;
bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ;
bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ;
bytes32 internal constant _IRedButton_ = "IRedButton" ;
bytes32 internal constant _IReserveManager_ = "IReserveManager" ;
bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ;
bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ;
bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ;
bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ;
bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ;
bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager";
bytes32 internal constant _ISGRToken_ = "ISGRToken" ;
bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ;
bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ;
bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager";
bytes32 internal constant _ISGNToken_ = "ISGNToken" ;
bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ;
bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ;
bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ;
bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ;
bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ;
bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ;
bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ;
bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ;
bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ;
bytes32 internal constant _IETHConverter_ = "IETHConverter" ;
bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ;
bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ;
bytes32 internal constant _IRateApprover_ = "IRateApprover" ;
bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ;
IContractAddressLocator private contractAddressLocator;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) internal {
require(_contractAddressLocator != address(0), "locator is illegal");
contractAddressLocator = _contractAddressLocator;
}
/**
* @dev Get the contract address locator.
* @return The contract address locator.
*/
function getContractAddressLocator() external view returns (IContractAddressLocator) {
return contractAddressLocator;
}
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) internal view returns (address) {
return contractAddressLocator.getContractAddress(_identifier);
}
/**
* @dev Determine whether or not the sender relates to one of the identifiers.
* @param _identifiers The identifiers.
* @return A boolean indicating if the sender relates to one of the identifiers.
*/
function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) {
return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers);
}
/**
* @dev Verify that the caller is mapped to a given identifier.
* @param _identifier The identifier.
*/
modifier only(bytes32 _identifier) {
require(msg.sender == getContractAddress(_identifier), "caller is illegal");
_;
}
}
// File: contracts/saga-genesis/interfaces/ISogurExchanger.sol
/**
* @title Sogur Exchanger Interface.
*/
interface ISogurExchanger {
/**
* @dev Transfer SGR to an SGN holder.
* @param _to The address of the SGN holder.
* @param _value The amount of SGR to transfer.
*/
function transferSgrToSgnHolder(address _to, uint256 _value) external;
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20 {
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 An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "sdjfndskjfndskjfb");
require(to != address(0), "asfdsf");
_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 != 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 != 0, "heerrrrrsss");
require(value <= _balances[account], "heerrrrr");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
// File: contracts/sogur/interfaces/ISGRTokenInfo.sol
/**
* @title SGR Token Info Interface.
*/
interface ISGRTokenInfo {
/**
* @return the name of the sgr token.
*/
function getName() external pure returns (string);
/**
* @return the symbol of the sgr token.
*/
function getSymbol() external pure returns (string);
/**
* @return the number of decimals of the sgr token.
*/
function getDecimals() external pure returns (uint8);
}
// File: contracts/sogur/SGRToken.sol
/**
* Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1
*/
/**
* @title Sogur Token.
* @dev ERC20 compatible.
* @dev Exchange ETH for SGR.
* @dev Exchange SGR for ETH.
*/
contract SGRToken is ERC20, ContractAddressLocatorHolder, IMintListener, ISogurExchanger, IPaymentHandler {
string public constant VERSION = "2.0.0";
bool public initialized;
event SgrTokenInitialized(address indexed _initializer, address _sgaToSGRTokenExchangeAddress, uint256 _sgaToSGRTokenExchangeSGRSupply);
/**
* @dev Public Address 0x6e9Cd21f2B9033ea0953943c81A041fe203D5E55.
* @notice SGR will be minted at this public address for SGN holders.
* @notice SGR will be transferred from this public address upon conversion by an SGN holder.
* @notice It is generated in a manner which ensures that the corresponding private key is unknown.
*/
address public constant SGR_MINTED_FOR_SGN_HOLDERS = address(keccak256("SGR_MINTED_FOR_SGN_HOLDERS"));
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
/**
* @dev Return the contract which implements the ISGRTokenManager interface.
*/
function getSGRTokenManager() public view returns (ISGRTokenManager) {
return ISGRTokenManager(getContractAddress(_ISGRTokenManager_));
}
/**
* @dev Return the contract which implements ISGRTokenInfo interface.
*/
function getSGRTokenInfo() public view returns (ISGRTokenInfo) {
return ISGRTokenInfo(getContractAddress(_ISGRTokenInfo_));
}
/**
* @dev Return the sgr token name.
*/
function name() public view returns (string) {
return getSGRTokenInfo().getName();
}
/**
* @dev Return the sgr token symbol.
*/
function symbol() public view returns (string){
return getSGRTokenInfo().getSymbol();
}
/**
* @dev Return the sgr token number of decimals.
*/
function decimals() public view returns (uint8){
return getSGRTokenInfo().getDecimals();
}
/**
* @dev Reverts if called when the contract is already initialized.
*/
modifier onlyIfNotInitialized() {
require(!initialized, "contract already initialized");
_;
}
/**
* @dev Exchange ETH for SGR.
* @notice Can be executed from externally-owned accounts but not from other contracts.
* @notice This is due to the insufficient gas-stipend provided to the fallback function.
*/
function() external payable {
ISGRTokenManager sgrTokenManager = getSGRTokenManager();
uint256 amount = sgrTokenManager.exchangeEthForSgr(msg.sender, msg.value);
_mint(msg.sender, amount);
sgrTokenManager.afterExchangeEthForSgr(msg.sender, msg.value, amount);
}
/**
* @dev Exchange ETH for SGR.
* @notice Can be executed from externally-owned accounts as well as from other contracts.
*/
function exchange() external payable {
ISGRTokenManager sgrTokenManager = getSGRTokenManager();
uint256 amount = sgrTokenManager.exchangeEthForSgr(msg.sender, msg.value);
_mint(msg.sender, amount);
sgrTokenManager.afterExchangeEthForSgr(msg.sender, msg.value, amount);
}
/**
* @dev Initialize the contract.
* @param _sgaToSGRTokenExchangeAddress the contract address.
* @param _sgaToSGRTokenExchangeSGRSupply SGR supply for the SGAToSGRTokenExchange contract.
*/
function init(address _sgaToSGRTokenExchangeAddress, uint256 _sgaToSGRTokenExchangeSGRSupply) external onlyIfNotInitialized only(_SGAToSGRInitializer_) {
require(_sgaToSGRTokenExchangeAddress != address(0), "SGA to SGR token exchange address is illegal");
initialized = true;
_mint(_sgaToSGRTokenExchangeAddress, _sgaToSGRTokenExchangeSGRSupply);
emit SgrTokenInitialized(msg.sender, _sgaToSGRTokenExchangeAddress, _sgaToSGRTokenExchangeSGRSupply);
}
/**
* @dev Transfer SGR to another account.
* @param _to The address of the destination account.
* @param _value The amount of SGR to be transferred.
* @return Status (true if completed successfully, false otherwise).
* @notice If the destination account is this contract, then exchange SGR for ETH.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
ISGRTokenManager sgrTokenManager = getSGRTokenManager();
if (_to == address(this)) {
uint256 amount = sgrTokenManager.exchangeSgrForEth(msg.sender, _value);
_burn(msg.sender, _value);
msg.sender.transfer(amount);
return sgrTokenManager.afterExchangeSgrForEth(msg.sender, _value, amount);
}
sgrTokenManager.uponTransfer(msg.sender, _to, _value);
bool transferResult = super.transfer(_to, _value);
return sgrTokenManager.afterTransfer(msg.sender, _to, _value, transferResult);
}
/**
* @dev Transfer SGR from one account to another.
* @param _from The address of the source account.
* @param _to The address of the destination account.
* @param _value The amount of SGR to be transferred.
* @return Status (true if completed successfully, false otherwise).
* @notice If the destination account is this contract, then the operation is illegal.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
ISGRTokenManager sgrTokenManager = getSGRTokenManager();
require(_to != address(this), "custodian-transfer of SGR into this contract is illegal");
sgrTokenManager.uponTransferFrom(msg.sender, _from, _to, _value);
bool transferFromResult = super.transferFrom(_from, _to, _value);
return sgrTokenManager.afterTransferFrom(msg.sender, _from, _to, _value, transferFromResult);
}
/**
* @dev Deposit ETH into this contract.
*/
function deposit() external payable {
getSGRTokenManager().uponDeposit(msg.sender, address(this).balance, msg.value);
}
/**
* @dev Withdraw ETH from this contract.
*/
function withdraw() external {
ISGRTokenManager sgrTokenManager = getSGRTokenManager();
uint256 priorWithdrawEthBalance = address(this).balance;
(address wallet, uint256 amount) = sgrTokenManager.uponWithdraw(msg.sender, priorWithdrawEthBalance);
wallet.transfer(amount);
sgrTokenManager.afterWithdraw(msg.sender, wallet, amount, priorWithdrawEthBalance, address(this).balance);
}
/**
* @dev Mint SGR for SGN holders.
* @param _value The amount of SGR to mint.
*/
function mintSgrForSgnHolders(uint256 _value) external only(_IMintManager_) {
ISGRTokenManager sgrTokenManager = getSGRTokenManager();
sgrTokenManager.uponMintSgrForSgnHolders(_value);
_mint(SGR_MINTED_FOR_SGN_HOLDERS, _value);
sgrTokenManager.afterMintSgrForSgnHolders(_value);
}
/**
* @dev Transfer SGR to an SGN holder.
* @param _to The address of the SGN holder.
* @param _value The amount of SGR to transfer.
*/
function transferSgrToSgnHolder(address _to, uint256 _value) external only(_SgnToSgrExchangeInitiator_) {
ISGRTokenManager sgrTokenManager = getSGRTokenManager();
sgrTokenManager.uponTransferSgrToSgnHolder(_to, _value);
_transfer(SGR_MINTED_FOR_SGN_HOLDERS, _to, _value);
sgrTokenManager.afterTransferSgrToSgnHolder(_to, _value);
}
/**
* @dev Transfer ETH to an SGR holder.
* @param _to The address of the SGR holder.
* @param _value The amount of ETH to transfer.
*/
function transferEthToSgrHolder(address _to, uint256 _value) external only(_IPaymentManager_) {
bool status = _to.send(_value);
getSGRTokenManager().postTransferEthToSgrHolder(_to, _value, status);
}
/**
* @dev Get the amount of available ETH.
* @return The amount of available ETH.
*/
function getEthBalance() external view returns (uint256) {
return address(this).balance;
}
/**
* @dev Get the address of the reserve-wallet and the deficient amount of ETH in this contract.
* @return The address of the reserve-wallet and the deficient amount of ETH in this contract.
*/
function getDepositParams() external view returns (address, uint256) {
return getSGRTokenManager().getDepositParams();
}
/**
* @dev Get the address of the reserve-wallet and the excessive amount of ETH in this contract.
* @return The address of the reserve-wallet and the excessive amount of ETH in this contract.
*/
function getWithdrawParams() external view returns (address, uint256) {
return getSGRTokenManager().getWithdrawParams();
}
} | Exchange ETH for SGR. Can be executed from externally-owned accounts as well as from other contracts./ | function exchange() external payable {
ISGRTokenManager sgrTokenManager = getSGRTokenManager();
uint256 amount = sgrTokenManager.exchangeEthForSgr(msg.sender, msg.value);
_mint(msg.sender, amount);
sgrTokenManager.afterExchangeEthForSgr(msg.sender, msg.value, amount);
}
| 208,329 |
./partial_match/1313161554/0xa200B567579a577F582d292f7A1b5C4ecce195F8/sources/Comptroller.sol | Claim all the PLY accrued by holder in the specified markets holder The address to claim PLY for auTokens The list of markets to claim PLY in/ | function claimReward(uint8 rewardType, address holder, AuToken[] memory auTokens) external {
_claimRewardForOne(rewardType, holder, auTokens, true, true);
}
| 16,936,510 |
/*
███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗
██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
█████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗
██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "./IFoxGame.sol";
import "./IFoxGameCarrot.sol";
import "./IFoxGameCrown.sol";
import "./IFoxGameNFT.sol";
contract FoxGames_v3 is IFoxGame, OwnableUpgradeable, IERC721ReceiverUpgradeable,
PausableUpgradeable, ReentrancyGuardUpgradeable {
using ECDSAUpgradeable for bytes32; // signature verification helpers
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; // iterable staked tokens
/****
* Thanks for checking out our contracts.
* If you're interested in working with us, you can find us on
* discord (https://discord.gg/foxgame). We also have a bug bounty
* program and are available at @officialfoxgame or [email protected]
***/
// Advantage score adjustments for both foxes and hunters
uint8 public constant MAX_ADVANTAGE = 8;
uint8 public constant MIN_ADVANTAGE = 5;
// Foxes take a 40% tax on all rabbiot $CARROT claimed
uint8 public constant RABBIT_CLAIM_TAX_PERCENTAGE = 40;
// Hunters have a 5% chance of stealing a fox as it unstakes
uint8 private hunterStealFoxProbabilityMod;
// Cut between hunters and foxes
uint8 private hunterTaxCutPercentage;
// Total hunter marksman scores staked
uint16 public totalMarksmanPointsStaked;
// Total fox cunning scores staked
uint16 public totalCunningPointsStaked;
// Number of Rabbit staked
uint32 public totalRabbitsStaked;
// Number of Foxes staked
uint32 public totalFoxesStaked;
// Number of Hunters staked
uint32 public totalHuntersStaked;
// The last time $CARROT was claimed
uint48 public lastClaimTimestamp;
// Rabbits must have 2 days worth of $CARROT to unstake or else it's too cold
uint48 public constant RABBIT_MINIMUM_TO_EXIT = 2 days;
// There will only ever be (roughly) 2.5 billion $CARROT earned through staking
uint128 public constant MAXIMUM_GLOBAL_CARROT = 2500000000 ether;
// amount of $CARROT earned so far
uint128 public totalCarrotEarned;
// Collected rewards before any foxes staked
uint128 public unaccountedFoxRewards;
// Collected rewards before any foxes staked
uint128 public unaccountedHunterRewards;
// Amount of $CARROT due for each cunning point staked
uint128 public carrotPerCunningPoint;
// Amount of $CARROT due for each marksman point staked
uint128 public carrotPerMarksmanPoint;
// Rabbit earn 10000 $CARROT per day
uint128 public constant RABBIT_EARNING_RATE = 115740740740740740; // 10000 ether / 1 days;
// Hunters earn 20000 $CARROT per day
uint128 public constant HUNTER_EARNING_RATE = 231481481481481470; // 20000 ether / 1 days;
// Staking state for both time-based and point-based rewards
struct TimeStake { uint16 tokenId; uint48 time; address owner; }
struct EarningStake { uint16 tokenId; uint128 earningRate; address owner; }
// Events
event TokenStaked(string kind, uint16 tokenId, address owner);
event TokenUnstaked(string kind, uint16 tokenId, address owner, uint128 earnings);
event FoxStolen(uint16 foxTokenId, address thief, address victim);
// Signature to prove membership and randomness
address private signVerifier;
// External contract reference
IFoxGameNFT private foxNFT;
IFoxGameCarrot private foxCarrot;
// Staked rabbits
mapping(uint16 => TimeStake) public rabbitStakeByToken;
// Staked foxes
mapping(uint8 => EarningStake[]) public foxStakeByCunning; // foxes grouped by cunning
mapping(uint16 => uint16) public foxHierarchy; // fox location within cunning group
// Staked hunters
mapping(uint16 => TimeStake) public hunterStakeByToken;
mapping(uint8 => EarningStake[]) public hunterStakeByMarksman; // hunter grouped by markman
mapping(uint16 => uint16) public hunterHierarchy; // hunter location within marksman group
// FoxGame membership date
mapping(address => uint48) public membershipDate;
mapping(address => uint32) public memberNumber;
event MemberJoined(address member, uint32 memberCount);
uint32 public membershipCount;
// External contract reference
IFoxGameNFT private foxNFTGen1;
// Mapping for staked tokens
mapping(address => EnumerableSetUpgradeable.UintSet) private _stakedTokens;
// Bool to store staking data
bool private _storeStaking;
// Use seed instead
uint256 private _seed;
// Reference to phase 2 utility token
IFoxGameCrown private foxCrown;
// amount of $CROWN earned so far
uint128 public totalCrownEarned;
// Cap CROWN earnings after 2.5 billion has been distributed
uint128 public constant MAXIMUM_GLOBAL_CROWN = 2500000000 ether;
// Entropy storage for future events that require randomness (claim, unstake).
// Address => OP (claim/unstake) => TokenID => BlockNumber
mapping(address => mapping(uint8 => mapping(uint16 => uint32))) private _stakeClaimBlock;
// Op keys for Entropy storage
uint8 private constant UNSTAKE_AND_CLAIM_IDX = 0;
uint8 private constant CLAIM_IDX = 1;
// Cost of a barrel in CARROT
uint256 public barrelPrice;
// Track account purchase of barrels
mapping(address => uint48) private barrelPurchaseDate;
// Barrel event purchase
event BarrelPurchase(address account, uint256 price, uint48 timestamp);
// Date when corruption begins to spread... 2 things happen:
// 1. Carrot begins to burning
// 2. Game risks go up
uint48 public corruptionStartDate;
// The last time $CROWN was claimed
uint48 public lastCrownClaimTimestamp;
// Phase 2 start date with 3 meanings:
// - the date carrot will no long accrue rewards
// - the date crown will start acruing rewards
// - the start of a 24-hour countdown for corruption
uint48 public divergenceTime;
// Corruption percent rate per second
uint128 public constant CORRUPTION_BURN_PERCENT_RATE = 1157407407407; // 10% burned per day
// Events for token claiming in phase 2
event ClaimCarrot(IFoxGameNFT.Kind, uint16 tokenId, address owner, uint128 reward, uint128 corruptedCarrot);
event CrownClaimed(string kind, uint16 tokenId, address owner, bool unstake, uint128 reward, uint128 tax, bool elevatedRisk);
// Store a bool per token to ensure we dont double claim carrot
mapping(uint16 => bool) private tokenCarrotClaimed;
// < Placeholder >
uint48 private ___;
// Amount of $CROWN due for each cunning point staked
uint128 public crownPerCunningPoint;
// Amount of $CROWN due for each marksman point staked
uint128 public crownPerMarksmanPoint;
// Indicator of which users are still grandfathered into the ground floor of
// $CROWN earnings.
mapping(uint16 => bool) private hasRecentEarningPoint;
/**
* Set the date for phase 2 launch.
* @param timestamp Timestamp
*/
function setDivergenceTime(uint48 timestamp) external onlyOwner {
divergenceTime = timestamp;
}
/**
* Init contract upgradability (only called once).
*/
function initialize() public initializer {
__Ownable_init();
__ReentrancyGuard_init();
__Pausable_init();
hunterStealFoxProbabilityMod = 20; // 100/5=20
hunterTaxCutPercentage = 30; // whole number %
// Pause staking on init
_pause();
}
/**
* Returns the corruption start date.
*/
function getCorruptionEnabled() external view returns (bool) {
return corruptionStartDate != 0 && corruptionStartDate < block.timestamp;
}
/**
* Sets the date when corruption will begin to destroy carrot.
* @param timestamp time.
*/
function setCorruptionStartTime(uint48 timestamp) external onlyOwner {
corruptionStartDate = timestamp;
}
/**
* Helper functions for validating random seeds.
*/
function getClaimSigningHash(address recipient, uint16[] calldata tokenIds, bool unstake, uint32[] calldata blocknums, uint256[] calldata seeds) public pure returns (bytes32) {
return keccak256(abi.encodePacked(recipient, tokenIds, unstake, blocknums, seeds));
}
function getMintSigningHash(address recipient, uint8 token, uint32 blocknum, uint256 seed) public pure returns (bytes32) {
return keccak256(abi.encodePacked(recipient, token, blocknum, seed));
}
function isValidMintSignature(address recipient, uint8 token, uint32 blocknum, uint256 seed, bytes memory sig) public view returns (bool) {
bytes32 message = getMintSigningHash(recipient, token, blocknum, seed).toEthSignedMessageHash();
return ECDSAUpgradeable.recover(message, sig) == signVerifier;
}
function isValidClaimSignature(address recipient, uint16[] calldata tokenIds, bool unstake, uint32[] calldata blocknums, uint256[] calldata seeds, bytes memory sig) public view returns (bool) {
bytes32 message = getClaimSigningHash(recipient, tokenIds, unstake, blocknums, seeds).toEthSignedMessageHash();
return ECDSAUpgradeable.recover(message, sig) == signVerifier;
}
/**
* Set the purchase price of Barrels.
* @param price Cost in CARROT
*/
function setBarrelPrice(uint256 price) external onlyOwner {
barrelPrice = price;
}
/**
* Allow accounts to purchase barrels using CARROT.
*/
function purchaseBarrel() external nonReentrant {
require(tx.origin == msg.sender, "eos");
require(barrelPurchaseDate[msg.sender] == 0, "one barrel per account");
barrelPurchaseDate[msg.sender] = uint48(block.timestamp);
foxCarrot.burn(msg.sender, barrelPrice);
emit BarrelPurchase(msg.sender, barrelPrice, uint48(block.timestamp));
}
/**
* Exposes user barrel purchase date.
* @param account Account to query.
*/
function ownsBarrel(address account) external view returns (bool) {
return barrelPurchaseDate[account] != 0;
}
/**
* Return the appropriate contract interface for token.
*/
function getTokenContract(uint16 tokenId) private view returns (IFoxGameNFT) {
return tokenId <= 10000 ? foxNFT : foxNFTGen1;
}
/**
* Helper method to fetch rotating entropy used to generate random seeds off-chain.
* @param tokenIds List of token IDs.
* @return entropies List of stored blocks per token.
*/
function getEntropies(address recipient, uint16[] calldata tokenIds) external view returns (uint32[2][] memory entropies) {
require(tx.origin == msg.sender, "eos");
entropies = new uint32[2][](tokenIds.length);
for (uint8 i; i < tokenIds.length; i++) {
uint16 tokenId = tokenIds[i];
entropies[i] = [
_stakeClaimBlock[recipient][UNSTAKE_AND_CLAIM_IDX][tokenId],
_stakeClaimBlock[recipient][CLAIM_IDX][tokenId]
];
}
}
/**
* Adds Rabbits, Foxes and Hunters to their respective safe homes.
* @param account the address of the staker
* @param tokenIds the IDs of the Rabbit and Foxes to stake
*/
function stakeTokens(address account, uint16[] calldata tokenIds) external nonReentrant _updateEarnings {
require((account == msg.sender && tx.origin == msg.sender) || msg.sender == address(foxNFTGen1), "not approved");
IFoxGameNFT nftContract;
uint32 blocknum = uint32(block.number);
mapping(uint16 => uint32) storage senderUnstakeBlock = _stakeClaimBlock[msg.sender][UNSTAKE_AND_CLAIM_IDX];
for (uint16 i; i < tokenIds.length; i++) {
uint16 tokenId = tokenIds[i];
// Thieves abound and leave minting gaps
if (tokenId == 0) {
continue;
}
// Set unstake entropy
senderUnstakeBlock[tokenId] = blocknum;
// Add to respective safe homes
nftContract = getTokenContract(tokenId);
IFoxGameNFT.Kind kind = _getKind(nftContract, tokenId);
if (kind == IFoxGameNFT.Kind.RABBIT) {
_addRabbitToKeep(account, tokenId);
} else if (kind == IFoxGameNFT.Kind.FOX) {
_addFoxToDen(nftContract, account, tokenId);
} else { // HUNTER
_addHunterToCabin(nftContract, account, tokenId);
}
// Transfer into safe house
if (msg.sender != address(foxNFTGen1)) { // dont do this step if its a mint + stake
require(nftContract.ownerOf(tokenId) == msg.sender, "not owner");
nftContract.transferFrom(msg.sender, address(this), tokenId);
}
}
}
/**
* Adds Rabbit to the Keep.
* @param account the address of the staker
* @param tokenId the ID of the Rabbit to add to the Barn
*/
function _addRabbitToKeep(address account, uint16 tokenId) internal {
rabbitStakeByToken[tokenId] = TimeStake({
owner: account,
tokenId: tokenId,
time: uint48(block.timestamp)
});
totalRabbitsStaked += 1;
emit TokenStaked("RABBIT", tokenId, account);
}
/**
* Add Fox to the Den.
* @param account the address of the staker
* @param tokenId the ID of the Fox
*/
function _addFoxToDen(IFoxGameNFT nftContract, address account, uint16 tokenId) internal {
uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId);
totalCunningPointsStaked += cunningIndex;
// Store fox by rating
foxHierarchy[tokenId] = uint16(foxStakeByCunning[cunningIndex].length);
// Add fox to their cunning group
foxStakeByCunning[cunningIndex].push(EarningStake({
owner: account,
tokenId: tokenId,
earningRate: crownPerCunningPoint
}));
// Phase 2 - Mark earning point as valid
hasRecentEarningPoint[tokenId] = true;
totalFoxesStaked += 1;
emit TokenStaked("FOX", tokenId, account);
}
/**
* Adds Hunter to the Cabin.
* @param account the address of the staker
* @param tokenId the ID of the Hunter
*/
function _addHunterToCabin(IFoxGameNFT nftContract, address account, uint16 tokenId) internal {
uint8 marksmanIndex = _getAdvantagePoints(nftContract, tokenId);
totalMarksmanPointsStaked += marksmanIndex;
// Store hunter by rating
hunterHierarchy[tokenId] = uint16(hunterStakeByMarksman[marksmanIndex].length);
// Add hunter to their marksman group
hunterStakeByMarksman[marksmanIndex].push(EarningStake({
owner: account,
tokenId: tokenId,
earningRate: crownPerMarksmanPoint
}));
hunterStakeByToken[tokenId] = TimeStake({
owner: account,
tokenId: tokenId,
time: uint48(block.timestamp)
});
// Phase 2 - Mark earning point as valid
hasRecentEarningPoint[tokenId] = true;
totalHuntersStaked += 1;
emit TokenStaked("HUNTER", tokenId, account);
}
// NB: Param struct is a workaround for too many variables error
struct Param {
IFoxGameNFT nftContract;
uint16 tokenId;
bool unstake;
uint256 seed;
}
/**
* Realize $CARROT earnings and optionally unstake tokens.
* @param tokenIds the IDs of the tokens to claim earnings from
* @param unstake whether or not to unstake ALL of the tokens listed in tokenIds
* @param blocknums list of blocks each token previously was staked or claimed.
* @param seeds random (off-chain) seeds provided for one-time use.
* @param sig signature verification.
*/
function claimRewardsAndUnstake(bool unstake, uint16[] calldata tokenIds, uint32[] calldata blocknums, uint256[] calldata seeds, bytes calldata sig) external nonReentrant _updateEarnings {
require(tx.origin == msg.sender, "eos");
require(isValidClaimSignature(msg.sender, tokenIds, unstake, blocknums, seeds, sig), "invalid signature");
require(tokenIds.length == blocknums.length && blocknums.length == seeds.length, "seed mismatch");
// Risk factors
bool elevatedRisk =
(corruptionStartDate != 0 && corruptionStartDate < block.timestamp) && // corrupted
(barrelPurchaseDate[msg.sender] == 0); // does not have barrel
// Calculate rewards for each token
uint128 reward;
mapping(uint16 => uint32) storage senderBlocks = _stakeClaimBlock[msg.sender][unstake ? UNSTAKE_AND_CLAIM_IDX : CLAIM_IDX];
Param memory params;
for (uint8 i; i < tokenIds.length; i++) {
uint16 tokenId = tokenIds[i];
// Confirm previous block matches seed generation
require(senderBlocks[tokenId] == blocknums[i], "seed not match");
// Set new entropy for next claim (dont bother if unstaking)
if (!unstake) {
senderBlocks[tokenId] = uint32(block.number);
}
// NB: Param struct is a workaround for too many variables
params.nftContract = getTokenContract(tokenId);
params.tokenId = tokenId;
params.unstake = unstake;
params.seed = seeds[i];
IFoxGameNFT.Kind kind = _getKind(params.nftContract, params.tokenId);
if (kind == IFoxGameNFT.Kind.RABBIT) {
reward += _claimRabbitsFromKeep(params.nftContract, params.tokenId, params.unstake, params.seed, elevatedRisk);
} else if (kind == IFoxGameNFT.Kind.FOX) {
reward += _claimFoxFromDen(params.nftContract, params.tokenId, params.unstake, params.seed, elevatedRisk);
} else { // HUNTER
reward += _claimHunterFromCabin(params.nftContract, params.tokenId, params.unstake);
}
}
// Disburse rewards
if (reward != 0) {
foxCrown.mint(msg.sender, reward);
}
}
/**
* realize $CARROT earnings for a single Rabbit and optionally unstake it
* if not unstaking, pay a 20% tax to the staked foxes
* if unstaking, there is a 50% chance all $CARROT is stolen
* @param nftContract Contract belonging to the token
* @param tokenId the ID of the Rabbit to claim earnings from
* @param unstake whether or not to unstake the Rabbit
* @param seed account seed
* @param elevatedRisk true if the user is facing higher risk of losing their token
* @return reward - the amount of $CARROT earned
*/
function _claimRabbitsFromKeep(IFoxGameNFT nftContract, uint16 tokenId, bool unstake, uint256 seed, bool elevatedRisk) internal returns (uint128 reward) {
TimeStake storage stake = rabbitStakeByToken[tokenId];
require(stake.owner == msg.sender, "not owner");
uint48 time = uint48(block.timestamp);
uint48 stakeStart = stake.time < divergenceTime ? divergenceTime : stake.time; // phase 2 reset
require(!(unstake && time - stakeStart < RABBIT_MINIMUM_TO_EXIT), "needs 2 days of crown");
// $CROWN time-based rewards
if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) {
reward = (time - stakeStart) * RABBIT_EARNING_RATE;
} else if (stakeStart <= lastCrownClaimTimestamp) {
// stop earning additional $CROWN if it's all been earned
reward = (lastCrownClaimTimestamp - stakeStart) * RABBIT_EARNING_RATE;
}
// Update reward based on game rules
uint128 tax;
if (unstake) {
// Chance of all $CROWN stolen (normal=50% vs corrupted=75%)
if (((seed >> 245) % 100) < (elevatedRisk ? 75 : 50)) {
_payTaxToPredators(reward, true);
tax = reward;
reward = 0;
}
delete rabbitStakeByToken[tokenId];
totalRabbitsStaked -= 1;
// send back Rabbit
nftContract.safeTransferFrom(address(this), msg.sender, tokenId, "");
} else {
// Pay foxes their tax
tax = reward * RABBIT_CLAIM_TAX_PERCENTAGE / 100;
_payTaxToPredators(tax, false);
reward = reward * (100 - RABBIT_CLAIM_TAX_PERCENTAGE) / 100;
// Update last earned time
rabbitStakeByToken[tokenId] = TimeStake({
owner: msg.sender,
tokenId: tokenId,
time: time
});
}
emit CrownClaimed("RABBIT", tokenId, stake.owner, unstake, reward, tax, elevatedRisk);
}
/**
* realize $CARROT earnings for a single Fox and optionally unstake it
* foxes earn $CARROT proportional to their Alpha rank
* @param nftContract Contract belonging to the token
* @param tokenId the ID of the Fox to claim earnings from
* @param unstake whether or not to unstake the Fox
* @param seed account seed
* @param elevatedRisk true if the user is facing higher risk of losing their token
* @return reward - the amount of $CARROT earned
*/
function _claimFoxFromDen(IFoxGameNFT nftContract, uint16 tokenId, bool unstake, uint256 seed, bool elevatedRisk) internal returns (uint128 reward) {
require(nftContract.ownerOf(tokenId) == address(this), "not staked");
uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId);
EarningStake storage stake = foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]];
require(stake.owner == msg.sender, "not owner");
// Calculate advantage-based rewards
uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? stake.earningRate : 0; // phase 2 reset
if (crownPerCunningPoint > migratedEarningPoint) {
reward = (MAX_ADVANTAGE - cunningIndex + MIN_ADVANTAGE) * (crownPerCunningPoint - migratedEarningPoint);
}
if (unstake) {
totalCunningPointsStaked -= cunningIndex; // Remove Alpha from total staked
EarningStake storage lastStake = foxStakeByCunning[cunningIndex][foxStakeByCunning[cunningIndex].length - 1];
foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]] = lastStake; // Shuffle last Fox to current position
foxHierarchy[lastStake.tokenId] = foxHierarchy[tokenId];
foxStakeByCunning[cunningIndex].pop(); // Remove duplicate
delete foxHierarchy[tokenId]; // Delete old mapping
totalFoxesStaked -= 1;
// Determine if Fox should be stolen by hunter (normal=5% vs corrupted=20%)
address recipient = msg.sender;
if (((seed >> 245) % (elevatedRisk ? 5 : hunterStealFoxProbabilityMod)) == 0) {
recipient = _randomHunterOwner(seed);
if (recipient == address(0x0)) {
recipient = msg.sender;
} else if (recipient != msg.sender) {
emit FoxStolen(tokenId, recipient, msg.sender);
}
}
nftContract.safeTransferFrom(address(this), recipient, tokenId, "");
} else {
// Update earning point
foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]] = EarningStake({
owner: msg.sender,
tokenId: tokenId,
earningRate: crownPerCunningPoint
});
hasRecentEarningPoint[tokenId] = true;
}
emit CrownClaimed("FOX", tokenId, stake.owner, unstake, reward, 0, elevatedRisk);
}
/**
* realize $CARROT earnings for a single Fox and optionally unstake it
* foxes earn $CARROT proportional to their Alpha rank
* @param nftContract Contract belonging to the token
* @param tokenId the ID of the Fox to claim earnings from
* @param unstake whether or not to unstake the Fox
* @return reward - the amount of $CARROT earned
*/
function _claimHunterFromCabin(IFoxGameNFT nftContract, uint16 tokenId, bool unstake) internal returns (uint128 reward) {
require(foxNFTGen1.ownerOf(tokenId) == address(this), "not staked");
uint8 marksmanIndex = _getAdvantagePoints(nftContract, tokenId);
EarningStake storage earningStake = hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]];
require(earningStake.owner == msg.sender, "not owner");
uint48 time = uint48(block.timestamp);
// Calculate advantage-based rewards
uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? earningStake.earningRate : 0; // phase 2 reset
if (crownPerMarksmanPoint > migratedEarningPoint) {
reward = (MAX_ADVANTAGE - marksmanIndex + MIN_ADVANTAGE) * (crownPerMarksmanPoint - migratedEarningPoint);
}
if (unstake) {
totalMarksmanPointsStaked -= marksmanIndex; // Remove Alpha from total staked
EarningStake storage lastStake = hunterStakeByMarksman[marksmanIndex][hunterStakeByMarksman[marksmanIndex].length - 1];
hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]] = lastStake; // Shuffle last Fox to current position
hunterHierarchy[lastStake.tokenId] = hunterHierarchy[tokenId];
hunterStakeByMarksman[marksmanIndex].pop(); // Remove duplicate
delete hunterHierarchy[tokenId]; // Delete old mapping
} else {
// Update earning point
hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]] = EarningStake({
owner: msg.sender,
tokenId: tokenId,
earningRate: crownPerMarksmanPoint
});
hasRecentEarningPoint[tokenId] = true;
}
// Calcuate time-based rewards
TimeStake storage timeStake = hunterStakeByToken[tokenId];
require(timeStake.owner == msg.sender, "not owner");
uint48 stakeStart = timeStake.time < divergenceTime ? divergenceTime : timeStake.time; // phase 2 reset
if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) {
reward += (time - stakeStart) * HUNTER_EARNING_RATE;
} else if (stakeStart <= lastCrownClaimTimestamp) {
// stop earning additional $CARROT if it's all been earned
reward += (lastCrownClaimTimestamp - stakeStart) * HUNTER_EARNING_RATE;
}
if (unstake) {
delete hunterStakeByToken[tokenId];
totalHuntersStaked -= 1;
// Unstake to owner
foxNFTGen1.safeTransferFrom(address(this), msg.sender, tokenId, "");
} else {
// Update last earned time
hunterStakeByToken[tokenId] = TimeStake({
owner: msg.sender,
tokenId: tokenId,
time: time
});
}
emit CrownClaimed("HUNTER", tokenId, earningStake.owner, unstake, reward, 0, false);
}
// Struct to abstract away calculation of rewards from claiming rewards
struct TokenReward {
address owner;
IFoxGameNFT.Kind kind;
uint128 reward;
uint128 corruptedCarrot;
}
/**
* Realize $CARROT earnings. There's no risk nor tax involed other than corruption.
* @param tokenId the token ID
* @param time current time
* @return claim reward information
*/
function getCarrotReward(uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) {
IFoxGameNFT nftContract = getTokenContract(tokenId);
claim.kind = _getKind(nftContract, tokenId);
if (claim.kind == IFoxGameNFT.Kind.RABBIT) {
claim = _getCarrotForRabbit(tokenId, time);
} else if (claim.kind == IFoxGameNFT.Kind.FOX) {
claim = _getCarrotForFox(nftContract, tokenId, time);
} else { // HUNTER
claim = _getCarrotForHunter(nftContract, tokenId, time);
}
}
/**
* Calculate carrot rewards for the given tokens.
* @param tokenIds list of tokens
* @return claims list of reward objects
*/
function getCarrotRewards(uint16[] calldata tokenIds) external view returns (TokenReward[] memory claims) {
uint48 time = uint48(block.timestamp);
claims = new TokenReward[](tokenIds.length);
for (uint8 i; i < tokenIds.length; i++) {
if (!tokenCarrotClaimed[tokenIds[i]]) {
claims[i] = getCarrotReward(tokenIds[i], time);
}
}
}
/**
* Realize $CARROT earnings. There's no risk nor tax involed other than corruption.
* @param tokenIds the IDs of the tokens to claim earnings from
*/
function claimCarrotRewards(uint16[] calldata tokenIds) external {
require(tx.origin == msg.sender, "eos");
uint128 reward;
TokenReward memory claim;
uint48 time = uint48(block.timestamp);
for (uint8 i; i < tokenIds.length; i++) {
if (!tokenCarrotClaimed[tokenIds[i]]) {
claim = getCarrotReward(tokenIds[i], time);
require(claim.owner == msg.sender, "not owner");
reward += claim.reward;
emit ClaimCarrot(claim.kind, tokenIds[i], claim.owner, claim.reward, claim.corruptedCarrot);
tokenCarrotClaimed[tokenIds[i]] = true;
}
}
// Disburse rewards
if (reward != 0) {
foxCarrot.mint(msg.sender, reward);
}
}
/**
* Calculate the carrot accumulated per token.
* @param time current time
*/
function calculateCorruptedCarrot(address account, uint128 reward, uint48 time) private view returns (uint128 corruptedCarrot) {
// If user has rewards and corruption has started
if (reward > 0 && corruptionStartDate != 0 && time > corruptionStartDate) {
// Calulate time that corruption was in effect
uint48 barrelTime = barrelPurchaseDate[account];
uint128 unsafeElapsed = (barrelTime == 0 ? time - corruptionStartDate // never bought barrel
: barrelTime > corruptionStartDate ? barrelTime - corruptionStartDate // bought after corruption
: 0 // bought before corruption
);
// Subtract from reward
if (unsafeElapsed > 0) {
corruptedCarrot = uint128((reward * unsafeElapsed * uint256(CORRUPTION_BURN_PERCENT_RATE)) / 1000000000000000000 /* 1eth */);
}
}
}
/**
* Realize $CARROT earnings for a single Rabbit
* @param tokenId the ID of the Rabbit to claim earnings from
* @param time current time
* @return claim carrot claim object
*/
function _getCarrotForRabbit(uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) {
// Carrot time-based rewards
uint128 reward;
TimeStake storage stake = rabbitStakeByToken[tokenId];
if (divergenceTime == 0 || time < divergenceTime) { // divergence has't yet started
reward = (time - stake.time) * RABBIT_EARNING_RATE;
} else if (stake.time < divergenceTime) { // last moment to accrue carrot
reward = (divergenceTime - stake.time) * RABBIT_EARNING_RATE;
}
claim.corruptedCarrot = calculateCorruptedCarrot(msg.sender, reward, time);
claim.reward = reward - claim.corruptedCarrot;
claim.owner = stake.owner;
}
/**
* Realize $CARROT earnings for a single Fox
* @param nftContract Contract belonging to the token
* @param tokenId the ID of the Fox to claim earnings from
* @param time current time
* @return claim carrot claim object
*/
function _getCarrotForFox(IFoxGameNFT nftContract, uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) {
uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId);
EarningStake storage stake = foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]];
// Calculate advantage-based rewards
uint128 reward;
if (!hasRecentEarningPoint[tokenId] && carrotPerCunningPoint > stake.earningRate) {
reward = (MAX_ADVANTAGE - cunningIndex + MIN_ADVANTAGE) * (carrotPerCunningPoint - stake.earningRate);
}
// Remove corrupted carrot
claim.corruptedCarrot = calculateCorruptedCarrot(msg.sender, reward, time);
claim.reward = reward - claim.corruptedCarrot;
claim.owner = stake.owner;
}
/**
* Realize $CARROT earnings for a single hunter
* @param nftContract Contract belonging to the token
* @param tokenId the ID of the Fox to claim earnings from
* @param time current time
* @return claim carrot claim object
*/
function _getCarrotForHunter(IFoxGameNFT nftContract, uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) {
require(foxNFTGen1.ownerOf(tokenId) == address(this), "not staked");
uint8 marksman = _getAdvantagePoints(nftContract, tokenId);
EarningStake storage earningStake = hunterStakeByMarksman[marksman][hunterHierarchy[tokenId]];
require(earningStake.owner == msg.sender, "not owner");
// Calculate advantage-based rewards
uint128 reward;
if (!hasRecentEarningPoint[tokenId] && carrotPerMarksmanPoint > earningStake.earningRate) {
reward = marksman * (carrotPerMarksmanPoint - earningStake.earningRate);
}
// Carrot time-based rewards
TimeStake storage timeStake = hunterStakeByToken[tokenId];
if (divergenceTime == 0 || time < divergenceTime) {
reward += (time - timeStake.time) * HUNTER_EARNING_RATE;
} else if (timeStake.time < divergenceTime) {
reward += (divergenceTime - timeStake.time) * HUNTER_EARNING_RATE;
}
// Remove corrupted carrot
claim.corruptedCarrot = calculateCorruptedCarrot(msg.sender, reward, time);
claim.reward = reward - claim.corruptedCarrot;
claim.owner = earningStake.owner;
}
/**
* Add $CARROT claimable pots for hunters and foxes
* @param amount $CARROT to add to the pot
* @param includeHunters true if hunters take a cut of the spoils
*/
function _payTaxToPredators(uint128 amount, bool includeHunters) internal {
uint128 amountDueFoxes = amount;
// Hunters take their cut first
if (includeHunters) {
uint128 amountDueHunters = amount * hunterTaxCutPercentage / 100;
amountDueFoxes -= amountDueHunters;
// Update hunter pools
if (totalMarksmanPointsStaked == 0) {
unaccountedHunterRewards += amountDueHunters;
} else {
crownPerMarksmanPoint += (amountDueHunters + unaccountedHunterRewards) / totalMarksmanPointsStaked;
unaccountedHunterRewards = 0;
}
}
// Update fox pools
if (totalCunningPointsStaked == 0) {
unaccountedFoxRewards += amountDueFoxes;
} else {
// makes sure to include any unaccounted $CARROT
crownPerCunningPoint += (amountDueFoxes + unaccountedFoxRewards) / totalCunningPointsStaked;
unaccountedFoxRewards = 0;
}
}
/**
* Tracks $CARROT earnings to ensure it stops once 2.4 billion is eclipsed
*/
modifier _updateEarnings() {
uint48 time = uint48(block.timestamp);
// CROWN - Capped by supply
if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) {
uint48 elapsed = time - lastCrownClaimTimestamp;
totalCrownEarned +=
(elapsed * totalRabbitsStaked * RABBIT_EARNING_RATE) +
(elapsed * totalHuntersStaked * HUNTER_EARNING_RATE);
lastCrownClaimTimestamp = time;
}
_;
}
/**
* Get token kind (rabbit, fox, hunter)
* @param tokenId the ID of the token to check
* @return kind
*/
function _getKind(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (IFoxGameNFT.Kind) {
return nftContract.getTraits(tokenId).kind;
}
/**
* gets the alpha score for a Fox
* @param tokenId the ID of the Fox to get the alpha score for
* @return the alpha score of the Fox (5-8)
*/
function _getAdvantagePoints(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (uint8) {
return MAX_ADVANTAGE - nftContract.getTraits(tokenId).advantage; // alpha index is 0-3
}
/**
* chooses a random Fox thief when a newly minted token is stolen
* @param seed a random value to choose a Fox from
* @return the owner of the randomly selected Fox thief
*/
function randomFoxOwner(uint256 seed) external view returns (address) {
if (totalCunningPointsStaked == 0) {
return address(0x0); // use 0x0 to return to msg.sender
}
// choose a value from 0 to total alpha staked
uint256 bucket = (seed & 0xFFFFFFFF) % totalCunningPointsStaked;
uint256 cumulative;
seed >>= 32;
// loop through each cunning bucket of Foxes
for (uint8 i = MAX_ADVANTAGE - 3; i <= MAX_ADVANTAGE; i++) {
cumulative += foxStakeByCunning[i].length * i;
// if the value is not inside of that bucket, keep going
if (bucket >= cumulative) continue;
// get the address of a random Fox with that alpha score
return foxStakeByCunning[i][seed % foxStakeByCunning[i].length].owner;
}
return address(0x0);
}
/**
* Chooses a random Hunter to steal a fox.
* @param seed a random value to choose a Hunter from
* @return the owner of the randomly selected Hunter thief
*/
function _randomHunterOwner(uint256 seed) internal view returns (address) {
if (totalMarksmanPointsStaked == 0) {
return address(0x0); // use 0x0 to return to msg.sender
}
// choose a value from 0 to total alpha staked
uint256 bucket = (seed & 0xFFFFFFFF) % totalMarksmanPointsStaked;
uint256 cumulative;
seed >>= 32;
// loop through each cunning bucket of Foxes
for (uint8 i = MAX_ADVANTAGE - 3; i <= MAX_ADVANTAGE; i++) {
cumulative += hunterStakeByMarksman[i].length * i;
// if the value is not inside of that bucket, keep going
if (bucket >= cumulative) continue;
// get the address of a random Fox with that alpha score
return hunterStakeByMarksman[i][seed % hunterStakeByMarksman[i].length].owner;
}
return address(0x0);
}
/**
* Realize $CROWN earnings
* @param tokenIds the IDs of the tokens to claim earnings from
*/
function calculateRewards(uint16[] calldata tokenIds) external view returns (TokenReward[] memory tokenRewards) {
require(tx.origin == msg.sender, "eos only");
IFoxGameNFT.Kind kind;
IFoxGameNFT nftContract;
tokenRewards = new TokenReward[](tokenIds.length);
uint48 time = uint48(block.timestamp);
for (uint8 i = 0; i < tokenIds.length; i++) {
nftContract = getTokenContract(tokenIds[i]);
kind = _getKind(nftContract, tokenIds[i]);
if (kind == IFoxGameNFT.Kind.RABBIT) {
tokenRewards[i] = _calculateRabbitReward(tokenIds[i], time);
} else if (kind == IFoxGameNFT.Kind.FOX) {
tokenRewards[i] = _calculateFoxReward(nftContract, tokenIds[i]);
} else { // HUNTER
tokenRewards[i] = _calculateHunterReward(nftContract, tokenIds[i], time);
}
}
}
/**
* Calculate rabbit reward.
* @param tokenId the ID of the Rabbit to claim earnings from
* @param time currnet block time
* @return tokenReward token reward response
*/
function _calculateRabbitReward(uint16 tokenId, uint48 time) internal view returns (TokenReward memory tokenReward) {
TimeStake storage stake = rabbitStakeByToken[tokenId];
uint48 stakeStart = stake.time < divergenceTime ? divergenceTime : stake.time; // phase 2 reset
// Calcuate time-based rewards
uint128 reward;
if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) {
reward = (time - stakeStart) * RABBIT_EARNING_RATE;
} else if (stakeStart <= lastCrownClaimTimestamp) {
// stop earning additional $CROWN if it's all been earned
reward = (lastCrownClaimTimestamp - stakeStart) * RABBIT_EARNING_RATE;
}
// Compose reward object
tokenReward.owner = stake.owner;
tokenReward.reward = reward * (100 - RABBIT_CLAIM_TAX_PERCENTAGE) / 100;
}
/**
* Calculate fox reward.
* @param nftContract Contract belonging to the token
* @param tokenId the ID of the Fox to claim earnings from
* @return tokenReward token reward response
*/
function _calculateFoxReward(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (TokenReward memory tokenReward) {
uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId);
EarningStake storage stake = foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]];
// Calculate advantage-based rewards
uint128 reward;
uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? stake.earningRate : 0; // phase 2 reset
if (crownPerCunningPoint > migratedEarningPoint) {
reward = (MAX_ADVANTAGE - cunningIndex + MIN_ADVANTAGE) * (crownPerCunningPoint - migratedEarningPoint);
}
// Compose reward object
tokenReward.owner = stake.owner;
tokenReward.reward = reward;
}
/**
* Calculate hunter reward.
* @param nftContract Contract belonging to the token
* @param tokenId the ID of the Fox to claim earnings from
* @param time currnet block time
* @return tokenReward token reward response
*/
function _calculateHunterReward(IFoxGameNFT nftContract, uint16 tokenId, uint48 time) internal view returns (TokenReward memory tokenReward) {
uint8 marksmanIndex = _getAdvantagePoints(nftContract, tokenId);
EarningStake storage earningStake = hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]];
// Calculate advantage-based rewards
uint128 reward;
uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? earningStake.earningRate : 0; // phase 2 reset
if (crownPerMarksmanPoint > migratedEarningPoint) {
reward = (MAX_ADVANTAGE - marksmanIndex + MIN_ADVANTAGE) * (crownPerMarksmanPoint - migratedEarningPoint);
}
// Calcuate time-based rewards
TimeStake storage timeStake = hunterStakeByToken[tokenId];
uint48 stakeStart = timeStake.time < divergenceTime ? divergenceTime : timeStake.time; // phase 2 reset
require(timeStake.owner == msg.sender, "not owner");
if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) {
reward += (time - stakeStart) * HUNTER_EARNING_RATE;
} else if (stakeStart <= lastCrownClaimTimestamp) {
reward += (lastCrownClaimTimestamp - stakeStart) * HUNTER_EARNING_RATE;
}
// Compose reward object
tokenReward.owner = earningStake.owner;
tokenReward.reward = reward;
}
/**
* Interface support to allow player staking.
*/
function onERC721Received(address, address from, uint256, bytes calldata) external pure override returns (bytes4) {
require(from == address(0x0));
return IERC721ReceiverUpgradeable.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed 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
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
pragma solidity ^0.8.10;
interface IFoxGame {
function stakeTokens(address, uint16[] calldata) external;
function randomFoxOwner(uint256) external view returns (address);
function isValidMintSignature(address, uint8, uint32, uint256, bytes memory) external view returns (bool);
function ownsBarrel(address) external view returns (bool);
function getCorruptionEnabled() external view returns (bool);
}
/*
███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗
██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
█████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗
██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IFoxGameCarrot {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
}
/*
███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗
██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
█████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗
██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IFoxGameCrown {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
}
/*
███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗
██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
█████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗
██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝
██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗
╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IFoxGameNFT {
enum Kind { RABBIT, FOX, HUNTER }
enum Coin { CARROT, CROWN }
struct Traits { Kind kind; uint8 advantage; uint8[7] traits; }
function getMaxGEN0Players() external pure returns (uint16);
function getTraits(uint16) external view returns (Traits memory);
function ownerOf(uint256) external view returns (address owner);
function transferFrom(address, address, uint256) external;
function safeTransferFrom(address, address, uint256, bytes memory) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
} | gets the alpha score for a Fox tokenId the ID of the Fox to get the alpha score for return the alpha score of the Fox (5-8)/ | function _getAdvantagePoints(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (uint8) {
}
| 14,423,443 |
./partial_match/1/0xfFdf17652cca46eB98A214cb3E413C8661241E49/sources/CryptoBeastiesToken.sol | Internal function to add a token ID to the list owned by a given address _to address representing the new owner of the token ID _tokenId uint256 ID of the token to be added/ index is +1 to avoid Solidity's zero default mapping value | function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
ownedTokens[_to].push(_tokenId);
ownedTokenIndexes[_tokenId] = ownedTokens[_to].length;
}
| 3,926,482 |
pragma solidity ^0.5.0;
import "./SafeMath.sol";
import "./Valset.sol";
import "./CosmosBridge.sol";
contract Oracle {
using SafeMath for uint256;
/*
* @dev: Public variable declarations
*/
CosmosBridge public cosmosBridge;
Valset public valset;
address public operator;
uint256 public consensusThreshold; // e.g. 75 = 75%
// Tracks the number of OracleClaims made on an individual BridgeClaim
mapping(uint256 => address[]) public oracleClaimValidators;
mapping(uint256 => mapping(address => bool)) public hasMadeClaim;
/*
* @dev: Event declarations
*/
event LogNewOracleClaim(
uint256 _prophecyID,
bytes32 _message,
address _validatorAddress,
bytes _signature
);
event LogProphecyProcessed(
uint256 _prophecyID,
uint256 _prophecyPowerCurrent,
uint256 _prophecyPowerThreshold,
address _submitter
);
/*
* @dev: Modifier to restrict access to the operator.
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be the operator.");
_;
}
/*
* @dev: Modifier to restrict access to current ValSet validators
*/
modifier onlyValidator() {
require(
valset.isActiveValidator(msg.sender),
"Must be an active validator"
);
_;
}
/*
* @dev: Modifier to restrict access to current ValSet validators
*/
modifier isPending(uint256 _prophecyID) {
require(
cosmosBridge.isProphecyClaimActive(_prophecyID) == true,
"The prophecy must be pending for this operation"
);
_;
}
/*
* @dev: Constructor
*/
constructor(
address _operator,
address _valset,
address _cosmosBridge,
uint256 _consensusThreshold
) public {
require(
_consensusThreshold > 0,
"Consensus threshold must be positive."
);
operator = _operator;
cosmosBridge = CosmosBridge(_cosmosBridge);
valset = Valset(_valset);
consensusThreshold = _consensusThreshold;
}
/*
* @dev: newOracleClaim
* Allows validators to make new OracleClaims on an existing Prophecy
*/
function newOracleClaim(
uint256 _prophecyID,
bytes32 _message,
bytes memory _signature
) public onlyValidator isPending(_prophecyID) {
address validatorAddress = msg.sender;
// Validate the msg.sender's signature
require(
validatorAddress == valset.recover(_message, _signature),
"Invalid message signature."
);
// Confirm that this address has not already made an oracle claim on this prophecy
require(
!hasMadeClaim[_prophecyID][validatorAddress],
"Cannot make duplicate oracle claims from the same address."
);
hasMadeClaim[_prophecyID][validatorAddress] = true;
oracleClaimValidators[_prophecyID].push(validatorAddress);
emit LogNewOracleClaim(
_prophecyID,
_message,
validatorAddress,
_signature
);
// Process the prophecy
(
bool valid,
uint256 prophecyPowerCurrent,
uint256 prophecyPowerThreshold
) = getProphecyThreshold(_prophecyID);
if (valid) {
completeProphecy(_prophecyID);
emit LogProphecyProcessed(
_prophecyID,
prophecyPowerCurrent,
prophecyPowerThreshold,
msg.sender
);
}
}
/*
* @dev: processBridgeProphecy
* Pubically available method which attempts to process a bridge prophecy
*/
function processBridgeProphecy(uint256 _prophecyID)
public
isPending(_prophecyID)
{
// Process the prophecy
(
bool valid,
uint256 prophecyPowerCurrent,
uint256 prophecyPowerThreshold
) = getProphecyThreshold(_prophecyID);
require(
valid,
"The cumulative power of signatory validators does not meet the threshold"
);
// Update the BridgeClaim's status
completeProphecy(_prophecyID);
emit LogProphecyProcessed(
_prophecyID,
prophecyPowerCurrent,
prophecyPowerThreshold,
msg.sender
);
}
/*
* @dev: checkBridgeProphecy
* Operator accessor method which checks if a prophecy has passed
* the validity threshold, without actually completing the prophecy.
*/
function checkBridgeProphecy(uint256 _prophecyID)
public
view
onlyOperator
isPending(_prophecyID)
returns (bool, uint256, uint256)
{
require(
cosmosBridge.isProphecyClaimActive(_prophecyID) == true,
"Can only check active prophecies"
);
return getProphecyThreshold(_prophecyID);
}
/*
* @dev: processProphecy
* Calculates the status of a prophecy. The claim is considered valid if the
* combined active signatory validator powers pass the consensus threshold.
* The threshold is x% of Total power, where x is the consensusThreshold param.
*/
function getProphecyThreshold(uint256 _prophecyID)
internal
view
returns (bool, uint256, uint256)
{
uint256 signedPower = 0;
uint256 totalPower = valset.totalPower();
// Iterate over the signatory addresses
for (
uint256 i = 0;
i < oracleClaimValidators[_prophecyID].length;
i = i.add(1)
) {
address signer = oracleClaimValidators[_prophecyID][i];
// Only add the power of active validators
if (valset.isActiveValidator(signer)) {
signedPower = signedPower.add(valset.getValidatorPower(signer));
}
}
// Prophecy must reach total signed power % threshold in order to pass consensus
uint256 prophecyPowerThreshold = totalPower.mul(consensusThreshold);
// consensusThreshold is a decimal multiplied by 100, so signedPower must also be multiplied by 100
uint256 prophecyPowerCurrent = signedPower.mul(100);
bool hasReachedThreshold = prophecyPowerCurrent >=
prophecyPowerThreshold;
return (
hasReachedThreshold,
prophecyPowerCurrent,
prophecyPowerThreshold
);
}
/*
* @dev: completeProphecy
* Completes a prophecy by completing the corresponding BridgeClaim
* on the CosmosBridge.
*/
function completeProphecy(uint256 _prophecyID) internal {
cosmosBridge.completeProphecyClaim(_prophecyID);
}
}
| : checkBridgeProphecy Operator accessor method which checks if a prophecy has passed the validity threshold, without actually completing the prophecy./ | function checkBridgeProphecy(uint256 _prophecyID)
public
view
onlyOperator
isPending(_prophecyID)
returns (bool, uint256, uint256)
{
require(
cosmosBridge.isProphecyClaimActive(_prophecyID) == true,
"Can only check active prophecies"
);
return getProphecyThreshold(_prophecyID);
}
| 5,498,029 |
./partial_match/1/0xdac4585B741E5b6625CEc460D2A255fB3FBE0D47/sources/contracts/lib/pools/FusePoolController.sol | Approves tokens to Fuse without spending gas on every deposit. cErc20Contract The CErc20 contract address of the token. erc20Contract The ERC20 contract address of the token. amount Amount of the specified token to approve to Fuse./ | function approve(address cErc20Contract, address erc20Contract, uint256 amount) external {
IERC20 token = IERC20(erc20Contract);
uint256 allowance = token.allowance(address(this), cErc20Contract);
if (allowance == amount) return;
if (amount > 0 && allowance > 0) token.safeApprove(cErc20Contract, 0);
token.safeApprove(cErc20Contract, amount);
return;
}
| 3,925,309 |
./full_match/1/0xD4515f0A85DcA839C8D639cf55d553Ce0FA4bBe8/sources/contracts/CoverMarketMakers.sol | Mint CLAIM / NOCLAIM , deposit CLAIM and NOCLAIM in balancer and return BPTs | function marketMakerDeposit(
IProtocol _protocol,
IBPool _claimPool,
IBPool _noclaimPool,
uint48 _expiration,
uint256 _mintAmount,
uint256 _collateraLpAmount,
address _collateral
) external {
IERC20(_collateral).safeTransferFrom(msg.sender, address(this), (_collateraLpAmount.add(_mintAmount)));
if (IERC20(_collateral).allowance(address(this), address(_protocol)) < (_collateraLpAmount.add(_mintAmount))) {
IERC20(_collateral).approve(address(_protocol), uint256(-1));
}
address noclaimTokenAddr = factory.getCovTokenAddress(_protocol.name(), _expiration, _collateral, _protocol.claimNonce(), false);
address claimTokenAddr = factory.getCovTokenAddress(_protocol.name(), _expiration, _collateral, _protocol.claimNonce(), true);
_protocol.addCover(_collateral, _expiration, _mintAmount);
_provideLiquidity(_claimPool, claimTokenAddr, _mintAmount, _collateral, _collateraLpAmount);
_provideLiquidity(_noclaimPool, noclaimTokenAddr, _mintAmount, _collateral, _collateraLpAmount);
uint256 remainCollateral = IERC20(_collateral).balanceOf(address(this));
if (remainCollateral > 0) {
IERC20(_collateral).safeTransfer(msg.sender, remainCollateral);
}
}
| 5,015,756 |
./partial_match/56/0xe8d312E41F8f5aBCd68911De96EDcA697E70FDB6/sources/Vault.sol | Reduce BaseToken reserve, effectively giving them to the depositors. value The number of BaseToken reserve to reduce. | function reduceReserve(uint256 value) external onlyOwner {
reservePool = reservePool.sub(value);
}
| 11,316,430 |
./full_match/43113/0xd1F3A2e663E1895F9Ef301E4f08093cb0f56d9ed/sources/LendingPool_flat.sol | mint it 1:1 to the amount put in get fee set first deposit to false | function deposit(uint256 _amount) external {
require(_amount > 0, "Can't deposit 0");
uint256 totalAmount = _amount * 10 ** 18;
_mint(msg.sender, totalAmount);
uint256 isFirstDeposit = balances[msg.sender].isFirstDeposit;
if (isFirstDeposit == 0) {
balances[msg.sender].isFirstDeposit = 1;
}
IERC20(poolToken).safeTransferFrom(msg.sender, address(this), totalAmount);
emit Deposit(msg.sender, totalAmount);
}
| 13,158,659 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {IKODAV3Minter} from "../core/IKODAV3Minter.sol";
import {IKODAV3PrimarySaleMarketplace} from "../marketplace/KODAV3PrimaryMarketplace.sol";
import {ICollabRoyaltiesRegistry} from "../collab/ICollabRoyaltiesRegistry.sol";
import {IKOAccessControlsLookup} from "../access/IKOAccessControlsLookup.sol";
contract MintingFactory is Context {
event EditionMintedAndListed(uint256 indexed _editionId, SaleType _saleType);
event MintingFactoryCreated();
event AdminMintingPeriodChanged(uint256 _mintingPeriod);
event AdminMaxMintsInPeriodChanged(uint256 _maxMintsInPeriod);
event AdminFrequencyOverrideChanged(address _account, bool _override);
event AdminRoyaltiesRegistryChanged(address _royaltiesRegistry);
modifier onlyAdmin() {
require(accessControls.hasAdminRole(_msgSender()), "Caller must have admin role");
_;
}
modifier canMintAgain(){
require(_canCreateNewEdition(_msgSender()), "Caller unable to create yet");
_;
}
IKOAccessControlsLookup public accessControls;
IKODAV3Minter public koda;
IKODAV3PrimarySaleMarketplace public marketplace;
ICollabRoyaltiesRegistry public royaltiesRegistry;
// Minting allowance period
uint256 public mintingPeriod = 30 days;
// Limit of mints with in the period
uint256 public maxMintsInPeriod = 15;
// Frequency override list for users - you can temporarily add in address which disables the freeze time check
mapping(address => bool) public frequencyOverride;
struct MintingPeriod {
uint128 mints;
uint128 firstMintInPeriod;
}
// How many mints within the current minting period
mapping(address => MintingPeriod) mintingPeriodConfig;
enum SaleType {
BUY_NOW, OFFERS, STEPPED, RESERVE
}
constructor(
IKOAccessControlsLookup _accessControls,
IKODAV3Minter _koda,
IKODAV3PrimarySaleMarketplace _marketplace,
ICollabRoyaltiesRegistry _royaltiesRegistry
) {
accessControls = _accessControls;
koda = _koda;
marketplace = _marketplace;
royaltiesRegistry = _royaltiesRegistry;
emit MintingFactoryCreated();
}
function mintToken(
SaleType _saleType,
uint128 _startDate,
uint128 _basePrice,
uint128 _stepPrice,
string calldata _uri,
uint256 _merkleIndex,
bytes32[] calldata _merkleProof,
address _deployedRoyaltiesHandler
) canMintAgain external {
require(accessControls.isVerifiedArtist(_merkleIndex, _msgSender(), _merkleProof), "Caller must have minter role");
// Make tokens & edition
uint256 editionId = koda.mintBatchEdition(1, _msgSender(), _uri);
_setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice);
_recordSuccessfulMint(_msgSender());
_setupRoyalties(editionId, _deployedRoyaltiesHandler);
}
function mintTokenAsProxy(
address _creator,
SaleType _saleType,
uint128 _startDate,
uint128 _basePrice,
uint128 _stepPrice,
string calldata _uri,
address _deployedRoyaltiesHandler
) canMintAgain external {
require(accessControls.isVerifiedArtistProxy(_creator, _msgSender()), "Caller is not artist proxy");
// Make tokens & edition
uint256 editionId = koda.mintBatchEdition(1, _creator, _uri);
_setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice);
_recordSuccessfulMint(_creator);
_setupRoyalties(editionId, _deployedRoyaltiesHandler);
}
function mintBatchEdition(
SaleType _saleType,
uint16 _editionSize,
uint128 _startDate,
uint128 _basePrice,
uint128 _stepPrice,
string calldata _uri,
uint256 _merkleIndex,
bytes32[] calldata _merkleProof,
address _deployedRoyaltiesHandler
) canMintAgain external {
require(accessControls.isVerifiedArtist(_merkleIndex, _msgSender(), _merkleProof), "Caller must have minter role");
// Make tokens & edition
uint256 editionId = koda.mintBatchEdition(_editionSize, _msgSender(), _uri);
_setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice);
_recordSuccessfulMint(_msgSender());
_setupRoyalties(editionId, _deployedRoyaltiesHandler);
}
function mintBatchEditionAsProxy(
address _creator,
SaleType _saleType,
uint16 _editionSize,
uint128 _startDate,
uint128 _basePrice,
uint128 _stepPrice,
string calldata _uri,
address _deployedRoyaltiesHandler
) canMintAgain external {
require(accessControls.isVerifiedArtistProxy(_creator, _msgSender()), "Caller is not artist proxy");
// Make tokens & edition
uint256 editionId = koda.mintBatchEdition(_editionSize, _creator, _uri);
_setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice);
_recordSuccessfulMint(_creator);
_setupRoyalties(editionId, _deployedRoyaltiesHandler);
}
function mintBatchEditionAndComposeERC20s(
SaleType _saleType,
// --- _config array (expected length of 5) ---
// Index 0 - Merkle Index
// Index 1 - Edition size
// Index 2 - Start Date
// Index 3 - Base price
// Index 4 - Step price
// ---------------------------------------------
uint128[] calldata _config,
string calldata _uri,
address[] calldata _erc20s,
uint256[] calldata _amounts,
bytes32[] calldata _merkleProof
) canMintAgain external {
require(accessControls.isVerifiedArtist(_config[0], _msgSender(), _merkleProof), "Caller must have minter role");
require(_config.length == 5, "Config must consist of 5 elements in the array");
uint256 editionId = koda.mintBatchEditionAndComposeERC20s(uint16(_config[1]), _msgSender(), _uri, _erc20s, _amounts);
_setupSalesMechanic(editionId, _saleType, _config[2], _config[3], _config[4]);
_recordSuccessfulMint(_msgSender());
}
function mintBatchEditionAndComposeERC20sAsProxy(
address _creator,
SaleType _saleType,
// --- _config array (expected length of 4) ---
// Index 0 - Edition size
// Index 1 - Start Date
// Index 2 - Base price
// Index 3 - Step price
// ---------------------------------------------
uint128[] calldata _config,
string calldata _uri,
address[] calldata _erc20s,
uint256[] calldata _amounts
) canMintAgain external {
require(accessControls.isVerifiedArtistProxy(_creator, _msgSender()), "Caller is not artist proxy");
require(_config.length == 4, "Config must consist of 4 elements in the array");
uint256 editionId = koda.mintBatchEditionAndComposeERC20s(uint16(_config[0]), _creator, _uri, _erc20s, _amounts);
_setupSalesMechanic(editionId, _saleType, _config[1], _config[2], _config[3]);
_recordSuccessfulMint(_creator);
}
function mintConsecutiveBatchEdition(
SaleType _saleType,
uint16 _editionSize,
uint128 _startDate,
uint128 _basePrice,
uint128 _stepPrice,
string calldata _uri,
uint256 _merkleIndex,
bytes32[] calldata _merkleProof,
address _deployedRoyaltiesHandler
) canMintAgain external {
require(accessControls.isVerifiedArtist(_merkleIndex, _msgSender(), _merkleProof), "Caller must have minter role");
// Make tokens & edition
uint256 editionId = koda.mintConsecutiveBatchEdition(_editionSize, _msgSender(), _uri);
_setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice);
_recordSuccessfulMint(_msgSender());
_setupRoyalties(editionId, _deployedRoyaltiesHandler);
}
function mintConsecutiveBatchEditionAsProxy(
address _creator,
SaleType _saleType,
uint16 _editionSize,
uint128 _startDate,
uint128 _basePrice,
uint128 _stepPrice,
string calldata _uri,
address _deployedRoyaltiesHandler
) canMintAgain external {
require(accessControls.isVerifiedArtistProxy(_creator, _msgSender()), "Caller is not artist proxy");
// Make tokens & edition
uint256 editionId = koda.mintConsecutiveBatchEdition(_editionSize, _creator, _uri);
_setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice);
_recordSuccessfulMint(_creator);
_setupRoyalties(editionId, _deployedRoyaltiesHandler);
}
function _setupSalesMechanic(uint256 _editionId, SaleType _saleType, uint128 _startDate, uint128 _basePrice, uint128 _stepPrice) internal {
if (SaleType.BUY_NOW == _saleType) {
marketplace.listForBuyNow(_msgSender(), _editionId, _basePrice, _startDate);
}
else if (SaleType.STEPPED == _saleType) {
marketplace.listSteppedEditionAuction(_msgSender(), _editionId, _basePrice, _stepPrice, _startDate);
}
else if (SaleType.OFFERS == _saleType) {
marketplace.enableEditionOffers(_editionId, _startDate);
} else if (SaleType.RESERVE == _saleType) {
// use base price for reserve price
marketplace.listForReserveAuction(_msgSender(), _editionId, _basePrice, _startDate);
}
emit EditionMintedAndListed(_editionId, _saleType);
}
function _setupRoyalties(uint256 _editionId, address _deployedHandler) internal {
if (_deployedHandler != address(0) && address(royaltiesRegistry) != address(0)) {
royaltiesRegistry.useRoyaltiesRecipient(_editionId, _deployedHandler);
}
}
/// Internal helpers
function _canCreateNewEdition(address _account) internal view returns (bool) {
// if frequency is overridden then assume they can mint
if (frequencyOverride[_account]) {
return true;
}
// if within the period range, check remaining allowance
if (_getNow() <= mintingPeriodConfig[_account].firstMintInPeriod + mintingPeriod) {
return mintingPeriodConfig[_account].mints < maxMintsInPeriod;
}
// if period expired - can mint another one
return true;
}
function _recordSuccessfulMint(address _account) internal {
MintingPeriod storage period = mintingPeriodConfig[_account];
uint256 endOfCurrentMintingPeriodLimit = period.firstMintInPeriod + mintingPeriod;
// if first time use, set the first timestamp to be now abd start counting
if (period.firstMintInPeriod == 0) {
period.firstMintInPeriod = _getNow();
period.mints = period.mints + 1;
}
// if still within the minting period, record the new mint
else if (_getNow() <= endOfCurrentMintingPeriodLimit) {
period.mints = period.mints + 1;
}
// if we are outside of the window reset the limit and record a new single mint
else if (endOfCurrentMintingPeriodLimit < _getNow()) {
period.mints = 1;
period.firstMintInPeriod = _getNow();
}
}
function _getNow() internal virtual view returns (uint128) {
return uint128(block.timestamp);
}
/// Public helpers
function canCreateNewEdition(address _account) public view returns (bool) {
return _canCreateNewEdition(_account);
}
function currentMintConfig(address _account) public view returns (uint128 mints, uint128 firstMintInPeriod) {
MintingPeriod memory config = mintingPeriodConfig[_account];
return (
config.mints,
config.firstMintInPeriod
);
}
function setFrequencyOverride(address _account, bool _override) onlyAdmin public {
frequencyOverride[_account] = _override;
emit AdminFrequencyOverrideChanged(_account, _override);
}
function setMintingPeriod(uint256 _mintingPeriod) onlyAdmin public {
mintingPeriod = _mintingPeriod;
emit AdminMintingPeriodChanged(_mintingPeriod);
}
function setRoyaltiesRegistry(ICollabRoyaltiesRegistry _royaltiesRegistry) onlyAdmin public {
royaltiesRegistry = _royaltiesRegistry;
emit AdminRoyaltiesRegistryChanged(address(_royaltiesRegistry));
}
function setMaxMintsInPeriod(uint256 _maxMintsInPeriod) onlyAdmin public {
maxMintsInPeriod = _maxMintsInPeriod;
emit AdminMaxMintsInPeriodChanged(_maxMintsInPeriod);
}
}
| Make tokens & edition | function mintBatchEditionAsProxy(
address _creator,
SaleType _saleType,
uint16 _editionSize,
uint128 _startDate,
uint128 _basePrice,
uint128 _stepPrice,
string calldata _uri,
address _deployedRoyaltiesHandler
) canMintAgain external {
require(accessControls.isVerifiedArtistProxy(_creator, _msgSender()), "Caller is not artist proxy");
uint256 editionId = koda.mintBatchEdition(_editionSize, _creator, _uri);
_setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice);
_recordSuccessfulMint(_creator);
_setupRoyalties(editionId, _deployedRoyaltiesHandler);
}
| 6,354,164 |
pragma solidity 0.4.24;
import "../common/ReservedAddrPublic.sol";
import "../../interaction/interface/IPermission.sol";
/// @title Permission contract
/// @author ["Rivtower Technologies <[email protected]>"]
/// @notice The address: Created by permissionCreator
/// The interface can be called: Only query type
contract Permission is IPermission, ReservedAddrPublic {
struct Resource {
// Contract address
address cont;
// Function hash
bytes4 func;
}
Resource[] resources;
bytes32 name;
event ResourcesAdded(address[] _conts, bytes4[] _funcs);
event ResourcesDeleted(address[] _conts, bytes4[] _funcs);
event NameUpdated(bytes32 indexed _oldName, bytes32 indexed _name);
modifier onlyPermissionManagement {
require(permissionManagementAddr == msg.sender, "permission denied.");
_;
}
/// @notice Constructor
constructor(bytes32 _name, address[] _conts, bytes4[] _funcs)
public
{
name = _name;
require(_addResources(_conts, _funcs), "constructor failed.");
}
/// @notice Add the resources
/// @param _conts The contracts of resource
/// @param _funcs The function signature of resource
/// @return true if successed, otherwise false
function addResources(address[] _conts, bytes4[] _funcs)
external
onlyPermissionManagement
returns (bool)
{
require(_addResources(_conts, _funcs), "addResources failed.");
return true;
}
/// @notice Delete the resources
/// @param _conts The contracts of resource
/// @param _funcs The function signature of resource
/// @return true if successed, otherwise false
function deleteResources(address[] _conts, bytes4[] _funcs)
external
onlyPermissionManagement
returns (bool)
{
for (uint i = 0; i < _conts.length; i++)
require(
resourceDelete(_conts[i], _funcs[i]),
"deleteResources failed."
);
emit ResourcesDeleted(_conts, _funcs);
return true;
}
/// @notice Update permission's name
/// @param _name The new name
/// @return true if successed, otherwise false
function updateName(bytes32 _name)
public
onlyPermissionManagement
returns (bool)
{
emit NameUpdated(name, _name);
name = _name;
return true;
}
/// @notice Destruct self
/// @return true if successed, otherwise false
function close()
public
onlyPermissionManagement
{
selfdestruct(msg.sender);
}
/// @notice Check resource in the permission
/// @param cont The contract address of the resource
/// @param func The function signature of the resource
/// @return true if in permission, otherwise false
function inPermission(address cont, bytes4 func)
public
view
returns (bool)
{
for (uint i = 0; i < resources.length; i++) {
if (cont == resources[i].cont && func == resources[i].func)
return true;
}
return false;
}
/// @notice Query the information of the permission
/// @return The information of permission: name and resources
function queryInfo()
public
view
returns (bytes32, address[], bytes4[])
{
uint len = resources.length;
address[] memory conts = new address[](len);
bytes4[] memory funcs = new bytes4[](len);
for (uint i = 0; i < resources.length; i++) {
conts[i] = resources[i].cont;
funcs[i] = resources[i].func;
}
return (name, conts, funcs);
}
/// @notice Query the name of the permission
/// @return The name of permission
function queryName()
public
view
returns (bytes32)
{
return name;
}
/// @notice Query the resource of the permission
/// @return The resources of permission
function queryResource()
public
view
returns (address[], bytes4[])
{
uint len = resources.length;
address[] memory conts = new address[](len);
bytes4[] memory funcs = new bytes4[](len);
for (uint i = 0; i < resources.length; i++) {
conts[i] = resources[i].cont;
funcs[i] = resources[i].func;
}
return (conts, funcs);
}
/// @notice Private: Delete the value of the resources
function resourceDelete(address _cont, bytes4 _func)
private
returns (bool)
{
uint index = resourceIndex(_cont, _func);
// Not found
if (index >= resources.length)
return false;
// Move the last element to the index of array
resources[index] = resources[resources.length - 1];
// Also delete the last element
delete resources[resources.length-1];
resources.length--;
return true;
}
/// @notice Private: Get the index of the value in the resources
function resourceIndex(address _cont, bytes4 _func)
private
view
returns (uint i)
{
for (i = 0; i < resources.length; i++) {
if (_cont == resources[i].cont && _func == resources[i].func)
return i;
}
}
/// @notice Private: Add resources
function _addResources(address[] _conts, bytes4[] _funcs)
private
returns (bool)
{
for (uint i = 0; i < _conts.length; i++) {
if (!inResources(_conts[i], _funcs[i])) {
Resource memory res = Resource(_conts[i], _funcs[i]);
resources.push(res);
}
}
emit ResourcesAdded(_conts, _funcs);
return true;
}
/// @notice Private: Check the duplicate resource
function inResources(address _cont, bytes4 _func)
private
view
returns (bool)
{
for (uint i = 0; i < resources.length; i++) {
if (_cont == resources[i].cont && _func == resources[i].func)
return true;
}
return false;
}
}
| Add the resources _conts The contracts of resource _funcs The function signature of resource return true if successed, otherwise false | function addResources(address[] _conts, bytes4[] _funcs)
external
onlyPermissionManagement
returns (bool)
{
require(_addResources(_conts, _funcs), "addResources failed.");
return true;
}
| 12,783,999 |
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// Lib: Safe Math
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a + b;
require(c >= a);
}
function safeSub(uint256 a, uint256 b) public pure returns (uint256 c) {
require(b <= a);
c = a - b;
}
function safeMul(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint256 a, uint256 b) public pure returns (uint256 c) {
require(b > 0);
c = a / b;
}
}
/**
ERC Token Standard #20 Interface
https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20Interface {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner)
public
constant
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
public
constant
returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens)
public
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(
address indexed tokenOwner,
address indexed spender,
uint256 tokens
);
}
/**
Contract function to receive approval and execute function in one call
Borrowed from MiniMeToken
*/
contract ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 tokens,
address token,
bytes data
) public;
}
/**
ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers
*/
contract TKT is ERC20Interface, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint256 public _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "TKT";
name = "TKT Token";
decimals = 4;
_totalSupply = 10000000000000;
// metamask - michael vergoz
// balances[0xf1E2C564b0182Fba1BfA07c196c443DeB10e7De4] = _totalSupply;
// emit Transfer(
// address(0),
// 0xf1E2C564b0182Fba1BfA07c196c443DeB10e7De4,
// _totalSupply
// );
balances[0x20e99E8DB53408e0033119A10Bcc2921C97B99eA] = _totalSupply;
emit Transfer(
address(0),
0x20e99E8DB53408e0033119A10Bcc2921C97B99eA,
_totalSupply
);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint256) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner)
public
constant
returns (uint256 balance)
{
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint256 tokens)
public
returns (bool success)
{
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint256 tokens)
public
returns (bool success)
{
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(
address from,
address to,
uint256 tokens
) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender)
public
constant
returns (uint256 remaining)
{
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(
address spender,
uint256 tokens,
bytes data
) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(
msg.sender,
tokens,
this,
data
);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function() public payable {
revert();
}
} | ------------------------------------------------------------------------ Token owner can approve for spender to transferFrom(...) tokens from the token owner's account. The spender contract function receiveApproval(...) is then executed ------------------------------------------------------------------------ | function approveAndCall(
address spender,
uint256 tokens,
bytes data
) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(
msg.sender,
tokens,
this,
data
);
return true;
}
| 62,168 |
./full_match/137/0xD6e87CE87382854e4817c9a8331C8F2341bc7264/sources/hh.sol | 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;
}
| 3,755,721 |
pragma solidity 0.4.18;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
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;
}
}
// File: contracts/Restricted.sol
/** @title Restricted
* Exposes onlyMonetha modifier
*/
contract Restricted is Ownable {
//MonethaAddress set event
event MonethaAddressSet(
address _address,
bool _isMonethaAddress
);
mapping (address => bool) public isMonethaAddress;
/**
* Restrict methods in such way, that they can be invoked only by monethaAddress account.
*/
modifier onlyMonetha() {
require(isMonethaAddress[msg.sender]);
_;
}
/**
* Allows owner to set new monetha address
*/
function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public {
isMonethaAddress[_address] = _isMonethaAddress;
MonethaAddressSet(_address, _isMonethaAddress);
}
}
// File: zeppelin-solidity/contracts/ownership/Contactable.sol
/**
* @title Contactable token
* @dev Basic version of a contactable contract, allowing the owner to provide a string with their
* contact information.
*/
contract Contactable is Ownable{
string public contactInformation;
/**
* @dev Allows the owner to set a string with their contact information.
* @param info The contact information to attach to the contract.
*/
function setContactInformation(string info) onlyOwner public {
contactInformation = info;
}
}
// File: contracts/MerchantDealsHistory.sol
/**
* @title MerchantDealsHistory
* Contract stores hash of Deals conditions together with parties reputation for each deal
* This history enables to see evolution of trust rating for both parties
*/
contract MerchantDealsHistory is Contactable, Restricted {
string constant VERSION = "0.3";
/// Merchant identifier hash
bytes32 public merchantIdHash;
//Deal event
event DealCompleted(
uint orderId,
address clientAddress,
uint32 clientReputation,
uint32 merchantReputation,
bool successful,
uint dealHash
);
//Deal cancellation event
event DealCancelationReason(
uint orderId,
address clientAddress,
uint32 clientReputation,
uint32 merchantReputation,
uint dealHash,
string cancelReason
);
//Deal refund event
event DealRefundReason(
uint orderId,
address clientAddress,
uint32 clientReputation,
uint32 merchantReputation,
uint dealHash,
string refundReason
);
/**
* @param _merchantId Merchant of the acceptor
*/
function MerchantDealsHistory(string _merchantId) public {
require(bytes(_merchantId).length > 0);
merchantIdHash = keccak256(_merchantId);
}
/**
* recordDeal creates an event of completed deal
* @param _orderId Identifier of deal's order
* @param _clientAddress Address of client's account
* @param _clientReputation Updated reputation of the client
* @param _merchantReputation Updated reputation of the merchant
* @param _isSuccess Identifies whether deal was successful or not
* @param _dealHash Hashcode of the deal, describing the order (used for deal verification)
*/
function recordDeal(
uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
bool _isSuccess,
uint _dealHash)
external onlyMonetha
{
DealCompleted(
_orderId,
_clientAddress,
_clientReputation,
_merchantReputation,
_isSuccess,
_dealHash
);
}
/**
* recordDealCancelReason creates an event of not paid deal that was cancelled
* @param _orderId Identifier of deal's order
* @param _clientAddress Address of client's account
* @param _clientReputation Updated reputation of the client
* @param _merchantReputation Updated reputation of the merchant
* @param _dealHash Hashcode of the deal, describing the order (used for deal verification)
* @param _cancelReason deal cancelation reason (text)
*/
function recordDealCancelReason(
uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _cancelReason)
external onlyMonetha
{
DealCancelationReason(
_orderId,
_clientAddress,
_clientReputation,
_merchantReputation,
_dealHash,
_cancelReason
);
}
/**
* recordDealRefundReason creates an event of not paid deal that was cancelled
* @param _orderId Identifier of deal's order
* @param _clientAddress Address of client's account
* @param _clientReputation Updated reputation of the client
* @param _merchantReputation Updated reputation of the merchant
* @param _dealHash Hashcode of the deal, describing the order (used for deal verification)
* @param _refundReason deal refund reason (text)
*/
function recordDealRefundReason(
uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _refundReason)
external onlyMonetha
{
DealRefundReason(
_orderId,
_clientAddress,
_clientReputation,
_merchantReputation,
_dealHash,
_refundReason
);
}
} | recordDealRefundReason creates an event of not paid deal that was cancelled _orderId Identifier of deal's order _clientAddress Address of client's account _clientReputation Updated reputation of the client _merchantReputation Updated reputation of the merchant _dealHash Hashcode of the deal, describing the order (used for deal verification) _refundReason deal refund reason (text)/ | function recordDealRefundReason(
uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _refundReason)
external onlyMonetha
{
DealRefundReason(
_orderId,
_clientAddress,
_clientReputation,
_merchantReputation,
_dealHash,
_refundReason
);
}
| 882,026 |
/// SPDX-License-Identifier: MIT
/*
▄▄█ ▄ ██ █▄▄▄▄ ▄█
██ █ █ █ █ ▄▀ ██
██ ██ █ █▄▄█ █▀▀▌ ██
▐█ █ █ █ █ █ █ █ ▐█
▐ █ █ █ █ █ ▐
█ ██ █ ▀
▀ */
/// Special thanks to Keno, Boring and Gonpachi for review and continued inspiration.
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
/// License-Identifier: MIT
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
}
/// @notice Interface for depositing into and withdrawing from Aave lending pool.
interface IAaveBridge {
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address token,
uint256 amount,
address destination
) external;
}
/// @notice Interface for depositing into and withdrawing from BentoBox vault.
interface IBentoBridge {
function balanceOf(IERC20, address) external view returns (uint256);
function registerProtocol() external;
function deposit(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external payable returns (uint256 amountOut, uint256 shareOut);
function withdraw(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external returns (uint256 amountOut, uint256 shareOut);
}
/// @notice Interface for depositing into and withdrawing from Compound finance protocol.
interface ICompoundBridge {
function underlying() external view returns (address);
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
}
/// @notice Interface for Dai Stablecoin (DAI) `permit()` primitive.
interface IDaiPermit {
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
/// @notice Interface for depositing into and withdrawing from SushiBar.
interface ISushiBarBridge {
function enter(uint256 amount) external;
function leave(uint256 share) external;
}
/// @notice Interface for SushiSwap.
interface ISushiSwap {
function deposit() external payable;
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
// File @boringcrypto/boring-solidity/contracts/interfaces/[email protected]
/// License-Identifier: MIT
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
/// License-Identifier: MIT
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
}
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
/// License-Identifier: MIT
contract BaseBoringBatchable {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
/// @return successes An array indicating the success of a call, mapped one-to-one to `calls`.
/// @return results An array with the returned data of each function call, mapped one-to-one to `calls`.
// F1: External is ok here because this is the batch function, adding it to a batch makes no sense
// F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value
// C3: The length of the loop is fully under user control, so can't be exploited
// C7: Delegatecall is only used on the same contract, so it's safe
function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) {
successes = new bool[](calls.length);
results = new bytes[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(calls[i]);
require(success || !revertOnFail, _getRevertMsg(result));
successes[i] = success;
results[i] = result;
}
}
}
/// @notice Extends `BoringBatchable` with DAI `permit()`.
contract BoringBatchableWithDai is BaseBoringBatchable {
address constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // DAI token contract
/// @notice Call wrapper that performs `ERC20.permit` on `dai` using EIP 2612 primitive.
/// Lookup `IDaiPermit.permit`.
function permitDai(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) public {
IDaiPermit(dai).permit(holder, spender, nonce, expiry, allowed, v, r, s);
}
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
/// @notice Contract that batches SUSHI staking and DeFi strategies - V1.
contract Inari is BoringBatchableWithDai {
using BoringMath for uint256;
using BoringERC20 for IERC20;
IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract
address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI
IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI
IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI
IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract
address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI
address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI
address constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // ETH wrapper contract (v9)
address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // SushiSwap factory contract
ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap
bytes32 constant pairCodeHash = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // SushiSwap pair code hash
/// @notice Initialize this Inari contract and core SUSHI strategies.
constructor() public {
bento.registerProtocol(); // register this contract with BENTO
sushiToken.approve(address(sushiBar), type(uint256).max); // max approve `sushiBar` spender to stake SUSHI into xSUSHI from this contract
sushiToken.approve(crSushiToken, type(uint256).max); // max approve `crSushiToken` spender to stake SUSHI into crSUSHI from this contract
IERC20(sushiBar).approve(address(aave), type(uint256).max); // max approve `aave` spender to stake xSUSHI into aXSUSHI from this contract
IERC20(sushiBar).approve(address(bento), type(uint256).max); // max approve `bento` spender to stake xSUSHI into BENTO from this contract
IERC20(sushiBar).approve(crXSushiToken, type(uint256).max); // max approve `crXSushiToken` spender to stake xSUSHI into crXSUSHI from this contract
IERC20(dai).approve(address(bento), type(uint256).max); // max approve `bento` spender to pull DAI into BENTO from this contract
}
/// @notice Helper function to approve this contract to spend and bridge more tokens among DeFi contracts.
function bridgeABC(IERC20[] calldata underlying, address[] calldata cToken) external {
for (uint256 i = 0; i < underlying.length; i++) {
underlying[i].approve(address(aave), type(uint256).max); // max approve `aave` spender to pull `underlying` from this contract
underlying[i].approve(address(bento), type(uint256).max); // max approve `bento` spender to pull `underlying` from this contract
underlying[i].approve(cToken[i], type(uint256).max); // max approve `cToken` spender to pull `underlying` from this contract (also serves as generalized approval bridge)
}
}
/************
SUSHI HELPERS
************/
/// @notice Stake SUSHI `amount` into xSushi for benefit of `to` by call to `sushiBar`.
function stakeSushi(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/// @notice Stake SUSHI local balance into xSushi for benefit of `to` by call to `sushiBar`.
function stakeSushiBalance(address to) external {
ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake local SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/**********
TKN HELPERS
**********/
/// @notice Token deposit function for `batch()` into strategies.
function depositToken(IERC20 token, uint256 amount) external {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
}
/// @notice Token withdraw function for `batch()` into strategies.
function withdrawToken(IERC20 token, address to, uint256 amount) external {
IERC20(token).safeTransfer(to, amount);
}
/// @notice Token local balance withdraw function for `batch()` into strategies.
function withdrawTokenBalance(IERC20 token, address to) external {
IERC20(token).safeTransfer(to, token.balanceOf(address(this)));
}
/*
██ ██ ▄ ▄███▄
█ █ █ █ █ █▀ ▀
█▄▄█ █▄▄█ █ █ ██▄▄
█ █ █ █ █ █ █▄ ▄▀
█ █ █ █ ▀███▀
█ █ █▐
▀ ▀ ▐ */
/***********
AAVE HELPERS
***********/
function toAave(address underlying, address to, uint256 amount) external {
aave.deposit(underlying, amount, to, 0);
}
function balanceToAave(address underlying, address to) external {
aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0);
}
function fromAave(address underlying, address to, uint256 amount) external {
aave.withdraw(underlying, amount, to);
}
function balanceFromAave(address aToken, address to) external {
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, IERC20(aToken).balanceOf(address(this)), to);
}
/**************************
AAVE -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`.
function aaveToBento(address aToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
bento.deposit(IERC20(underlying), address(this), to, amount, 0); // stake `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> AAVE
**************************/
/// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`.
function bentoToAave(IERC20 underlying, address to, uint256 amount) external {
bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract
aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to`
}
/*************************
AAVE -> UNDERLYING -> COMP
*************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`.
function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
/*************************
COMP -> UNDERLYING -> AAVE
*************************/
/// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`.
function compoundToAave(address cToken, address to, uint256 amount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract
ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying`
address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token
aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0); // stake resulting `underlying` into `aave` for `to`
}
/**********************
SUSHI -> XSUSHI -> AAVE
**********************/
/// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`.
function stakeSushiToAave(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
aave.deposit(sushiBar, IERC20(sushiBar).balanceOf(address(this)), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to`
}
/**********************
AAVE -> XSUSHI -> SUSHI
**********************/
/// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`.
function unstakeSushiFromAave(address to, uint256 amount) external {
aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract
aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI
ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
███ ▄███▄ ▄ ▄▄▄▄▀ ████▄
█ █ █▀ ▀ █ ▀▀▀ █ █ █
█ ▀ ▄ ██▄▄ ██ █ █ █ █
█ ▄▀ █▄ ▄▀ █ █ █ █ ▀████
███ ▀███▀ █ █ █ ▀
█ ██ */
/// @notice Helper function to `permit()` this contract to deposit `dai` into `bento` for benefit of `to`.
function daiToBentoWithPermit(
address to, uint256 amount, uint256 nonce, uint256 expiry,
uint8 v, bytes32 r, bytes32 s
) external {
IDaiPermit(dai).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); // `permit()` this contract to spend `msg.sender` `dai`
IERC20(dai).safeTransferFrom(msg.sender, address(this), amount); // pull `dai` `amount` into this contract
bento.deposit(IERC20(dai), address(this), to, amount, 0); // stake `dai` into BENTO for `to`
}
/************
BENTO HELPERS
************/
function toBento(IERC20 token, address to, uint256 amount) external {
bento.deposit(token, address(this), to, amount, 0);
}
function balanceToBento(IERC20 token, address to) external {
bento.deposit(token, address(this), to, token.balanceOf(address(this)), 0);
}
function fromBento(IERC20 token, address to, uint256 amount) external {
bento.withdraw(token, msg.sender, to, amount, 0);
}
function balanceFromBento(IERC20 token, address to) external {
bento.withdraw(token, msg.sender, to, bento.balanceOf(token, msg.sender), 0);
}
/***********************
SUSHI -> XSUSHI -> BENTO
***********************/
/// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`.
function stakeSushiToBento(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to`
}
/***********************
BENTO -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`.
function unstakeSushiFromBento(address to, uint256 amount) external {
bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract
ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
▄█▄ █▄▄▄▄ ▄███▄ ██ █▀▄▀█
█▀ ▀▄ █ ▄▀ █▀ ▀ █ █ █ █ █
█ ▀ █▀▀▌ ██▄▄ █▄▄█ █ ▄ █
█▄ ▄▀ █ █ █▄ ▄▀ █ █ █ █
▀███▀ █ ▀███▀ █ █
▀ █ ▀
▀ */
// - COMPOUND - //
/***********
COMP HELPERS
***********/
function toCompound(ICompoundBridge cToken, uint256 underlyingAmount) external {
cToken.mint(underlyingAmount);
}
function balanceToCompound(ICompoundBridge cToken) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
cToken.mint(underlying.balanceOf(address(this)));
}
function fromCompound(ICompoundBridge cToken, uint256 cTokenAmount) external {
ICompoundBridge(cToken).redeem(cTokenAmount);
}
function balanceFromCompound(address cToken) external {
ICompoundBridge(cToken).redeem(IERC20(cToken).balanceOf(address(this)));
}
/**************************
COMP -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`.
function compoundToBento(address cToken, address to, uint256 cTokenAmount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract
ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying`
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.deposit(underlying, address(this), to, underlying.balanceOf(address(this)), 0); // stake resulting `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> COMP
**************************/
/// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`.
function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract
ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
/**********************
SUSHI -> CREAM -> BENTO
**********************/
/// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`.
function sushiToCreamToBento(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI
bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).balanceOf(address(this)), 0); // stake resulting crSUSHI into BENTO for `to`
}
/**********************
BENTO -> CREAM -> SUSHI
**********************/
/// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`.
function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external {
bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract
ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/***********************
SUSHI -> XSUSHI -> CREAM
***********************/
/// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`.
function stakeSushiToCream(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).balanceOf(address(this))); // transfer resulting crXSUSHI to `to`
}
/***********************
CREAM -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCream(address to, uint256 cTokenAmount) external {
IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract
ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/********************************
SUSHI -> XSUSHI -> CREAM -> BENTO
********************************/
/// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`.
function stakeSushiToCreamToBento(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).balanceOf(address(this)), 0); // stake resulting crXSUSHI into BENTO for `to`
}
/********************************
BENTO -> CREAM -> XSUSHI -> SUSHI
********************************/
/// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external {
bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract
ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
▄▄▄▄▄ ▄ ▄ ██ █ ▄▄
█ ▀▄ █ █ █ █ █ █
▄ ▀▀▀▀▄ █ ▄ █ █▄▄█ █▀▀▀
▀▄▄▄▄▀ █ █ █ █ █ █
█ █ █ █ █
▀ ▀ █ ▀
▀ */
/// @notice SushiSwap ETH to stake SUSHI into xSUSHI for benefit of `to`.
function ethStakeSushi(address to) external payable { // SWAP `N STAKE
(uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
uint256 amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
ISushiSwap(wETH).deposit{value: msg.value}();
IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);
sushiSwapSushiETHPair.swap(amountOut, 0, address(this), "");
ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/// @notice SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`.
function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, "");
}
}
/// @notice SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`.
function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
uint256 amountIn = IERC20(fromToken).balanceOf(address(this));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, "");
}
}
/// @notice SushiSwap ETH `msg.value` to `toToken` for benefit of `to`.
function swapETH(address toToken, address to) external payable returns (uint256 amountOut) {
(address token0, address token1) = wETH < toToken ? (wETH, toToken) : (toToken, wETH);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
ISushiSwap(wETH).deposit{value: msg.value}();
if (toToken > wETH) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(wETH).safeTransfer(address(pair), msg.value);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(wETH).safeTransfer(address(pair), msg.value);
pair.swap(amountOut, 0, to, "");
}
}
} | Stake SUSHI local balance into xSushi for benefit of `to` by call to `sushiBar`. | function stakeSushiBalance(address to) external {
}
| 44,077 |
./full_match/1/0x0000000304aAD016bA7a745da3cE64f6198B76B3/sources/lib/solady/src/utils/FixedPointMathLib.sol | Returns `x y`, without checking for overflow. | function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
| 3,200,585 |
pragma solidity >=0.5.0 <0.6.0;
/// @title ERC165Interface
/// @dev https://eips.ethereum.org/EIPS/eip-165
interface ERC165Interface {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/// @title Shared constants used throughout the Cheeze Wizards Contracts
contract WizardConstants {
// Wizards normally have their affinity set when they are first created,
// but for example Exclusive Wizards can be created with no set affinity.
// In this case the affinity can be set by the owner.
uint8 internal constant ELEMENT_NOTSET = 0; //000
// A neutral Wizard has no particular strength or weakness with specific
// elements.
uint8 internal constant ELEMENT_NEUTRAL = 1; //001
// The fire, water and wind elements are used both to reflect an affinity
// of Elemental Wizards for a specific element, and as the moves a
// Wizard can make during a duel.
// Note thta if these values change then `moveMask` and `moveDelta` in
// ThreeAffinityDuelResolver would need to be updated accordingly.
uint8 internal constant ELEMENT_FIRE = 2; //010
uint8 internal constant ELEMENT_WATER = 3; //011
uint8 internal constant ELEMENT_WIND = 4; //100
uint8 internal constant MAX_ELEMENT = ELEMENT_WIND;
}
contract ERC1654 {
/// @dev bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 public constant ERC1654_VALIDSIGNATURE = 0x1626ba7e;
/// @dev Should return whether the signature provided is valid for the provided data
/// @param hash 32-byte hash of the data that is signed
/// @param _signature Signature byte array associated with _data
/// MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
/// MUST allow external calls
function isValidSignature(
bytes32 hash,
bytes calldata _signature)
external
view
returns (bytes4);
}
/**
* @title IERC165
* @dev https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
contract WizardGuildInterfaceId {
bytes4 internal constant _INTERFACE_ID_WIZARDGUILD = 0x41d4d437;
}
/// @title The public interface of the Wizard Guild
/// @notice The methods listed in this interface (including the inherited ERC-721 interface),
/// make up the public interface of the Wizard Guild contract. Any Contracts that wish
/// to make use of Cheeze Wizard NFTs (such as Cheeze Wizards Tournaments!) should use
/// these methods to ensure they are working correctly with the base NFTs.
contract WizardGuildInterface is IERC721, WizardGuildInterfaceId {
/// @notice Returns the information associated with the given Wizard
/// owner - The address that owns this Wizard
/// innatePower - The innate power level of this Wizard, set when minted and entirely
/// immutable
/// affinity - The Elemental Affinity of this Wizard. For most Wizards, this is set
/// when they are minted, but some exclusive Wizards are minted with an affinity
/// of 0 (ELEMENT_NOTSET). A Wizard with an NOTSET affinity should NOT be able
/// to participate in Tournaments. Once the affinity of a Wizard is set to a non-zero
/// value, it can never be changed again.
/// metadata - A 256-bit hash of the Wizard's metadata, which is stored off chain. This
/// contract doesn't specify format of this hash, nor the off-chain storage mechanism
/// but, let's be honest, it's probably an IPFS SHA-256 hash.
///
/// NOTE: Series zero Wizards have one of four Affinities: Neutral (1), Fire (2), Water (3)
/// or Air (4, sometimes called "Wind" in the code). Future Wizard Series may have
/// additional Affinities, and clients of this API should be prepared for that
/// eventuality.
function getWizard(uint256 id) external view returns (address owner, uint88 innatePower, uint8 affinity, bytes32 metadata);
/// @notice Sets the affinity for a Wizard that doesn't already have its elemental affinity chosen.
/// Only usable for Exclusive Wizards (all non-Exclusives must have their affinity chosen when
/// conjured.) Even Exclusives can't change their affinity once it's been chosen.
///
/// NOTE: This function can only be called by the series minter, and (therefore) only while the
/// series is open. A Wizard that has no affinity when a series is closed will NEVER have an Affinity.
/// BTW- This implies that a minter is responsible for either never minting ELEMENT_NOTSET
/// Wizards, or having some public mechanism for a Wizard owner to set the Affinity after minting.
/// @param wizardId The id of the wizard
/// @param newAffinity The new affinity of the wizard
function setAffinity(uint256 wizardId, uint8 newAffinity) external;
/// @notice A function to be called that conjures a whole bunch of Wizards at once! You know how
/// there's "a pride of lions", "a murder of crows", and "a parliament of owls"? Well, with this
/// here function you can conjure yourself "a stench of Cheeze Wizards"!
///
/// Unsurprisingly, this method can only be called by the registered minter for a Series.
/// @param powers the power level of each wizard
/// @param affinities the Elements of the wizards to create
/// @param owner the address that will own the newly created Wizards
function mintWizards(
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
) external returns (uint256[] memory wizardIds);
/// @notice A function to be called that conjures a series of Wizards in the reserved ID range.
/// @param wizardIds the ID values to use for each Wizard, must be in the reserved range of the current Series
/// @param affinities the Elements of the wizards to create
/// @param powers the power level of each wizard
/// @param owner the address that will own the newly created Wizards
function mintReservedWizards(
uint256[] calldata wizardIds,
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
) external;
/// @notice Sets the metadata values for a list of Wizards. The metadata for a Wizard can only be set once,
/// can only be set by the COO or Minter, and can only be set while the Series is still open. Once
/// a Series is closed, the metadata is locked forever!
/// @param wizardIds the ID values of the Wizards to apply metadata changes to.
/// @param metadata the raw metadata values for each Wizard. This contract does not define how metadata
/// should be interpreted, but it is likely to be a 256-bit hash of a complete metadata package
/// accessible via IPFS or similar.
function setMetadata(uint256[] calldata wizardIds, bytes32[] calldata metadata) external;
/// @notice Returns true if the given "spender" address is allowed to manipulate the given token
/// (either because it is the owner of that token, has been given approval to manage that token)
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
/// @notice Verifies that a given signature represents authority to control the given Wizard ID,
/// reverting otherwise. It handles three cases:
/// - The simplest case: The signature was signed with the private key associated with
/// an external address that is the owner of this Wizard.
/// - The signature was generated with the private key associated with an external address
/// that is "approved" for working with this Wizard ID. (See the Wizard Guild and/or
/// the ERC-721 spec for more information on "approval".)
/// - The owner or approval address (as in cases one or two) is a smart contract
/// that conforms to ERC-1654, and accepts the given signature as being valid
/// using its own internal logic.
///
/// NOTE: This function DOES NOT accept a signature created by an address that was given "operator
/// status" (as granted by ERC-721's setApprovalForAll() functionality). Doing so is
/// considered an extreme edge case that can be worked around where necessary.
/// @param wizardId The Wizard ID whose control is in question
/// @param hash The message hash we are authenticating against
/// @param sig the signature data; can be longer than 65 bytes for ERC-1654
function verifySignature(uint256 wizardId, bytes32 hash, bytes calldata sig) external view;
/// @notice Convienence function that verifies signatures for two wizards using equivalent logic to
/// verifySignature(). Included to save on cross-contract calls in the common case where we
/// are verifying the signatures of two Wizards who wish to enter into a Duel.
/// @param wizardId1 The first Wizard ID whose control is in question
/// @param wizardId2 The second Wizard ID whose control is in question
/// @param hash1 The message hash we are authenticating against for the first Wizard
/// @param hash2 The message hash we are authenticating against for the first Wizard
/// @param sig1 the signature data corresponding to the first Wizard; can be longer than 65 bytes for ERC-1654
/// @param sig2 the signature data corresponding to the second Wizard; can be longer than 65 bytes for ERC-1654
function verifySignatures(
uint256 wizardId1,
uint256 wizardId2,
bytes32 hash1,
bytes32 hash2,
bytes calldata sig1,
bytes calldata sig2) external view;
}
// We use a contract and multiple inheritence to expose this constant.
// It's the best that Solidity offers at the moment.
contract DuelResolverInterfaceId {
/// @notice The erc165 interface ID
bytes4 internal constant _INTERFACE_ID_DUELRESOLVER = 0x41fc4f1e;
}
/// @notice An interface for Contracts that resolve duels between Cheeze Wizards. Abstracting this out
/// into its own interface and instance allows for different tournaments to use
/// different duel mechanics while keeping the core tournament logic unchanged.
contract DuelResolverInterface is DuelResolverInterfaceId, ERC165Interface {
/// @notice Indicates if the given move set is a valid input for this duel resolver.
/// It's important that this method is called before a move set is committed to
/// because resolveDuel() will abort if it the moves are invalid, making it
/// impossible to resolve the duel.
function isValidMoveSet(bytes32 moveSet) public pure returns(bool);
/// @notice Indicates that a particular affinity is a valid input for this duel resolver.
/// Should be called before a Wizard is entered into a tournament. As a rule, Wizard
/// Affinities don't change, so there's not point in checking for each duel.
///
/// @dev This method should _only_ return false for affinities that are
/// known to cause problems with your duel resolver. If your resolveDuel() function
/// can safely work with any affinity value (even if it just ignores the values that
/// it doesn't know about), it should return true.
function isValidAffinity(uint256 affinity) public pure returns(bool);
/// @notice Resolves the duel between two Cheeze Wizards given their chosen move sets, their
/// powers, and each Wizard's affinity. It is the responsibility of the Tournament contract
/// to ensure that ALL Wizards in a Tournament have an affinity value that is compatible with
/// the logic of this DuelResolver. It must also ensure that both move sets are valid before
/// those move sets are locked in, otherwise the duel can never be resolved!
///
/// Returns the amount of power to be transferred from the first Wizard to the second Wizard
/// (which will be a negative number if the second Wizard wins the duel), zero in the case of
/// a tie.
/// @param moveSet1 The move set for the first Wizard. The interpretation and therefore valid
/// values for this are determined by the individual duel resolver.
/// @param moveSet2 The move set for the second Wizard.
function resolveDuel(
bytes32 moveSet1,
bytes32 moveSet2,
uint256 power1,
uint256 power2,
uint256 affinity1,
uint256 affinity2)
public pure returns(int256);
}
/// @title Contract that manages addresses and access modifiers for certain operations.
/// @author Dapper Labs Inc. (https://www.dapperlabs.com)
contract AccessControl {
/// @dev The address of the master administrator account that has the power to
/// update itself and all of the other administrator addresses.
/// The CEO account is not expected to be used regularly, and is intended to
/// be stored offline (i.e. a hardware device kept in a safe).
address public ceoAddress;
/// @dev The address of the "day-to-day" operator of various priviledged
/// functions inside the smart contract. Although the CEO has the power
/// to replace the COO, the CEO address doesn't actually have the power
/// to do "COO-only" operations. This is to discourage the regular use
/// of the CEO account.
address public cooAddress;
/// @dev The address that is allowed to move money around. Kept seperate from
/// the COO because the COO address typically lives on an internet-connected
/// computer.
address payable public cfoAddress;
// Events to indicate when access control role addresses are updated.
event CEOTransferred(address previousCeo, address newCeo);
event COOTransferred(address previousCoo, address newCoo);
event CFOTransferred(address previousCfo, address newCfo);
/// @dev The AccessControl constructor sets the `ceoAddress` to the sender account. Also
/// initializes the COO and CFO to the passed values (CFO is optional and can be address(0)).
/// @param newCooAddress The initial COO address to set
/// @param newCfoAddress The initial CFO to set (optional)
constructor(address newCooAddress, address payable newCfoAddress) public {
_setCeo(msg.sender);
setCoo(newCooAddress);
if (newCfoAddress != address(0)) {
setCfo(newCfoAddress);
}
}
/// @notice Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress, "Only CEO");
_;
}
/// @notice Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress, "Only COO");
_;
}
/// @notice Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress, "Only CFO");
_;
}
function checkControlAddress(address newController) internal view {
require(newController != address(0), "Zero access control address");
require(newController != ceoAddress, "CEO address cannot be reused");
}
/// @notice Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param newCeo The address of the new CEO
function setCeo(address newCeo) external onlyCEO {
checkControlAddress(newCeo);
_setCeo(newCeo);
}
/// @dev An internal utility function that updates the CEO variable and emits the
/// transfer event. Used from both the public setCeo function and the constructor.
function _setCeo(address newCeo) private {
emit CEOTransferred(ceoAddress, newCeo);
ceoAddress = newCeo;
}
/// @notice Assigns a new address to act as the COO. Only available to the current CEO.
/// @param newCoo The address of the new COO
function setCoo(address newCoo) public onlyCEO {
checkControlAddress(newCoo);
emit COOTransferred(cooAddress, newCoo);
cooAddress = newCoo;
}
/// @notice Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param newCfo The address of the new CFO
function setCfo(address payable newCfo) public onlyCEO {
checkControlAddress(newCfo);
emit CFOTransferred(cfoAddress, newCfo);
cfoAddress = newCfo;
}
}
/// @title TournamentTimeAbstract - abstract contract for controlling time for Cheeze Wizards.
/// @notice Time is important in Cheeze Wizards, and there are a variety of different ways of
/// slicing up time that we should clarify here at the outset:
///
/// 1. The tournament is split into three major PHASES:
/// - The first Phase is the Admission Phase. During this time, Wizards can be entered into
/// the tournament with their admission fee, and will be given a power level commensurate
/// with that fee. Their power level can not exceed the base power level encoded into the NFT.
/// No duels take place during this phase.
/// - The second Phase is the Revival Phase. During this time, new Wizards can enter the tournament,
/// eliminated Wizards can be revived, and the dueling commences!
/// - The third phase is the Elimination Phase. It's all duels, all the time. No new Wizards can enter,
/// all eliminations are _final_. It's at this time that the Blue Mold begins to grow, forcing
/// Wizards to engage in battle or be summarily eliminated.
/// - Collectively the phases where Wizards can enter the tournament (i.e. Admission Phase and
/// Revival Phase) are the Enter Phases.
/// - Collectively the phases where Wizards can duel (i.e. Revival Phase and Elimination Phase)
/// are the Battle Phases.
///
/// 2. During the Battle Phases, where Wizards can duel, we break time up into a series of repeating WINDOWS:
/// - The first Window is the Ascension Window. During the Elimination Phase, Ascension Windows are critically
/// important: Any Wizard which is in danger of being eliminated by the next Blue Mold power increase
/// can attempt to Ascend during this time. If multiple Wizards attempt to Ascend, they are paired
/// off into Duels to Exhaustion: A one-time, winner-takes-all battle that sees one Wizard triumphant
/// and the other Wizard eliminated from the tournament. If an odd number of Wizards attempt to Ascend,
/// the last Wizard to attempt to Ascend remains in the Ascension Chamber where they _must_ accept the
/// first duel challenge offered to them in the following Fight Window. During the Revival Phase, the time
/// slice which would be an Ascension Windows is counted as more or less nothing.
/// - The second Window is the Fight Window. This is where all the fun happens! Wizards challenge Wizards,
/// and their duels result in power transfers. But beware! If your power level drops to zero (or below
/// the Blue Mold level), you will be eliminated!
/// - The third Window is the Resolution Window. This is a period of time after the Fight Window equal
/// to the maximum length of a duel. During the Resolution Window, the only action that most Wizards
/// can take is to reveal moves for duels initiated during the Fight Window. However, this is also the
/// time slice during which a successfully Ascending Wizard is able to power up!
/// - The fourth Window is the Culling Window. During the Elimination Phase, the Culling Window is used
/// to permanently remove all Wizards who have been reduced to zero power (are tired), or who have fallen below
/// the power level of the inexorable Blue Mold.
///
/// 3. A complete sequence of four Windows is called a SESSION. During the official Cheeze Wizard tournament,
/// we will set the Session length to as close to 8 hours as possible (while still using blocks as time
/// keeping mechanism), ensuring three Sessions per day. Other Tournaments may have very different time limits.
///
/// A Handy Diagram!
/// ...--|--asc.--|------fight------|--res--|-----cull------|--asc.--|------fight------|--res--|-----cull--...
/// .....|^^^^^^^^^^^^^^^^^^ 1 session ^^^^^^^^^^^^^^^^^^^^^|...
contract TournamentTimeAbstract is AccessControl {
event Paused(uint256 pauseEndingBlock);
/// @dev We pack these parameters into a struct to save storage costs.
struct TournamentTimeParameters {
// The block height at which the tournament begins. Starts in the Admission Phase.
uint48 tournamentStartBlock;
// The block height after which the pause will end.
uint48 pauseEndingBlock;
// The duration (in blocks) of the Admission Phase.
uint32 admissionDuration;
// The duration (in blocks) of the Revival Phase; the Elimination Phase has no time limit.
uint32 revivalDuration;
// The maximum duration (in blocks) between the second commit in a normal duel and when it times out.
// Ascension Duels always time out at the end of the Resolution Phase following the Fight or Ascension
// Window in which they were initiated.
uint32 duelTimeoutDuration;
}
TournamentTimeParameters internal tournamentTimeParameters;
// This probably looks insane, but there is a method to our madness!
//
// Checking which window we are in is something that happens A LOT, especially during duels.
// The naive way of checking this is gas intensive, as it either involves data stored in
// multiple storage slots, or by performing a number of computations for each check. By caching all
// of the data needed to compute if we're in a window in a single struct means that
// we can do the check cost effectively using a single SLOAD. Unfortunately, different windows need different
// data, so we end up storing A LOT of duplicate data. This is a classic example of
// optimizing for one part of the code (fast checking if we're in a window) at the expense of another
// part of the code (overall storage footprint and deployment gas cost). In
// the common case this is a significant improvement in terms of gas usage, over the
// course of an entire Tournament.
// The data needed to check if we are in a given Window
struct WindowParameters {
// The block number that the first window of this type begins
uint48 firstWindowStartBlock;
// A copy of the pause ending block, copied into this storage slot to save gas
uint48 pauseEndingBlock;
// The length of an entire "session" (see above for definitions), ALL windows
// repeat with a period of one session.
uint32 sessionDuration;
// The duration of this window
uint32 windowDuration;
}
WindowParameters internal ascensionWindowParameters;
WindowParameters internal fightWindowParameters;
WindowParameters internal resolutionWindowParameters;
WindowParameters internal cullingWindowParameters;
// Another struct, with another copy of some of the same parameters as above. This time we are
// collecting everything related to computing the power of the Blue Mold into one place.
struct BlueMoldParameters {
uint48 blueMoldStartBlock;
uint32 sessionDuration;
uint32 moldDoublingDuration;
uint88 blueMoldBasePower;
}
BlueMoldParameters internal blueMoldParameters;
constructor(
address _cooAddress,
uint256 tournamentStartBlock,
uint256 admissionDuration,
uint256 revivalDuration,
uint256 ascensionDuration,
uint256 fightDuration,
uint256 cullingDuration,
uint256 duelTimeoutDuration,
uint256 blueMoldBasePower,
uint256 sessionsBetweenMoldDoubling
)
internal AccessControl(_cooAddress, address(0)) {
require(tournamentStartBlock > block.number, "Invalid start time");
// The contract block arithmetic presumes a block number below 2^47,
// so we enforce that constraint here to avoid risk of an overflow.
require(tournamentStartBlock < 1 << 47, "Start block too high");
// Even if you want to have a very fast Tournament, a timeout of fewer than 20 blocks
// is asking for trouble. We would always recommend a value >100.
require(duelTimeoutDuration >= 20, "Timeout too short");
// Rather than checking all of these inputs against zero, we just multiply them all together and exploit
// the fact that if any of them are zero, their product will also be zero.
// Theoretically, you can find five non-zero numbers that multiply to zero because of overflow.
// However, at least one of those numbers would need to be >50 bits long which is large enough that it
// would also be an invalid duration! :P
require(
(admissionDuration * revivalDuration * ascensionDuration * fightDuration * cullingDuration) != 0,
"Time durations must be non-0");
// The Fight Window needs to be at least twice as long as the Duel Timeout. Necessary to
// ensure there is enough time to challenge an Ascending Wizard.
require(fightDuration >= duelTimeoutDuration * 2, "Fight window too short");
// Make sure the Culling Window is at least as big as a Fight Window
require(cullingDuration >= duelTimeoutDuration, "Culling window too short");
uint256 sessionDuration = ascensionDuration + fightDuration + duelTimeoutDuration + cullingDuration;
// Make sure that the end of the Revival Phase coincides with the start of a
// new session. Many of our calculations depend on this fact!
require((revivalDuration % sessionDuration) == 0, "Revival/Session length mismatch");
tournamentTimeParameters = TournamentTimeParameters({
tournamentStartBlock: uint48(tournamentStartBlock),
pauseEndingBlock: uint48(0),
admissionDuration: uint32(admissionDuration),
revivalDuration: uint32(revivalDuration),
duelTimeoutDuration: uint32(duelTimeoutDuration)
});
uint256 firstSessionStartBlock = tournamentStartBlock + admissionDuration;
// NOTE: ascension windows don't begin until after the Revival Phase is over
ascensionWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(firstSessionStartBlock + revivalDuration),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(ascensionDuration)
});
fightWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(firstSessionStartBlock + ascensionDuration),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(fightDuration)
});
resolutionWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(firstSessionStartBlock + ascensionDuration + fightDuration),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(duelTimeoutDuration)
});
// NOTE: The first Culling Window only occurs after the first Revival Phase is over.
uint256 cullingStart = firstSessionStartBlock + revivalDuration + ascensionDuration + fightDuration + duelTimeoutDuration;
cullingWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(cullingStart),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(cullingDuration)
});
// Note: BasicTournament.revive() depends on blueMoldBasePower always being
// positive, so if this constraint somehow ever changes, that function
// will need to be verified for correctness
require(blueMoldBasePower > 0 && blueMoldBasePower < 1<<88, "Invalid mold power");
require(sessionsBetweenMoldDoubling > 0, "The mold must double!");
blueMoldParameters = BlueMoldParameters({
blueMoldStartBlock: uint48(firstSessionStartBlock + revivalDuration),
sessionDuration: uint32(sessionDuration),
moldDoublingDuration: uint32(sessionsBetweenMoldDoubling * sessionDuration),
blueMoldBasePower: uint88(blueMoldBasePower)
});
}
/// @notice Returns true if the current block is in the Revival Phase
function _isRevivalPhase() internal view returns (bool) {
// Copying the stucture into memory once saves gas. Each access to a member variable
// counts as a new read!
TournamentTimeParameters memory localParams = tournamentTimeParameters;
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
return ((block.number >= localParams.tournamentStartBlock + localParams.admissionDuration) &&
(block.number < localParams.tournamentStartBlock + localParams.admissionDuration + localParams.revivalDuration));
}
/// @notice Returns true if the current block is in the Elimination Phase
function _isEliminationPhase() internal view returns (bool) {
// Copying the stucture into memory once saves gas. Each access to a member variable
// counts as a new read!
TournamentTimeParameters memory localParams = tournamentTimeParameters;
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
return (block.number >= localParams.tournamentStartBlock + localParams.admissionDuration + localParams.revivalDuration);
}
/// @dev Returns true if the current block is a valid time to enter a Wizard into the Tournament. As in,
/// it's either the Admission Phase or the Revival Phase.
function _isEnterPhase() internal view returns (bool) {
// Copying the stucture into memory once saves gas. Each access to a member variable
// counts as a new read!
TournamentTimeParameters memory localParams = tournamentTimeParameters;
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
return ((block.number >= localParams.tournamentStartBlock) &&
(block.number < localParams.tournamentStartBlock + localParams.admissionDuration + localParams.revivalDuration));
}
// An internal convenience function that checks to see if we are currently in the Window
// defined by the WindowParameters struct passed as an argument.
function _isInWindow(WindowParameters memory localParams) internal view returns (bool) {
// We are never "in a window" if the contract is paused
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
// If we are before the first window of this type, we are obviously NOT in this window!
if (block.number <= localParams.firstWindowStartBlock) {
return false;
}
// Use modulus to figure out how far we are past the beginning of the most recent window
// of this type
uint256 windowOffset = (block.number - localParams.firstWindowStartBlock) % localParams.sessionDuration;
// If we are in the window, we will be within duration of the start of the most recent window
return windowOffset < localParams.windowDuration;
}
/// @notice Requires the current block is in an Ascension Window
function checkAscensionWindow() internal view {
require(_isInWindow(ascensionWindowParameters), "Only during Ascension Window");
}
/// @notice Requires the current block is in a Fight Window
function checkFightWindow() internal view {
require(_isInWindow(fightWindowParameters), "Only during Fight Window");
}
/// @notice Requires the current block is in a Resolution Window
function checkResolutionWindow() internal view {
require(_isInWindow(resolutionWindowParameters), "Only during Resolution Window");
}
/// @notice Requires the current block is in a Culling Window
function checkCullingWindow() internal view {
require(_isInWindow(cullingWindowParameters), "Only during Culling Window");
}
/// @notice Returns the block number when an Ascension Battle initiated in the current block
/// should time out. This is always the end of the upcoming Resolution Window.
///
/// NOTE: This function is only designed to be called during an Ascension or
/// Fight Window, after we have entered the Elimination Phase.
/// Behaviour at other times is not defined.
function _ascensionDuelTimeout() internal view returns (uint256) {
WindowParameters memory localParams = cullingWindowParameters;
// The end of the next Resolution Window is the same as the start of the next
// Culling Window.
// First we count the number of COMPLETE sessions that will have passed between
// the start of the first Culling Window and the block one full session duration
// past the current block height. We are looking into the future to ensure that
// we with any negative values.
uint256 sessionCount = (block.number + localParams.sessionDuration -
localParams.firstWindowStartBlock) / localParams.sessionDuration;
return localParams.firstWindowStartBlock + sessionCount * localParams.sessionDuration;
}
/// @notice Returns true if there is at least one full duel timeout duration between
/// now and the end of the current Fight Window. To be used to ensure that
/// someone challenging an Ascending Wizard is given the Ascending Wizard
/// enough time to respond.
///
/// NOTE: This function is only designed to be called during a Fight Window,
/// after we have entered the Elimination Phase.
/// Behaviour at other times is not defined.
function canChallengeAscendingWizard() internal view returns (bool) {
// We start by computing the start on the next Resolution Window, using the same
// logic as in _ascensionDuelTimeout().
WindowParameters memory localParams = resolutionWindowParameters;
uint256 sessionCount = (block.number + localParams.sessionDuration -
localParams.firstWindowStartBlock) / localParams.sessionDuration;
uint256 resolutionWindowStart = localParams.firstWindowStartBlock + sessionCount * localParams.sessionDuration;
// Remember that the Resolution Window has the same duration as the duel time out
return resolutionWindowStart - localParams.windowDuration > block.number;
}
/// @notice Returns the power level of the Blue Mold at the current block.
function _blueMoldPower() internal view returns (uint256) {
BlueMoldParameters memory localParams = blueMoldParameters;
if (block.number <= localParams.blueMoldStartBlock) {
return localParams.blueMoldBasePower;
} else {
uint256 moldDoublings = (block.number - localParams.blueMoldStartBlock) / localParams.moldDoublingDuration;
// In the initialization function, we cap the maximum Blue Mold base power to a value under 1 << 88
// (which is the maximum Wizard power level, and would result in all Wizards INSTANTLY being moldy!)
// Here, we cap the number of "mold doublings" to 88. This ensures that the mold power
// can't overflow, while also ensuring that, even if blueMoldBasePower starts at 1
// that it will exceed the max power of any Wizard. This guarantees that the tournament
// will ALWAYS terminate.
if (moldDoublings > 88) {
moldDoublings = 88;
}
return localParams.blueMoldBasePower << moldDoublings;
}
}
modifier duringEnterPhase() {
require(_isEnterPhase(), "Only during Enter Phases");
_;
}
modifier duringRevivalPhase() {
require(_isRevivalPhase(), "Only during Revival Phases");
_;
}
modifier duringAscensionWindow() {
checkAscensionWindow();
_;
}
modifier duringFightWindow() {
checkFightWindow();
_;
}
modifier duringResolutionWindow() {
checkResolutionWindow();
_;
}
modifier duringCullingWindow() {
checkCullingWindow();
_;
}
/// @notice Pauses the Tournament, starting immediately, for a duration specified in blocks.
/// This function can be called if the Tournament is already paused, but only to extend the pause
/// period until at most `(block.number + sessionDuration)`. In other words, the Tournament can't be
/// paused indefinitely unless this function is called periodically, at least once every session length.
///
/// NOTE: This function is reasonably expensive and inefficient because it has to update so many storage
/// variables. This is done intentionally because pausing should be rare and it's far more important
/// to optimize the hot paths (which are the modifiers above).
///
/// @param pauseDuration the number of blocks to pause for. CAN NOT exceed the length of one Session.
function pause(uint256 pauseDuration) public onlyCOO {
uint256 sessionDuration = ascensionWindowParameters.sessionDuration;
// Require all pauses be less than one session in length
require(pauseDuration <= sessionDuration, "Invalid pause duration");
// Figure out when our pause will be done
uint48 newPauseEndingBlock = uint48(block.number + pauseDuration);
uint48 tournamentExtensionAmount = uint48(pauseDuration);
if (block.number <= tournamentTimeParameters.pauseEndingBlock) {
// If we are already paused, we need to adjust the tournamentExtension
// amount to reflect that we are only extending the pause amount, not
// setting it anew
require(tournamentTimeParameters.pauseEndingBlock > newPauseEndingBlock, "Already paused");
tournamentExtensionAmount = uint48(newPauseEndingBlock - tournamentTimeParameters.pauseEndingBlock);
}
// We now need to update all of the various structures where we cached time information
// to make sure they reflect the new information
tournamentTimeParameters.tournamentStartBlock += tournamentExtensionAmount;
tournamentTimeParameters.pauseEndingBlock = newPauseEndingBlock;
ascensionWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
ascensionWindowParameters.pauseEndingBlock = newPauseEndingBlock;
fightWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
fightWindowParameters.pauseEndingBlock = newPauseEndingBlock;
resolutionWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
resolutionWindowParameters.pauseEndingBlock = newPauseEndingBlock;
cullingWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
cullingWindowParameters.pauseEndingBlock = newPauseEndingBlock;
blueMoldParameters.blueMoldStartBlock += tournamentExtensionAmount;
emit Paused(newPauseEndingBlock);
}
function isPaused() public view returns (bool) {
return block.number <= tournamentTimeParameters.pauseEndingBlock;
}
}
// This is kind of a hacky way to expose this constant, but it's the best that Solidity offers!
contract TournamentInterfaceId {
bytes4 internal constant _INTERFACE_ID_TOURNAMENT = 0xbd059098;
}
/// @title Tournament interface, known to GateKeeper
contract TournamentInterface is TournamentInterfaceId, ERC165Interface {
// function enter(uint256 tokenId, uint96 power, uint8 affinity) external payable;
function revive(uint256 wizardId) external payable;
function enterWizards(uint256[] calldata wizardIds, uint88[] calldata powers) external payable;
// Returns true if the Tournament is currently running and active.
function isActive() external view returns (bool);
function powerScale() external view returns (uint256);
}
/// @title A basic Cheeze Wizards Tournament
/// @notice This contract mediates a Tournament between any number of Cheeze Wizards with
/// the following features:
/// - All Wizards who enter the Tournament are required to provide a contribution
/// to the Big Cheeze prize pool that is directly proportional to their power
/// level. There is no way for some Wizards to have a power level that is disproprtional
/// to their pot contribution amount; not even for the Tournament creators.
/// - All Tournaments created with this contract follow the time constraints set out in the
/// TournamentTimeAbstract contract. While different Tournament instances might run more
/// quickly or more slowly than others, the basic cadence of the Tournament is consistent
/// across all instances.
/// - The Tournament contract is designed such that, once the contract is set up, that
/// all participants can trustlessly enjoy the Tournament without fear of being ripped
/// off by the organizers. Some care needs to be taken _before_ you enter your Wizard
/// in the Tournament (including ensuring that you are actually entering into a copy
/// of this Tournament contract that hasn't been modified!), but once your Wizard has
/// been entered, you can have confidence that the rules of the contest will be followed
/// correctly, without fear of manipulation or fraud on the part of the contest creators.
contract BasicTournament is TournamentInterface, TournamentTimeAbstract, WizardConstants,
DuelResolverInterfaceId {
// A Duel officially starts (both commits are locked in on-chain)
event DuelStart(
bytes32 duelId,
uint256 wizardId1,
uint256 wizardId2,
uint256 timeoutBlock,
bool isAscensionBattle
);
// A Duel resolves normally, powers are post-resolution values
event DuelEnd(
bytes32 duelId,
uint256 wizardId1,
uint256 wizardId2,
bytes32 moveSet1,
bytes32 moveSet2,
uint256 power1,
uint256 power2
);
// A Duel times out, powers are post-resolution values
event DuelTimeOut(bytes32 duelId, uint256 wizardId1, uint256 wizardId2, uint256 power1, uint256 power2);
// A Wizard has been formally eliminated. Note that Elimination can only happen in the Elimination phase, and
// is NOT necessarily associated with a Wizard going to power zero.
event WizardElimination(uint256 wizardId);
// A Wizard in the "danger zone" has opted to try to Ascend
event AscensionStart(uint256 wizardId);
// A Wizard tried to Ascend when someone was in the Ascension Chamber; locked into a fight with each other.
event AscensionPairUp(uint256 wizardId1, uint256 wizardId2);
// A Wizard in the Ascension Chamber wasn't challenged during the Fight Window, their power triples!
event AscensionComplete(uint256 wizardId, uint256 power);
// A Wizard has been revived; power is the revival amount chosen (above Blue Mold level, below maxPower)
event Revive(uint256 wizId, uint256 power);
// One Wizard sent all of its power to another. "givingWizId" has zero power after this
event PowerGifted(uint256 givingWizId, uint256 receivingWizId, uint256 amountGifted);
// The winner (or one of the winners) has claimed their portion of the prize.
event PrizeClaimed(uint256 claimingWinnerId, uint256 prizeAmount);
// Used to prefix signed data blobs to prevent replay attacks
byte internal constant EIP191_PREFIX = byte(0x19);
byte internal constant EIP191_VERSION_DATA = byte(0);
/// @dev The ratio between the cost of a Wizard (in wei) and the power of the wizard.
/// power = cost / powerScale
/// cost = power * powerScale
uint256 public powerScale;
/// @dev The maximimum power level attainable by a Wizard
uint88 internal constant MAX_POWER = uint88(-1);
// Address of the GateKeeper, likely to be a smart contract, but we don't care if it is
// TODO: Update this address once the Gate Keeper is deployed.
address internal constant gateKeeper = address(0);
// The Wizard Guild contract. This is a variable so subclasses can modify it for
// testing, but by default it cannot change from this default.
// TODO: Update this address once the Wizard Guild is deployed.
WizardGuildInterface internal constant wizardGuild = WizardGuildInterface(address(0xb4aCd2c618EB426a8E195cCA2194c0903372AC0d));
// The Duel Resolver contract
DuelResolverInterface public duelResolver;
/// @notice Power and other data while the Wizard is participating in the Tournament
/// @dev fits into two words
struct BattleWizard {
/// @notice the wizards current power
uint88 power;
/// @notice the highest power a Wizard ever reached during a tournament
uint88 maxPower;
/// @notice a nonce value incremented when the Wizard's power level changes
uint32 nonce;
/// @notice a cached copy of the affinity of the Wizard - how handy!
uint8 affinity;
/// @notice The "id" of the Duel the Wizard is currently engaged in (which is actually
/// the hash of the duel's parameters, see _beginDuel().)
bytes32 currentDuel;
}
mapping(uint256 => BattleWizard) internal wizards;
/// @notice The total number of Wizards in this tournament. Goes up as new Wizards are entered
/// (during the Enter Phases), and goes down as Wizards get eliminated. We know we can
/// look for winners once this gets down to 5 or less!
uint256 internal remainingWizards;
/// @notice A structure used to keep track of one-sided commitments that have been made on chain.
/// We anticipate most duels will make use of the doubleCommitment mechanism (because it
/// uses less gas), but that requires a trusted intermediary, so we provide one-sided commitments
/// for fully trustless interactions.
struct SingleCommitment {
uint256 opponentId;
bytes32 commitmentHash;
}
// Key is Wizard ID, value is their selected opponent and their commitment hash
mapping(uint256 => SingleCommitment) internal pendingCommitments;
/// @notice A mapping that keeps track of one-sided reveals that have been made on chain. Like one-sided
/// commits, we expect one-sided reveals to be rare. But not quite as rare! If a player takes too
/// long to submit their reveal, their opponent will want to do a one-sided reveal to win the duel!
/// First key is Duel ID, second key is Wizard ID, value is the revealed moveset. (This structure
/// might seem odd if you aren't familiar with how Solidity handles storage-based mappings. If you
/// are confused, it's worth looking into; it's non-obvious, but quite efficient and clever!)
mapping(bytes32 => mapping(uint256 => bytes32)) internal revealedMoves;
// There can be at most 1 ascending Wizard at a time, who's ID is stored in this variable. If a second
// Wizard tries to ascend when someone is already in the chamber, we make 'em fight!
uint256 internal ascendingWizardId;
// If there is a Wizard in the growth chamber when a second Wizard attempts to ascend, those two
// Wizards are paired off into an Ascension Battle. This dictionary keeps track of the IDs of these
// paired off Wizards. Wizard 1's ID maps to Wizard 2, and vice versa. (This means that each Ascension
// Battle requires the storage of two words, which is kinda lame... ¯\_(ツ)_/¯ )
mapping(uint256 => uint256) internal ascensionOpponents;
// If there are an odd number of Wizards that attempt to ascend, one of them will be left in the
// Ascension Chamber when the Fighting Window starts. ANY Wizard can challenge them, and they MUST
// accept! This structure stores the commitment from the first challenger (if there is one).
//
// NOTE: The fields in this version of the structure are used subtly different than in the pending
// commitments mapping. In pendingCommitments, the opponentId is the ID of the person you want to fight
// and the commitmentHash is the commitment of YOUR moves. In the ascensionCommitment variable, the
// opponentId is the Wizard that has challenged the ascending Wizard, and the commitmentHash is their
// own moves. It makes sense in context, but it is technically a semantic switch worth being explicit about.
SingleCommitment internal ascensionCommitment;
struct Duel {
uint128 timeout;
bool isAscensionBattle;
}
/// @notice All of the currently active Duels, keyed by Duel ID
mapping(bytes32 => Duel) internal duels;
constructor(
address cooAddress_,
address duelResolver_,
uint256 powerScale_,
uint256 tournamentStartBlock_,
uint256 admissionDuration_,
uint256 revivalDuration_,
uint256 ascensionDuration_,
uint256 fightDuration_,
uint256 cullingDuration_,
uint256 blueMoldBasePower_,
uint256 sessionsBetweenMoldDoubling_,
uint256 duelTimeoutBlocks_
)
public
TournamentTimeAbstract(
cooAddress_,
tournamentStartBlock_,
admissionDuration_,
revivalDuration_,
ascensionDuration_,
fightDuration_,
cullingDuration_,
duelTimeoutBlocks_,
blueMoldBasePower_,
sessionsBetweenMoldDoubling_
)
{
duelResolver = DuelResolverInterface(duelResolver_);
require(
duelResolver_ != address(0) &&
duelResolver.supportsInterface(_INTERFACE_ID_DUELRESOLVER), "Invalid DuelResolver");
powerScale = powerScale_;
}
/// @notice We allow this contract to accept any payments. All Eth sent in this way
/// automatically becomes part of the prize pool. This is useful in cases
/// where the Tournament organizers want to "seed the pot" with more funds
/// than are contributed by the players.
function() external payable {}
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return
interfaceId == this.supportsInterface.selector || // ERC165
interfaceId == _INTERFACE_ID_TOURNAMENT; // Tournament
}
/// @notice Returns true if the Tournament is currently active.
///
/// NOTE: This will return false (not active) either before the Tournament
/// begins (before any Wizards enter), or after it is over (after all
/// Wizards have been eliminated.) It also considers a Tournament inactive
/// if 200 * blueWallDoubling blocks have passed. (After 100 doublings
/// ALL of the Wizards will have subcumbed to the Blue Wall, and another
/// 100 doublings should be enough time for the winners to withdraw their
/// winnings. Anything left after that is fair game for the GateKeeper to take.)
function isActive() public view returns (bool) {
uint256 maximumTournamentLength = blueMoldParameters.moldDoublingDuration * 200;
if (block.number > blueMoldParameters.blueMoldStartBlock + maximumTournamentLength) {
return false;
} else {
return remainingWizards != 0;
}
}
// NOTE: This might seem a like a slightly odd pattern. Typical smart contract code
// (including other smart Contracts that are part of Cheeze Wizards) would
// just include the require() statement in the modifier itself instead of
// creating an additional function.
//
// Unforunately, this contract is very close to the maximum size limit
// for Ethereum (which is 24576 bytes, as per EIP-170). Modifiers work by
// more-or-less copy-and-pasting the code in them into the functions they
// decorate. It turns out that copying these modifiers (especially the
// contents of checkController() into every function that uses them adds
// up to a very large amount of space. By defining the modifier to be
// no more than a function call, we can save several KBs of contract size
// at a very small gas cost (an internal branch is just 10 gas)).
function checkGateKeeper() internal view {
require(msg.sender == gateKeeper, "Only GateKeeper can call");
}
// Modifier for functions only exposed to the GateKeeper
modifier onlyGateKeeper() {
checkGateKeeper();
_;
}
function checkExists(uint256 wizardId) internal view {
require(wizards[wizardId].maxPower != 0, "Wizard does not exist");
}
// Modifier to ensure a specific Wizard is currently entered into the Tournament
modifier exists(uint256 wizardId) {
checkExists(wizardId);
_;
}
function checkController(uint256 wizardId) internal view {
require(wizards[wizardId].maxPower != 0, "Wizard does not exist");
require(wizardGuild.isApprovedOrOwner(msg.sender, wizardId), "Must be Wizard controller");
}
// Modifier for functions that only the owner (or an approved operator) should be able to call
// Also checks that the Wizard exists!
modifier onlyWizardController(uint256 wizardId) {
checkController(wizardId);
_;
}
/// @notice A function to get the current state of the Wizard, includes the computed properties:
/// ascending (is this Wizard in the ascension chamber), ascensionOpponent (the ID of
/// an ascensionChallenger, if any) molded (this Wizard's power below the Blue Mold power
/// level), and ready (see the isReady() method for definition). You can tell if a Wizard
/// is in a battle by checking "currentDuel" against 0.
function getWizard(uint256 wizardId) public view exists(wizardId) returns(
uint256 affinity,
uint256 power,
uint256 maxPower,
uint256 nonce,
bytes32 currentDuel,
bool ascending,
uint256 ascensionOpponent,
bool molded,
bool ready
) {
BattleWizard memory wizard = wizards[wizardId];
affinity = wizard.affinity;
power = wizard.power;
maxPower = wizard.maxPower;
nonce = wizard.nonce;
currentDuel = wizard.currentDuel;
ascending = ascendingWizardId == wizardId;
ascensionOpponent = ascensionOpponents[wizardId];
molded = _blueMoldPower() > wizard.power;
ready = _isReady(wizardId, wizard);
}
/// @notice A finger printing function to capture the important state data about a Wizard into
/// a secure hash. This is especially useful during sales and trading to be sure that the Wizard's
/// state hasn't changed materially between the time the trade/purchase decision was made and
/// when the actual transfer is executed on-chain.
function wizardFingerprint(uint256 wizardId) external view returns (bytes32) {
(uint256 affinity,
uint256 power,
uint256 maxPower,
uint256 nonce,
bytes32 currentDuel,
bool ascending,
uint256 ascensionOpponent,
bool molded,
) = getWizard(wizardId);
uint256 pendingOpponent = pendingCommitments[wizardId].opponentId;
// Includes all Wizard state (including computed properties) plus the Wizard ID
// TODO: remove all pending commitment code
return keccak256(
abi.encodePacked(
wizardId,
affinity,
power,
maxPower,
nonce,
currentDuel,
ascending,
ascensionOpponent,
molded,
pendingOpponent
));
}
/// @notice Returns true if a Wizard is "ready", meaning it can participate in a battle, ascension, or power
/// transfer. A "ready" Wizard is not ascending, not battling, not moldy, hasn't committed to an ascension
/// battle, and has a valid affinity.
function isReady(uint256 wizardId) public view exists(wizardId) returns (bool) {
BattleWizard memory wizard = wizards[wizardId];
return _isReady(wizardId, wizard);
}
/// @notice An internal version of the isReady function that leverages a BattleWizard struct
/// that is already in memory
function _isReady(uint256 wizardId, BattleWizard memory wizard) internal view returns (bool) {
// IMPORTANT NOTE: oneSidedCommit() needs to recreate 90% of this logic, because it needs to check to
// see if a Wizard is ready, but it allows the Wizard to have an ascension opponent. If you make any
// changes this this function, you should double check that the same edit doesn't need to be made
// to oneSidedCommit().
return ((wizardId != ascendingWizardId) &&
(ascensionOpponents[wizardId] == 0) &&
(ascensionCommitment.opponentId != wizardId) &&
(_blueMoldPower() <= wizard.power) &&
(wizard.affinity != ELEMENT_NOTSET) &&
(wizard.currentDuel == 0));
}
/// @notice The function called by the GateKeeper to enter wizards into the tournament. Only the GateKeeper can
/// call this function, meaning that the GateKeeper gets to decide who can enter. However! The Tournament
/// enforces that ALL Wizards that are entered into the Tournament have paid the same pro-rata share of
/// the prize pool as matches their starting power. Additionally, the starting power for each Wizard
/// in the Tournament can't exceed the innate power of the Wizard when it was created. This is done to
/// ensure the Tournament is possible.
/// @param wizardIds The IDs of the Wizards to enter into the Tournament, can be length 1.
/// @param powers The list of powers for each of the Wizards (one-to-one mapping by index).
function enterWizards(uint256[] calldata wizardIds, uint88[] calldata powers) external payable duringEnterPhase onlyGateKeeper {
require(wizardIds.length == powers.length, "Mismatched parameter lengths");
uint256 totalCost = 0;
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
uint88 power = powers[i];
require(wizards[wizardId].maxPower == 0, "Wizard already in tournament");
(, uint88 innatePower, uint8 affinity, ) = wizardGuild.getWizard(wizardId);
require(power <= innatePower, "Power exceeds innate power");
wizards[wizardId] = BattleWizard({
power: power,
maxPower: power,
nonce: 0,
affinity: affinity,
currentDuel: 0
});
totalCost += power * powerScale;
}
remainingWizards += wizardIds.length;
require(msg.value >= totalCost, "Insufficient funds");
}
/// @dev Brings a tired Wizard back to fightin' strength. Can only be used during the revival
/// phase. The buy-back can be to any power level between the Blue Wall power (at the low end)
/// and the previous max power achived by this Wizard in this tournament. This does mean a revival
/// can bring a Wizard back above their innate power! The contribution into the pot MUST be equivalent
/// to the cost that would be needed to bring in a new Wizard at the same power level. Can only
/// be called by the GateKeeper to allow the GateKeeper to manage the pot contribution rate and
/// potentially apply other rules or requirements to revival.
function revive(uint256 wizardId) external payable exists(wizardId) duringRevivalPhase onlyGateKeeper {
BattleWizard storage wizard = wizards[wizardId];
uint88 maxPower = wizard.maxPower;
uint88 revivalPower = uint88(msg.value / powerScale);
require((revivalPower > _blueMoldPower()) && (revivalPower <= maxPower), "Invalid power level");
require(wizard.power == 0, "Can only revive tired Wizards");
// There is no scenario in which a Wizard can be "not ready" and have a zero power.
// require(isReady(wizardId), "Can't revive a busy Wizard");
wizard.power = revivalPower;
wizard.nonce += 1;
emit Revive(wizardId, revivalPower);
}
/// @notice Updates the cached value of a Wizard's affinity with the value from the Wizard Guild.
/// Only useful for Exclusive Wizards that initially have no elemental affinity, and which
/// is then selected by the owner. When the Wizard enters the Tournament it might not have
/// it's affinity set yet, and this will copy the affinity from the Guild contract if it's
/// been updated. Can be called by anyone since it can't be abused.
/// @param wizardId The id of the Wizard to update
function updateAffinity(uint256 wizardId) external exists(wizardId) {
(, , uint8 newAffinity, ) = wizardGuild.getWizard(wizardId);
BattleWizard storage wizard = wizards[wizardId];
require(wizard.affinity == ELEMENT_NOTSET, "Affinity already updated");
wizard.affinity = newAffinity;
}
function startAscension(uint256 wizardId) external duringAscensionWindow onlyWizardController(wizardId) {
BattleWizard memory wizard = wizards[wizardId];
require(_isReady(wizardId, wizard), "Can't ascend a busy wizard!");
require(wizard.power < _blueMoldPower() * 2, "Not eligible for ascension");
if (ascendingWizardId != 0) {
// there is already a Wizard ascending! Pair up the incoming Wizard with the
// Wizard in the Ascension Chamber and make them fight it out!
ascensionOpponents[ascendingWizardId] = wizardId;
ascensionOpponents[wizardId] = ascendingWizardId;
emit AscensionPairUp(ascendingWizardId, wizardId);
// Empty out the Ascension Chamber for the next Ascension
ascendingWizardId = 0;
} else {
// the chamber is empty, get in!
ascendingWizardId = wizardId;
emit AscensionStart(wizardId);
}
}
function _checkChallenge(uint256 challengerId, uint256 recipientId) internal view {
require(pendingCommitments[challengerId].opponentId == 0, "Pending battle already exists");
require(challengerId != recipientId, "Cannot duel oneself!");
}
/// @notice Any live Wizard can challenge an ascending Wizard during the fight phase. They must
/// provide a commitment of their moves (which is totally reasonable, since they know
/// exactly who they will be fighting!)
function challengeAscending(uint256 wizardId, bytes32 commitment) external duringFightWindow onlyWizardController(wizardId) {
require(ascensionCommitment.opponentId == 0, "Wizard already challenged");
_checkChallenge(wizardId, ascendingWizardId);
// Ascension Battles MUST come well before the end of the fight window to give the
// ascending Wizard a chance to respond with their own commitment.
require(canChallengeAscendingWizard(), "Challenge too late");
BattleWizard memory wizard = wizards[wizardId];
require(_isReady(wizardId, wizard), "Wizard not ready");
// We don't need to call isReady() on the ascendingWizard: It's definitionally ready for a challenge!
// Store a pending commitment that the ascending Wizard can accept
ascensionCommitment = SingleCommitment({opponentId: wizardId, commitmentHash: commitment});
}
/// @notice Allows the Ascending Wizard to respond to an ascension commitment with their own move commitment,
// thereby starting an Ascension Battle.
function acceptAscensionChallenge(bytes32 commitment) external duringFightWindow onlyWizardController(ascendingWizardId) {
uint256 challengerId = ascensionCommitment.opponentId;
require(challengerId != 0, "No challenge to accept");
if (challengerId < ascendingWizardId) {
_beginDuel(challengerId, ascendingWizardId, ascensionCommitment.commitmentHash, commitment, true);
} else {
_beginDuel(ascendingWizardId, challengerId, commitment, ascensionCommitment.commitmentHash, true);
}
// The duel has begun! THERE CAN BE ONLY ONE!!!
delete ascensionCommitment;
delete ascendingWizardId;
}
/// @notice Completes the Ascension for the Wizard in the Ascension Chamber. Note that this can only be called
/// during a Resolution Window, and a Wizard can only enter the Ascension Chamber during the Ascension Window,
/// and there is _always_ a Fight Window between the Ascension Window and the Resolution Window. In other
/// words, there is a always a chance for a challenger to battle the Ascending Wizard before the
/// ascension can complete.
function completeAscension() public duringResolutionWindow {
require(ascendingWizardId != 0, "No Wizard to ascend");
BattleWizard storage ascendingWiz = wizards[ascendingWizardId];
if (ascensionCommitment.opponentId != 0) {
// Someone challenged the ascending Wizard, but the ascending Wizard didn't fight!
// You. Are. Outtahere!
ascendingWiz.power = 0;
}
else {
// Oh lucky day! The Wizard survived a complete fight cycle without any challengers
// coming along! Let's just triple their power.
//
// A note to the naive: THIS WILL NEVER ACTUALLY HAPPEN.
_updatePower(ascendingWiz, ascendingWiz.power * 3);
}
ascendingWiz.nonce += 1;
emit AscensionComplete(ascendingWizardId, ascendingWiz.power);
ascendingWizardId = 0;
}
function oneSidedCommit(uint256 committingWizardId, uint256 otherWizardId, bytes32 commitment)
external duringFightWindow onlyWizardController(committingWizardId) exists(otherWizardId)
{
_checkChallenge(committingWizardId, otherWizardId);
bool isAscensionBattle = false;
if ((ascensionOpponents[committingWizardId] != 0) || (ascensionOpponents[otherWizardId] != 0)) {
require(
(ascensionOpponents[committingWizardId] == otherWizardId) &&
(ascensionOpponents[otherWizardId] == committingWizardId), "Must resolve Ascension Battle");
isAscensionBattle = true;
}
BattleWizard memory committingWiz = wizards[committingWizardId];
BattleWizard memory otherWiz = wizards[otherWizardId];
// Ideally, we'd use the isReady() function here, but it will return false if the caller has an
// ascension opponent, which, of course, our Wizards just might!
require(
(committingWizardId != ascendingWizardId) &&
(ascensionCommitment.opponentId != committingWizardId) &&
(_blueMoldPower() <= committingWiz.power) &&
(committingWiz.affinity != ELEMENT_NOTSET) &&
(committingWiz.currentDuel == 0), "Wizard not ready");
require(
(otherWizardId != ascendingWizardId) &&
(ascensionCommitment.opponentId != otherWizardId) &&
(_blueMoldPower() <= otherWiz.power) &&
(otherWiz.affinity != ELEMENT_NOTSET) &&
(otherWiz.currentDuel == 0), "Wizard not ready.");
SingleCommitment memory otherCommitment = pendingCommitments[otherWizardId];
if (otherCommitment.opponentId == 0) {
// The other Wizard does not currently have any pending commitments, we will store a
// pending commitment so that the other Wizard can pick it up later.
pendingCommitments[committingWizardId] = SingleCommitment({opponentId: otherWizardId, commitmentHash: commitment});
} else if (otherCommitment.opponentId == committingWizardId) {
// We've found a matching commitment! Be sure to order them correctly...
if (committingWizardId < otherWizardId) {
_beginDuel(committingWizardId, otherWizardId, commitment, otherCommitment.commitmentHash, isAscensionBattle);
} else {
_beginDuel(otherWizardId, committingWizardId, otherCommitment.commitmentHash, commitment, isAscensionBattle);
}
delete pendingCommitments[otherWizardId];
if (isAscensionBattle) {
delete ascensionOpponents[committingWizardId];
delete ascensionOpponents[otherWizardId];
}
}
else {
revert("Opponent has a pending challenge");
}
}
function cancelCommitment(uint256 wizardId) external onlyWizardController(wizardId) {
require(ascensionOpponents[wizardId] == 0, "Can't cancel Ascension Battle");
delete pendingCommitments[wizardId];
}
/// @notice Commits two Wizards into a duel with a single transaction. Both Wizards must be "ready"
/// (not ascending, not battling, not moldy, and having a valid affinity), and it must be during a
/// Fight Window.
/// @dev A note on implementation: Each duel is identified by a hash that combines both Wizard IDs,
/// both Wizard nonces, and both commits. Just the IDs and nonces are sufficient to ensure a unique
/// identifier of the duel, but by including the commits in the hash, we don't need to store the commits
/// on-chain (which is pretty expensive, given that they each take up 32 bytes). This does mean that
/// the duel resolution functions require the caller to pass in both commits in order to be resolved, but
/// the commit data is publicly available. Overall, this results in a pretty significant gas savings.
///
/// Earlier versions of this function provided convenience functionality, such as checking to see if a
/// Wizard was ready to ascend, or needed to be removed from a timed-out duel before starting this duel.
/// Each of those checks took more gas, required more code, and ultimately just tested conditions that are
/// trivial to check off-chain (where code is cheap and gas is for cars). This results in clearer
/// on-chain code, and very little extra effort off-chain.
/// @param wizardId1 The id of the 1st wizard
/// @param wizardId2 The id of the 2nd wizard
/// @param commit1 The commitment hash of the 1st Wizard's moves
/// @param commit2 The commitment hash of the 2nd Wizard's moves
/// @param sig1 The signature corresponding to wizard1
/// @param sig2 The signature corresponding to wizard2
function doubleCommit(
uint256 wizardId1,
uint256 wizardId2,
bytes32 commit1,
bytes32 commit2,
bytes calldata sig1,
bytes calldata sig2) external duringFightWindow returns (bytes32 duelId) {
// Ideally, we'd use the exists() modifiers instead of this code, but doing so runs over
// Solidity's stack limit
checkExists(wizardId1);
checkExists(wizardId2);
// The Wizard IDs must be strictly in ascending order so that we don't treat a battle betwen
// "wizard 3 and wizard 5" as different than the battle between "wizard 5 and wizard 3".
// This also ensures that a Wizards isn't trying to duel itself!
require(wizardId1 < wizardId2, "Wizard IDs must be ordered");
bool isAscensionBattle = false;
if ((ascensionOpponents[wizardId1] != 0) || (ascensionOpponents[wizardId2] != 0)) {
require(
(ascensionOpponents[wizardId1] == wizardId2) &&
(ascensionOpponents[wizardId2] == wizardId1), "Must resolve Ascension Battle");
isAscensionBattle = true;
// We can safely delete the ascensionOppenents values now because either this function
// will culminate in a committed duel, or it will revert entirely. It also lets us
// use the _isReady() convenience function (which treats a Wizard with a non-zero
// ascension opponent as not ready).
delete ascensionOpponents[wizardId1];
delete ascensionOpponents[wizardId2];
}
// Get in-memory copies of the wizards
BattleWizard memory wiz1 = wizards[wizardId1];
BattleWizard memory wiz2 = wizards[wizardId2];
require(_isReady(wizardId1, wiz1) && _isReady(wizardId2, wiz2), "Wizard not ready");
// Check that the signatures match the duel data and commitments
bytes32 signedHash1 = _signedHash(wizardId1, wizardId2, wiz1.nonce, wiz2.nonce, commit1);
bytes32 signedHash2 = _signedHash(wizardId1, wizardId2, wiz1.nonce, wiz2.nonce, commit2);
wizardGuild.verifySignatures(wizardId1, wizardId2, signedHash1, signedHash2, sig1, sig2);
// If both signatures have passed, we can begin the duel!
duelId = _beginDuel(wizardId1, wizardId2, commit1, commit2, isAscensionBattle);
// Remove any potential commitments so that they won't be reused
delete pendingCommitments[wizardId1];
delete pendingCommitments[wizardId2];
}
/// @notice An internal utility function that computes the hash that is used for the commitment signature
/// from each Wizard.
function _signedHash(uint256 wizardId1, uint256 wizardId2, uint32 nonce1, uint32 nonce2, bytes32 commit)
internal view returns(bytes32)
{
return keccak256(
abi.encodePacked(
EIP191_PREFIX,
EIP191_VERSION_DATA,
this,
wizardId1,
wizardId2,
nonce1,
nonce2,
commit
));
}
/// @notice The internal utility function to create the duel structure on chain, requires Commitments
/// from both Wizards.
function _beginDuel(uint256 wizardId1, uint256 wizardId2, bytes32 commit1, bytes32 commit2, bool isAscensionBattle)
internal returns (bytes32 duelId)
{
// Get a reference to the Wizard objects in storage
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
// Compute a unique ID for this battle, this ID can't be reused because we strictly increase
// the nonce for each Wizard whenever a battle is recreated. (Includes the contract address
// to avoid replay attacks between different tournaments).
duelId = keccak256(
abi.encodePacked(
this,
wizardId1,
wizardId2,
wiz1.nonce,
wiz2.nonce,
commit1,
commit2
));
// Store the duel ID in each Wizard, to mark the fact that they are fighting
wiz1.currentDuel = duelId;
wiz2.currentDuel = duelId;
// Keep track of the timeout for this duel
uint256 duelTimeout;
if (isAscensionBattle) {
// Ascension Battles always last for a while after the current fight window to ensure
// both sides have a well-defined timeframe for revealing their moves (Ascension Battles)
// are inherently more asynchronous than normal battles.
duelTimeout = _ascensionDuelTimeout();
} else {
// Normal battles just timeout starting .... NOW!
duelTimeout = block.number + tournamentTimeParameters.duelTimeoutDuration;
}
duels[duelId] = Duel({timeout: uint128(duelTimeout), isAscensionBattle: isAscensionBattle});
emit DuelStart(duelId, wizardId1, wizardId2, duelTimeout, isAscensionBattle);
}
/// @notice Reveals the moves for one of the Wizards in a duel. This should be called rarely, but
/// is necessary in order to resolve a duel where one player is unwilling or unable to reveal
/// their moves (also useful if a coordinating intermediary is unavailable or unwanted for some reason).
/// It's worth noting that this method doesn't check any signatures or filter on msg.sender because
/// it is cryptographically impossible for someone to submit a moveset and salt that matches the
/// commitment (which was signed, don't forget!).
///
/// Note: This function doens't need exists(wizardId) because an eliminated Wizard would have
/// currentDuel == 0
/// @param committingWizardId The Wizard whose moves are being revealed
/// @param commit A copy of the commitment used previously, not stored on-chain to save gas
/// @param moveSet The revealed move set
/// @param salt The salt used to secure the commitment hash
/// @param otherWizardId The other Wizard in this battle
/// @param otherCommit The other Wizard's commitment, not stored on-chain to save gas
function oneSidedReveal(
uint256 committingWizardId,
bytes32 commit,
bytes32 moveSet,
bytes32 salt,
uint256 otherWizardId,
bytes32 otherCommit) external
{
BattleWizard memory wizard = wizards[committingWizardId];
BattleWizard memory otherWizard = wizards[otherWizardId];
bytes32 duelId = wizard.currentDuel;
require(duelId != 0, "Wizard not dueling");
// Check that the passed data matches the duel hash
bytes32 computedDuelId;
// Make sure we compute the duel ID with the Wizards sorted in ascending order
if (committingWizardId < otherWizardId) {
computedDuelId = keccak256(
abi.encodePacked(
this,
committingWizardId,
otherWizardId,
wizard.nonce,
otherWizard.nonce,
commit,
otherCommit
));
} else {
computedDuelId = keccak256(
abi.encodePacked(
this,
otherWizardId,
committingWizardId,
otherWizard.nonce,
wizard.nonce,
otherCommit,
commit
));
}
require(computedDuelId == duelId, "Invalid duel data");
// Confirm that the revealed data matches the commitment
require(keccak256(abi.encodePacked(moveSet, salt)) == commit, "Moves don't match commitment");
// We need to verify that the provided moveset is valid here. Otherwise the duel resolution will
// fail later, and the duel can never be resolved. We treat a _valid_ commit/reveal of an _invalid_
// moveset as being equivalent of not providing a reveal (which is subject to automatic loss). I mean,
// you really should have known better!
require(duelResolver.isValidMoveSet(moveSet), "Invalid moveset");
if (revealedMoves[duelId][otherWizardId] != 0) {
// We have the revealed moves for the other Wizard also, we can resolve the duel now
if (committingWizardId < otherWizardId) {
_resolveDuel(duelId, committingWizardId, otherWizardId, moveSet, revealedMoves[duelId][otherWizardId]);
} else {
_resolveDuel(duelId, otherWizardId, committingWizardId, revealedMoves[duelId][otherWizardId], moveSet);
}
}
else {
require(block.number < duels[duelId].timeout, "Duel expired");
// Store our revealed moves for later resolution
revealedMoves[duelId][committingWizardId] = moveSet;
}
}
/// @notice Reveals the moves for both Wizards at once, saving lots of gas and lowering the number
/// of required transactions. As with oneSidedReveal(), no authentication is required other
/// than matching the reveals to the commits. It is not an error if oneSidedReveal is called
/// and then doubleReveal, although we do ignore the previous one-sided reveal if it exists.
/// The _resolvedDuel utility function will clean up any cached revealedMoves for BOTH Wizards.
///
/// NOTE: As with the doubleCommit() method, the Wizards must be provided in _strict_ ascending
/// order for this function to work correctly.
///
/// NOTE: This function will fail if _either_ of the Wizards have submitted an invalid moveset.
/// The correct way of handling this situation is to use oneSidedReveal() (if one moveset is valid
/// and the other is not) and then let the Battle timeout, or -- if both movesets are invalid --
/// don't do any reveals and let the Battle timeout.
///
/// Note: This function doens't need exists(wizardId1) exists(wizardId2) because an
/// eliminated Wizard would have currentDuel == 0
/// @param wizardId1 The id of the 1st wizard
/// @param wizardId2 The id of the 2nd wizard
/// @param commit1 A copy of the 1st Wizard's commitment, not stored on-chain to save gas
/// @param commit2 A copy of the 2nd Wizard's commitment, not stored on-chain to save gas
/// @param moveSet1 The plaintext reveal (moveset) of the 1st wizard
/// @param moveSet2 The plaintext reveal (moveset) of the 2nd wizard
/// @param salt1 The secret salt of the 1st wizard
/// @param salt2 The secret salt of the 2nd wizard
function doubleReveal(
uint256 wizardId1,
uint256 wizardId2,
bytes32 commit1,
bytes32 commit2,
bytes32 moveSet1,
bytes32 moveSet2,
bytes32 salt1,
bytes32 salt2) external
{
// Get a reference to the Wizard objects in storage
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
// In order to match the duel ID generated by the commit functions, the Wizard IDs must be strictly
// in ascending order. However! We don't actually check that here because that just wastes gas
// to perform a check that the duel ID comparison below will have to do anyway. But, we're leaving
// this commented out here as a reminder...
// require(wizardId1 < wizardId2, "Wizard IDs must be ordered");
// Confirm that the duel data passed into the function matches the duel ID in the Wizard
bytes32 duelId = keccak256(
abi.encodePacked(
this,
wizardId1,
wizardId2,
wiz1.nonce,
wiz2.nonce,
commit1,
commit2
));
// NOTE: We don't actually need to check the currentDuel field of the other Wizard because
// we trust the hash function.
require(wiz1.currentDuel == duelId, "Invalid duel data");
// Confirm that the reveals match the commitments
require(
(keccak256(abi.encodePacked(moveSet1, salt1)) == commit1) &&
(keccak256(abi.encodePacked(moveSet2, salt2)) == commit2), "Moves don't match commitment");
// Resolve the duel!
_resolveDuel(duelId, wizardId1, wizardId2, moveSet1, moveSet2);
}
/// @notice An utility function to resolve a duel once both movesets have been revealed.
function _resolveDuel(bytes32 duelId, uint256 wizardId1, uint256 wizardId2, bytes32 moveSet1, bytes32 moveSet2) internal {
Duel memory duelInfo = duels[duelId];
require(block.number < duelInfo.timeout, "Duel expired");
// Get a reference to the Wizard objects in storage
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
int256 battlePower1 = wiz1.power;
int256 battlePower2 = wiz2.power;
int256 moldPower = int256(_blueMoldPower());
if (duelInfo.isAscensionBattle) {
// In Ascension Battles, if one Wizard is more powerful than the other Wizard by
// more than double the current blue mold level, we cap the at-risk power of that
// more powerful Wizard to match the power level of the weaker wizard. This probably
// isn't clear, so here are some examples. In all of these examples, the second wizard
// is more powerful than the first, but the logic is equivalent in both directions.
// In each case, we assume the blue mold level is 100. (The non-intuitive lines are
// marked with an arrow.)
//
// power1 | power2 | battlePower2
// 100 | 100 | 100
// 100 | 200 | 200
// 100 | 300 | 300
// 100 | 301 | 100 <==
// 199 | 200 | 200
// 199 | 300 | 300
// 199 | 399 | 399
// 199 | 400 | 199 <==
//
// This technique is necessary to achieve three somewhat conflicting goals
// simultaneously:
// - Anyone should be able to battle an ascending Wizard, regardless of the
// power differential
// - Your probability of winning an Ascension Battle should be proportional to
// the amount of power you put at risk
// - A Wizard that is Ascending should be _guaranteed_ that, if they manage to
// win the Ascension Battle, they will have enough power to escape the next
// Blue Mold increase. (And if they lose, at least they had a fair shot.)
//
// Note that although a very powerful Wizard becomes less likely to win under this
// scheme (because they aren't using their entire power in this battle), they are
// putting much less power at risk (while the ascending Wizard is risking EVERYTHING).
if (battlePower1 > battlePower2 + 2*moldPower) {
battlePower1 = battlePower2;
} else if (battlePower2 > battlePower1 + 2*moldPower) {
battlePower2 = battlePower1;
}
}
int256 powerDiff = duelResolver.resolveDuel(
moveSet1,
moveSet2,
uint256(battlePower1),
uint256(battlePower2),
wiz1.affinity,
wiz2.affinity);
// A duel resolver should never return a negative value with a magnitude greater than the
// first wizard's power, or a positive value with a magnitude greater than the second
// wizard's power. We enforce that here to be safe (since it is an external contract).
if (powerDiff < -battlePower1) {
powerDiff = -battlePower1;
} else if (powerDiff > battlePower2) {
powerDiff = battlePower2;
}
// Given the checks above, both of these values will resolve to >= 0
battlePower1 += powerDiff;
battlePower2 -= powerDiff;
if (duelInfo.isAscensionBattle) {
// In an Ascension Battle, we always transfer 100% of the power-at-risk. Give it
// to the Wizard with the highest power after the battle (which might not be the
// Wizard who got the higher score!)
if (battlePower1 >= battlePower2) {
// NOTE! The comparison above is very carefully chosen: In the case of a
// tie in the power level after the battle (exceedingly unlikely, but possible!)
// we want the win to go to the Wizard with the lower ID. Since all of the duel
// functions require the wizards to be strictly ascending ID order, that's
// wizardId1, which means we want a tie to land in this leg of the if-else statement.
powerDiff += battlePower2;
} else {
powerDiff -= battlePower1;
}
}
// We now apply the power differential to the _actual_ Wizard powers (and not just
// the power-at-risk).
int256 power1 = wiz1.power + powerDiff;
int256 power2 = wiz2.power - powerDiff;
// We now check to see if either of the wizards ended up under the blue mold level.
// If so, we transfer ALL of the rest of the power from the weaker Wizard to the winner.
if (power1 < moldPower) {
power2 += power1;
power1 = 0;
}
else if (power2 < moldPower) {
power1 += power2;
power2 = 0;
}
_updatePower(wiz1, power1);
_updatePower(wiz2, power2);
// unlock wizards
wiz1.currentDuel = 0;
wiz2.currentDuel = 0;
// Incrememnt the Wizard nonces
wiz1.nonce += 1;
wiz2.nonce += 1;
// Clean up old data
delete duels[duelId];
delete revealedMoves[duelId][wizardId1];
delete revealedMoves[duelId][wizardId2];
// emit event
emit DuelEnd(duelId, wizardId1, wizardId2, moveSet1, moveSet2, wiz1.power, wiz2.power);
}
/// @notice Utility function to update the power on a Wizard, ensuring it doesn't overflow
/// a uint88 and also updates maxPower as appropriate.
// solium-disable-next-line security/no-assign-params
function _updatePower(BattleWizard storage wizard, int256 newPower) internal {
if (newPower > MAX_POWER) {
newPower = MAX_POWER;
}
wizard.power = uint88(newPower);
if (wizard.maxPower < newPower) {
wizard.maxPower = uint88(newPower);
}
}
/// @notice Resolves a duel that has timed out. This can only happen if one or both players
/// didn't reveal their moves. If both don't reveal, there is no power transfer, if one
/// revealed, they win ALL the power.
///
/// Note: This function doens't need exists(wizardId1) exists(wizardId2) because an
/// eliminated Wizard would have currentDuel == 0
function resolveTimedOutDuel(uint256 wizardId1, uint256 wizardId2) external {
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
bytes32 duelId = wiz1.currentDuel;
require(duelId != 0 && wiz2.currentDuel == duelId, "Wizards are not dueling");
require(block.number > duels[duelId].timeout, "Duel not timed out");
int256 allPower = wiz1.power + wiz2.power;
if (revealedMoves[duelId][wizardId1] != 0) {
// The first Wizard revealed their moves, but the second one didn't (otherwise it
// would have been resolved). Transfer all of the power from two to one.
_updatePower(wiz1, allPower);
wiz2.power = 0;
}
else if (revealedMoves[duelId][wizardId2] != 0) {
// The second Wizard revealed, so it drains the first.
_updatePower(wiz2, allPower);
wiz1.power = 0;
}
// NOTE: If neither Wizard did a reveal, we just end the battle with no power transfer.
// unlock wizards
wiz1.currentDuel = 0;
wiz2.currentDuel = 0;
// Incrememnt the Wizard nonces
wiz1.nonce += 1;
wiz2.nonce += 1;
// Clean up old data
delete duels[duelId];
delete revealedMoves[duelId][wizardId1];
delete revealedMoves[duelId][wizardId2];
// emit event
emit DuelTimeOut(duelId, wizardId1, wizardId2, wiz1.power, wiz2.power);
}
/// @notice Transfer the power of one Wizard to another. The caller has to be the owner
/// or have approval of the sending Wizard. Both Wizards must be ready (not moldy,
/// ascending or in a duel), and we limit power transfers to happen during Fight
/// Windows (this is important so that power transfers don't interfere with Culling
/// or Ascension operations).
/// @param sendingWizardId The Wizard to transfer power from. After the transfer,
/// this Wizard will have no power.
/// @param receivingWizardId The Wizard to transfer power to.
function giftPower(uint256 sendingWizardId, uint256 receivingWizardId) external
onlyWizardController(sendingWizardId) exists(receivingWizardId) duringFightWindow
{
BattleWizard storage sendingWiz = wizards[sendingWizardId];
BattleWizard storage receivingWiz = wizards[receivingWizardId];
require(sendingWizardId != receivingWizardId, "Can't gift power to yourself");
require(isReady(sendingWizardId) && isReady(receivingWizardId), "Wizard not ready");
emit PowerGifted(sendingWizardId, receivingWizardId, sendingWiz.power);
_updatePower(receivingWiz, sendingWiz.power + receivingWiz.power);
sendingWiz.power = 0;
// update the nonces to reflect the state change and invalidate any pending commitments
sendingWiz.nonce += 1;
receivingWiz.nonce += 1;
}
/// @notice A function that will permanently remove eliminated Wizards from the smart contract.
///
/// The way that this (and cullMoldedWithMolded()) works isn't entirely obvious, so please settle
/// down for story time!
///
/// The "obvious" solution to elminating Wizards from the Tournament is to simply delete
/// them from the wizards mapping when they are beaten into submission (Oh! Sorry! Marketing
/// team says I should say "tired".) But we can't do this during the revival phase, because
/// maybe that player wants to revive their Wizard. What's more is that when the Blue Mold
/// starts, there is no on-chain event that fires when the Blue Mold power level doubles
/// (which can also lead to Wizard elimination).
///
/// The upshot is that we could have a bunch of Wizards sitting around in the wizards mapping
/// that are below the Blue Mold level, possibly even with a power level of zero. If we can't
/// get rid of them somehow, we can't know when the Tournament is over (which would make for
/// a pretty crappy tournament, huh?).
///
/// The next obvious solution? If a Wizard is below the Blue Mold level, just let anyone come
/// along and delete that sucker. Whoa, there, Cowboy! Maybe you should think it through for
/// a minute before you jump to any conclusions. Give it a minute, you'll see what I mean.
///
/// Yup. I knew you'd see it. If we start deleting ALL the Wizards below the Blue Mold level,
/// there's a not-so-rare edge case where the last two or three or ten Wizards decide not
/// to fight each other, and they all get molded. Eek! Another great way to make for a crappy
/// tournament! No winner!
///
/// So, if we do end up with ALL of the Wizards molded, how do we resolve the Tournament? Our
/// solution is to let the 5 most powerful molded Wizards split the pot pro-rata (so, if you have
/// 60% of the total power represented in the 5 winning Wizards, you get 60% of the pot.)
///
/// But this puts us in a bit of a pickle. How can we delete a molded Wizard if it might just
/// be a winner?!
///
/// Simple! If someone wants to permanently remove a Wizard from the tournament, they just have
/// to pass in a reference to _another_ Wizard (or Wizards) that _prove_ that the Wizard they
/// want to elminate can't possibly be the winner.
///
/// This function handles the simpler of the two cases: If the caller can point to a Wizard
/// that is _above_ the Blue Mold level, then _any_ Wizard that is below the Blue
/// mold level can be safely eliminated.
///
/// Note that there are no restrictions on who can cull moldy Wizards. Anyone can call, so
/// long as they have the necessary proof!
/// @param wizardIds A list of moldy Wizards to permanently remove from the Tournament
/// @param survivor The ID of a surviving Wizard, as proof that it's safe to remove those moldy folks
function cullMoldedWithSurvivor(uint256[] calldata wizardIds, uint256 survivor) external
exists(survivor) duringCullingWindow
{
uint256 moldLevel = _blueMoldPower();
require(wizards[survivor].power >= moldLevel, "Survivor isn't alive");
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
if (wizards[wizardId].maxPower != 0 && wizards[wizardId].power < moldLevel) {
delete wizards[wizardId];
remainingWizards--;
emit WizardElimination(wizardId);
}
}
}
/// @notice Another function to remove eliminated Wizards from the smart contract.
///
/// Well, partner, it's good to see you back again. I hope you've recently read the comments
/// on cullMoldedWithSurvivor() because that'll provide you with some much needed context here.
///
/// This function handles the other case, what if there IS no unmolded Wizard to point to, how do
/// you cull the excess moldy Wizards to pare it down to the five final survivors that should split
/// the pot?
///
/// Well, the answer is much the same as before, only instead of pointing to a single example of
/// a Wizard that has a better claim to the pot, we require that the caller provides a reference
/// to FIVE other Wizards who have a better claim to the pot.
///
/// It would be pretty easy to write this function in a way that was very expensive, so in order
/// to save ourselves a lot of gas, we require that the list of Wizards is in strictly decending
/// order of power (if two wizards have identical power levels, we consider the one with the
/// lower ID as being more powerful).
///
/// We also require that the first (i.e. most powerful) Wizard in the list is moldy, even though
/// it's not going to be eliminated! This may not seem strictly necessary, but it makes the
/// logic simpler (because then we can just assume that ALL the Wizards are moldy, without any
/// further checks). If it isn't moldy, the caller should just use the cullMoldedWithSurvivor()
/// method instead!
///
/// "Oh ho!" you say, taking great pleasure in your clever insight. "How can you be so sure that
/// the first five Wizards passed in as 'leaders' are _actually_ the five most powerful molded
/// Wizards?" Well, my dear friend... you are right: We can't!
///
/// However it turns out that's actually fine! If the caller (for some reason) decides to start the list
/// with the Wizards ranked 6-10 in the Tournament, they can do it that and we'd never know the
/// difference.... Except that's not actually a problem, because they'd still only be able to remove
/// molded Wizards ranked 11th or higher, all of which are due for removal anyway. (It's the same
/// argument that we don't actually know -- inside this function -- if there's a non-molded Wizard;
/// it's still safe to allow the caller to eliminate molded Wizards ranked 6th or higher.)
/// @param moldyWizardIds A list of moldy Wizards, in strictly decreasing power order. Entries 5+ in this list
/// will be permanently removed from the Tournament
function cullMoldedWithMolded(uint256[] calldata moldyWizardIds) external duringCullingWindow {
uint256 currentId;
uint256 currentPower;
uint256 previousId = moldyWizardIds[0];
uint256 previousPower = wizards[previousId].power;
// It's dumb to call this function with fewer than 5 wizards, but nothing bad will happen
// so we don't waste gas preventing it.
// require(moldyWizardsIds.length > 5, "No wizards to eliminate");
require(previousPower < _blueMoldPower(), "Not moldy");
for (uint256 i = 1; i < moldyWizardIds.length; i++) {
currentId = moldyWizardIds[i];
checkExists(currentId);
currentPower = wizards[currentId].power;
// Confirm that this new Wizard has a worse claim on the prize than the previous Wizard
require(
(currentPower < previousPower) ||
((currentPower == previousPower) && (currentId > previousId)),
"Wizards not strictly ordered");
if (i >= 5)
{
delete wizards[currentId];
remainingWizards--;
emit WizardElimination(currentId);
}
previousId = currentId;
previousPower = currentPower;
}
}
/// @notice One last culling function that simply removes Wizards with zero power. They can't
/// even get a cut of the final pot... (Worth noting: Culling Windows are only available
/// during the Elmination Phase, so even Wizards that go to zero can't be removed during
/// the Revival Phase.)
function cullTiredWizards(uint256[] calldata wizardIds) external duringCullingWindow {
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
if (wizards[wizardId].maxPower != 0 && wizards[wizardId].power == 0) {
delete wizards[wizardId];
remainingWizards--;
emit WizardElimination(wizardId);
}
}
}
/// @notice This is a pretty important function! When the Tournament has a single remaining Wizard left
/// we can send them ALL of the funds in this smart contract. Notice that we don't actually check
/// to see if the claimant is moldy: If there is a single remaining Wizard in the Tournament, they
/// get to take the pot, regardless of the mold level.
function claimTheBigCheeze(uint256 claimingWinnerId) external duringCullingWindow onlyWizardController(claimingWinnerId) {
require(remainingWizards == 1, "Keep fighting!");
// They did it! They were the final survivor. They get all the money!
emit PrizeClaimed(claimingWinnerId, address(this).balance);
remainingWizards = 0;
delete wizards[claimingWinnerId];
msg.sender.transfer(address(this).balance);
}
/// @notice A function that allows one of the 5 most powerful Wizards to claim their pro-rata share of
/// the pot if the Tournament ends with all Wizards subcumbing to the Blue Mold. Note that
/// all but five of the Moldy Wizards need to first be eliminated with cullMoldedWithMolded().
///
/// It might seem like it would be tricky to split the pot one player at a time. Imagine that
/// there are just three winners, with power levels 20, 30, and 50. If the third player claims
/// first, they will get 50% of the (remaining) pot, but if they claim last, they will get
/// 100% of the remaining pot! If you run some examples, you'll see that by decreasing the pot
/// size by a value exactly proportional to the power of the removed Wizard, everyone gets
/// the same amount of winnings, regardless of the order in which they claim (plus or minus
/// a wei or two due to rounding).
/// @param claimingWinnerId The Wizard who's share is currently being claimed
/// @param allWinners The complete set of all remaining Wizards in the tournament. This set MUST
/// be ordered by ascending ID.
function claimSharedWinnings(uint256 claimingWinnerId, uint256[] calldata allWinners)
external duringCullingWindow onlyWizardController(claimingWinnerId)
{
require(remainingWizards <= 5, "Too soon to claim");
require(remainingWizards == allWinners.length, "Must provide all winners");
require(wizards[claimingWinnerId].power != 0, "No cheeze for you!");
uint256 moldLevel = _blueMoldPower();
uint256 totalPower = 0;
uint256 lastWizard = 0;
// Check to see that all of the remaining Wizards are molded and not yet eliminated,
// assuming they are, keep track of the total power level of the remaining entrants
for (uint256 i = 0; i < allWinners.length; i++) {
uint256 wizardId = allWinners[i];
uint256 wizardPower = wizards[wizardId].power;
require(wizardId > lastWizard, "Winners not unique and ordered");
require(wizards[wizardId].maxPower != 0, "Wizard already eliminated");
require(wizardPower < moldLevel, "Wizard not moldy");
lastWizard = wizardId;
totalPower += wizardPower;
}
uint256 claimingWinnerShare = address(this).balance * wizards[claimingWinnerId].power / totalPower;
// Be sure to delete their claim on the prize before sending them the balance!
delete wizards[claimingWinnerId];
remainingWizards--;
emit PrizeClaimed(claimingWinnerId, claimingWinnerShare);
msg.sender.transfer(claimingWinnerShare);
}
/// @notice Allows the GateKeeper to destroy this contract if it's not needed anymore.
function destroy() external onlyGateKeeper {
require(isActive() == false, "Tournament active");
selfdestruct(msg.sender);
}
}
| An internal convenience function that checks to see if we are currently in the Window defined by the WindowParameters struct passed as an argument. We are never "in a window" if the contract is paused If we are before the first window of this type, we are obviously NOT in this window! | function _isInWindow(WindowParameters memory localParams) internal view returns (bool) {
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
if (block.number <= localParams.firstWindowStartBlock) {
return false;
}
}
| 12,784,503 |
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
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/utils/Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view 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/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library 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
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
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 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/TadUniswapMiningStorage.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract OwnableStorage{
address internal _owner;
}
contract PausableStorage{
bool internal _paused;
}
contract TadUniswapMiningStorage {
using SafeMath for uint256;
bool constant public isTadUniswapMining = true;
bool public initiated = false;
// proxy storage
address public admin;
address public implementation;
ERC20 public LPToken;
ERC20 public TadToken;
uint public startMiningBlockNum = 0;
uint public totalMiningBlockNum = 2400000;
uint public endMiningBlockNum = startMiningBlockNum + totalMiningBlockNum;
uint public tadPerBlock = 83333333333333333;
uint public constant stakeInitialIndex = 1e36;
uint public miningStateBlock = startMiningBlockNum;
uint public miningStateIndex = stakeInitialIndex;
struct Stake{
uint amount;
uint lockedUntil;
uint lockPeriod;
uint stakePower;
bool exists;
}
mapping (address => Stake[]) public stakes;
mapping (address => uint) public stakeCount;
uint public totalStaked;
uint public totalStakedPower;
mapping (address => uint) public stakeHolders;
mapping (address => uint) public stakerPower;
mapping (address => uint) public stakerIndexes;
mapping (address => uint) public stakerClaimed;
uint public totalClaimed;
}
// File: contracts/TadUniswapMining.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract TadUniswapMining is Ownable, Pausable, TadUniswapMiningStorage {
event Staked(address indexed user, uint256 amount, uint256 total, uint256 lockedUntil);
event Unstaked(address indexed user, uint256 amount, uint256 total);
event ClaimedTad(address indexed user, uint amount, uint total);
function initiate(uint _startMiningBlocknum, uint _totalMiningBlockNum, uint _tadPerBlock, ERC20 _tad, ERC20 _lp) public onlyOwner{
require(initiated==false, "contract is already initiated");
initiated = true;
require(_totalMiningBlockNum >= 100, "_totalMiningBlockNum is too small");
if(_startMiningBlocknum == 0){
_startMiningBlocknum = block.number;
}
_tad.totalSupply(); //sanity check
_lp.totalSupply(); //sanity check
startMiningBlockNum = _startMiningBlocknum;
totalMiningBlockNum = _totalMiningBlockNum;
endMiningBlockNum = startMiningBlockNum + totalMiningBlockNum;
miningStateBlock = startMiningBlockNum;
tadPerBlock = _tadPerBlock;
TadToken = _tad;
LPToken = _lp;
}
// @notice stake some LP tokens
// @param _amount some amount of LP tokens, requires enought allowance from LP token smart contract
// @param _locked the locking period; option: 0, 30 days (2592000), 90 days (7776000), 180 days (15552000), 360 days (31104000)
function stake(uint256 _amount, uint256 _locked) public whenNotPaused{
createStake(msg.sender, _amount, _locked);
}
// @notice internal function for staking
function createStake(
address _address,
uint256 _amount,
uint256 _locked
)
internal
{
claimTad();
require(block.number<endMiningBlockNum, "staking period has ended");
require(_locked == 0 || _locked == 30 days || _locked == 90 days || _locked == 180 days || _locked == 360 days , "invalid locked period" );
require(
LPToken.transferFrom(_address, address(this), _amount),
"Stake required");
uint _lockedUntil = block.timestamp.add(_locked);
uint _powerRatio;
uint _power;
if(_locked == 0){
_powerRatio = 1;
} else if(_locked == 30 days){
_powerRatio = 2;
} else if(_locked == 90 days){
_powerRatio = 3;
} else if(_locked == 180 days){
_powerRatio = 4;
} else if(_locked == 360 days){
_powerRatio = 5;
}
_power = _amount.mul(_powerRatio);
Stake memory _stake = Stake(_amount, _lockedUntil, _locked, _power, true);
stakes[_address].push(_stake);
stakeCount[_address] = stakeCount[_address].add(1);
stakerPower[_address] = stakerPower[_address].add(_power);
stakeHolders[_address] = stakeHolders[_address].add(_amount);
totalStaked = totalStaked.add(_amount);
totalStakedPower = totalStakedPower.add(_power);
emit Staked(
_address,
_amount,
stakeHolders[_address],
_lockedUntil);
}
// @notice unstake LP token
// @param _index the index of stakes array
function unstake(uint256 _index, uint256 _amount) public whenNotPaused{
require(stakes[msg.sender][_index].exists == true, "stake index doesn't exist");
require(stakes[msg.sender][_index].amount == _amount, "stake amount doesn't match");
withdrawStake(msg.sender, _index);
}
// @notice internal function for removing stake and reorder the array
function removeStake(address _address, uint index) internal {
for (uint i = index; i < stakes[_address].length-1; i++) {
stakes[_address][i] = stakes[_address][i+1];
}
stakes[_address].pop();
}
// @notice internal function for unstaking
function withdrawStake(
address _address,
uint256 _index
)
internal
{
claimTad();
if(block.number <= endMiningBlockNum){ //if current block is lower than endMiningBlockNum, check lockedUntil
require(stakes[_address][_index].lockedUntil <= block.timestamp, "the stake is still locked");
}
uint _amount = stakes[_address][_index].amount;
uint _power = stakes[_address][_index].stakePower;
if(_amount > stakeHolders[_address]){ //if amount is larger than owned
_amount = stakeHolders[_address];
}
require(
LPToken.transfer(_address, _amount),
"Unable to withdraw stake");
removeStake(_address, _index);
stakeCount[_address] = stakeCount[_address].sub(1);
stakerPower[_address] = stakerPower[_address].sub(_power);
totalStakedPower = totalStakedPower.sub(_power);
stakeHolders[_address] = stakeHolders[_address].sub(_amount);
totalStaked = totalStaked.sub(_amount);
updateMiningState();
emit Unstaked(
_address,
_amount,
stakeHolders[_address]);
}
// @notice internal function for updating mining state
function updateMiningState() internal{
if(miningStateBlock == endMiningBlockNum){ //if miningStateBlock is already the end of program, dont update state
return;
}
(miningStateIndex, miningStateBlock) = getMiningState(block.number);
}
// @notice calculate current mining state
function getMiningState(uint _blockNum) public view returns(uint, uint){
require(_blockNum >= miningStateBlock, "_blockNum must be >= miningStateBlock");
uint blockNumber = _blockNum;
if(_blockNum>endMiningBlockNum){ //if current block.number is bigger than the end of program, only update the state to endMiningBlockNum
blockNumber = endMiningBlockNum;
}
uint deltaBlocks = blockNumber.sub(miningStateBlock);
uint _miningStateBlock = miningStateBlock;
uint _miningStateIndex = miningStateIndex;
if (deltaBlocks > 0 && totalStaked > 0) {
uint tadAccrued = deltaBlocks.mul(tadPerBlock);
uint ratio = tadAccrued.mul(1e18).div(totalStakedPower); //multiple ratio to 1e18 to prevent rounding error
_miningStateIndex = miningStateIndex.add(ratio); //index is 1e18 precision
_miningStateBlock = blockNumber;
}
return (_miningStateIndex, _miningStateBlock);
}
// @notice claim TAD based on current state
function claimTad() public whenNotPaused {
updateMiningState();
uint claimableTad = claimableTad(msg.sender);
stakerIndexes[msg.sender] = miningStateIndex;
if(claimableTad > 0){
stakerClaimed[msg.sender] = stakerClaimed[msg.sender].add(claimableTad);
totalClaimed = totalClaimed.add(claimableTad);
TadToken.transfer(msg.sender, claimableTad);
emit ClaimedTad(msg.sender, claimableTad, stakerClaimed[msg.sender]);
}
}
// @notice calculate claimable tad based on current state
function claimableTad(address _address) public view returns(uint){
uint stakerIndex = stakerIndexes[_address];
// if it's the first stake for user and the first stake for entire mining program, set stakerIndex as stakeInitialIndex
if (stakerIndex == 0 && totalStaked == 0) {
stakerIndex = stakeInitialIndex;
}
//else if it's the first stake for user, set stakerIndex as current miningStateIndex
if(stakerIndex == 0){
stakerIndex = miningStateIndex;
}
uint deltaIndex = miningStateIndex.sub(stakerIndex);
uint tadDelta = deltaIndex.mul(stakerPower[_address]).div(1e18);
return tadDelta;
}
// @notice test function
function doNothing() public{
}
/*======== admin functions =========*/
// @notice admin function to pause the contract
function pause() public onlyOwner{
_pause();
}
// @notice admin function to unpause the contract
function unpause() public onlyOwner{
_unpause();
}
// @notice admin function to send TAD to external address, for emergency use
function sendTad(address _to, uint _amount) public onlyOwner{
TadToken.transfer(_to, _amount);
}
} | claim TAD based on current state | function claimTad() public whenNotPaused {
updateMiningState();
uint claimableTad = claimableTad(msg.sender);
stakerIndexes[msg.sender] = miningStateIndex;
if(claimableTad > 0){
stakerClaimed[msg.sender] = stakerClaimed[msg.sender].add(claimableTad);
totalClaimed = totalClaimed.add(claimableTad);
TadToken.transfer(msg.sender, claimableTad);
emit ClaimedTad(msg.sender, claimableTad, stakerClaimed[msg.sender]);
}
}
| 325,199 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
// Part: Address
/**
* @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.3._
*/
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.3._
*/
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);
}
}
}
}
// Part: Context
/*
* @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 virtual view returns (address payable) {
return msg.sender;
}
function _msgData() internal virtual view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Part: IERC20
/**
* @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
);
}
// Part: SafeMath
/**
* @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, "add: +");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "sub: -");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "mul: *");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// 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, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "div: /");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "mod: %");
}
/**
* @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;
}
}
// Part: ERC20
// File: contracts/token/ERC20/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 override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// Part: Ownable
/**
* @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: Sanctuary.sol
contract Sanctuary is ERC20("Staked SDT", "xSDT"), Ownable {
using SafeMath for uint256;
IERC20 public sdt;
address public rewardDistribution;
event Stake(address indexed staker, uint256 xsdtReceived);
event Unstake(address indexed unstaker, uint256 sdtReceived);
event RewardDistributorSet(address indexed newRewardDistributor);
event SdtFeeReceived(address indexed from, uint256 sdtAmount);
modifier onlyRewardDistribution() {
require(
_msgSender() == rewardDistribution,
"Caller is not reward distribution"
);
_;
}
constructor(IERC20 _sdt) public {
sdt = _sdt;
}
// Enter the Sanctuary. Pay some SDTs. Earn some shares.
function enter(uint256 _amount) public {
uint256 totalSdt = sdt.balanceOf(address(this));
uint256 totalShares = totalSupply();
if (totalShares == 0 || totalSdt == 0) {
_mint(_msgSender(), _amount);
emit Stake(_msgSender(), _amount);
} else {
uint256 what = _amount.mul(totalShares).div(totalSdt);
_mint(_msgSender(), what);
emit Stake(_msgSender(), what);
}
sdt.transferFrom(_msgSender(), address(this), _amount);
}
// Leave the Sanctuary. Claim back your SDTs.
function leave(uint256 _share) public {
uint256 totalShares = totalSupply();
uint256 what =
_share.mul(sdt.balanceOf(address(this))).div(totalShares);
_burn(_msgSender(), _share);
sdt.transfer(_msgSender(), what);
emit Unstake(_msgSender(), what);
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
emit RewardDistributorSet(_rewardDistribution);
}
function notifyRewardAmount(uint256 _balance)
external
onlyRewardDistribution
{
sdt.transferFrom(_msgSender(), address(this), _balance);
emit SdtFeeReceived(_msgSender(), _balance);
}
}
| Leave the Sanctuary. Claim back your SDTs. | function leave(uint256 _share) public {
uint256 totalShares = totalSupply();
uint256 what =
_share.mul(sdt.balanceOf(address(this))).div(totalShares);
_burn(_msgSender(), _share);
sdt.transfer(_msgSender(), what);
emit Unstake(_msgSender(), what);
}
| 120,036 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "./TokenHolder.sol";
import "./lib/Sig.sol";
import "./lib/Bytes.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Erdstall is Ownable {
// The epoch-balance statements signed by the TEE.
struct Balance {
uint64 epoch;
address account;
bool exit;
TokenValue[] tokens;
}
struct TokenValue {
address token;
bytes value;
}
// use 2nd-highest number to indicate not-frozen
uint64 constant notFrozen = 0xfffffffffffffffe;
// Parameters set during deployment.
address public immutable tee; // yummi 🍵
uint64 public immutable bigBang; // start of first epoch
uint64 public immutable epochDuration; // number of blocks of one epoch
mapping(address => string) public tokenTypes; // holder => type
mapping(address => TokenHolder) public tokenHolders; // token => holder contract
// epoch => account => token values
// Multiple deposits can be made in a single epoch, so we have to use an
// array.
mapping(uint64 => mapping(address => TokenValue[])) public deposits;
mapping(uint64 => mapping(address => bool)) public withdrawn; // epoch => account => withdrawn-flag
mapping(uint64 => mapping(address => bool)) public challenges; // epoch => account => challenge-flag
mapping(uint64 => uint256) public numChallenges; // epoch => numChallenges
uint64 public frozenEpoch = notFrozen; // epoch at which contract was frozen
event TokenTypeRegistered(string tokenType, address tokenHolder);
event TokenRegistered(address indexed token, string tokenType, address tokenHolder);
event Deposited(uint64 indexed epoch, address indexed account, address token, bytes value);
event Withdrawn(uint64 indexed epoch, address indexed account, TokenValue[] tokens);
event WithdrawalException(uint64 indexed epoch, address indexed account, address indexed token,
bytes value, bytes error);
event Challenged(uint64 indexed epoch, address indexed account);
event ChallengeResponded(uint64 indexed epoch, address indexed account, TokenValue[] tokens, bytes sig);
event Frozen(uint64 indexed epoch);
constructor(address _tee, uint64 _epochDuration) {
tee = _tee;
bigBang = uint64(block.number);
epochDuration = _epochDuration;
}
// Lets the owner register a token holder for a token type. Deposits into
// Erdstall can be made via registered token holders.
function registerTokenType(address holder, string calldata tokenType)
external onlyOwner
{
string storage regTokenType = tokenTypes[holder];
if (!empty(regTokenType)) {
require(Bytes.areEqualStr(regTokenType, tokenType),
"registered token type mismatch");
return;
}
tokenTypes[holder] = tokenType;
emit TokenTypeRegistered(tokenType, holder);
}
function getTokenType(address holder) internal view returns (string storage) {
string storage tokenType = tokenTypes[holder];
require(!empty(tokenType), "token holder not registered");
return tokenType;
}
// Lets the owner manually register a token's holder. This is usually done
// implicitly during deposits.
function registerToken(address token, address holder) external onlyOwner {
ensureTokenRegistered(token, holder);
}
// called during deposits to ensure that token can be mapped back to token
// holder during withdrawals.
function ensureTokenRegistered(address token, address holder) internal {
address regHolder = address(tokenHolders[token]);
if (regHolder != address(0)) {
require(regHolder == holder, "registered holder mismatch");
return;
}
_registerToken(token, holder);
}
function _registerToken(address token, address holder) internal {
// implicitly checks that holder is registered
string storage tokenType = getTokenType(holder);
tokenHolders[token] = TokenHolder(holder);
emit TokenRegistered(token, tokenType, holder);
}
function getTokenHolder(address token) internal view returns (TokenHolder) {
TokenHolder holder = tokenHolders[token];
require(address(holder) != address(0), "token not registered");
return holder;
}
modifier onlyTokenHolders() {
require(!empty(tokenTypes[msg.sender]), "caller not token holder");
_;
}
modifier onlyAlive() {
require(!isFrozen(), "Erdstall frozen");
uint64 ep = epoch();
// prevent underflow, freeze couldn't have happened yet.
if (ep >= 3) {
unchecked {
// in case ensureFrozen wasn't called yet...
require(numChallenges[ep-3] == 0, "Erdstall freezing");
}
}
_;
}
modifier onlyUnchallenged() {
uint64 ep = epoch();
// prevent underflow, challenges couldn't have happened yet.
if (ep >= 2) {
unchecked {
require(numChallenges[ep-2] == 0, "open challenges");
}
}
_;
}
//
// Normal Operation
//
// deposit registers a deposit of `value` for token `token` from user
// `sender` in the Erdstall system. It can only be called by TokenHolders.
//
// Users need to deposit into the Erdstall system by depositing into the
// respective TokenHolders, who then call this function to record the
// deposit.
//
// Can only be called if there are no open challenges.
function deposit(address depositor, address token, bytes memory value)
external onlyTokenHolders onlyAlive onlyUnchallenged
{
ensureTokenRegistered(token, msg.sender);
uint64 ep = epoch();
// Record deposit in case of freeze of the next two epochs.
deposits[ep][depositor].push(TokenValue({token: token, value: value}));
emit Deposited(ep, depositor, token, value);
}
// withdraw lets a user withdraw their funds from the system. It is only
// possible to withdraw with an exit proof, that is, a balance proof with
// field `exit` set to true.
//
// `sig` must be a signature created with
// `signText(keccak256(abi.encode(...)))`.
// See `encodeBalanceProof` for exact encoding specification.
//
// Can only be called if there are no open challenges.
function withdraw(Balance calldata balance, bytes calldata sig)
external onlyAlive onlyUnchallenged
{
require(balance.epoch <= sealedEpoch(), "withdraw: too early");
require(balance.account == msg.sender, "withdraw: wrong sender");
require(balance.exit, "withdraw: no exit proof");
verifyBalance(balance, sig);
_withdraw(balance.epoch, balance.tokens);
}
// Transfers all tokens to msg.sender, using each token's token holder.
function _withdraw(uint64 _epoch, TokenValue[] memory tokens) internal {
require(!withdrawn[_epoch][msg.sender], "already withdrawn");
withdrawn[_epoch][msg.sender] = true;
for (uint i=0; i < tokens.length; i++) {
TokenValue memory tv = tokens[i];
TokenHolder holder = getTokenHolder(tv.token);
try holder.transfer(tv.token, msg.sender, tv.value) {
// successful withdrawal of this token
} catch (bytes memory error) {
emit WithdrawalException(_epoch, msg.sender, tv.token, tv.value, error);
}
}
emit Withdrawn(_epoch, msg.sender, tokens);
}
//
// Challenge Functions
//
// Challenges the operator to post the user's last epoch's exit proof.
// The user needs to pass the latest balance proof, that is, of the just
// sealed epoch, to proof that they are part of the system.
//
// After a challenge is opened, the operator (anyone, actually) can respond
// to the challenge using function `respondChallenge`.
function challenge(Balance calldata balance, bytes calldata sig) external onlyAlive {
require(balance.account == msg.sender, "challenge: wrong sender");
require(balance.epoch == sealedEpoch(), "challenge: wrong epoch");
require(!balance.exit, "challenge: exit proof");
verifyBalance(balance, sig);
registerChallenge(balance.tokens.length);
}
// challengeDeposit should be called by a user if they deposited but never
// received a balance proof from the operator.
//
// After a challenge is opened, the operator (anyone, actually) can respond
// to the challenge using function `respondChallenge`.
function challengeDeposit() external onlyAlive {
registerChallenge(0);
}
function registerChallenge(uint256 numSealedValues) internal {
// next line reverts (underflow) on purpose if called too early
uint64 challEpoch = epoch() - 1;
require(!challenges[challEpoch][msg.sender], "already challenged");
uint256 numValues =
numSealedValues + deposits[challEpoch][msg.sender].length;
require(numValues > 0, "no value in system");
challenges[challEpoch][msg.sender] = true;
numChallenges[challEpoch]++;
emit Challenged(challEpoch, msg.sender);
}
// respondChallenge lets the operator (or anyone) respond to open challenges
// that were posted during the previous on-chain epoch.
//
// The latest or second latest balance proof needs to be submitted, so the
// contract can verify that all challenges were seen by the enclave and all
// challenging users were exited from the system.
//
// Note that a challenging user has to subscribe to ChallengeResponded
// events from both, the latest and second latest epoch to receive their
// exit proof.
function respondChallenge(Balance calldata balance, bytes calldata sig) external onlyAlive {
// next line reverts (underflow) on purpose if called too early
uint64 challEpoch = epoch() - 2;
require((balance.epoch == challEpoch) || (balance.epoch == challEpoch+1),
"respondChallenge: wrong epoch");
require(balance.exit, "respondChallenge: no exit proof");
verifyBalance(balance, sig);
require(challenges[challEpoch][balance.account], "respondChallenge: no challenge registered");
challenges[challEpoch][balance.account] = false;
numChallenges[challEpoch]--;
// The challenging user can create their exit proof from this data and
// withdraw with `withdraw` starting with the next epoch.
emit ChallengeResponded(balance.epoch, balance.account, balance.tokens, sig);
}
// withdrawFrozen lets any user withdraw all funds locked in the frozen
// contract. Parameter `balance` needs to be the balance proof of the last
// unchallenged epoch.
//
// Implicitly calls ensureFrozen to ensure that the contract state is set to
// frozen if the last epoch has an unanswered challenge.
function withdrawFrozen(Balance calldata balance, bytes calldata sig) external {
ensureFrozen();
require(balance.account == msg.sender, "withdrawFrozen: wrong sender");
require(balance.epoch == frozenEpoch, "withdrawFrozen: wrong epoch");
verifyBalance(balance, sig);
// Also recover deposits from broken epochs
TokenValue[] memory tokens = appendFrozenDeposits(balance.tokens);
_withdraw(frozenEpoch, tokens);
}
// withdrawFrozenDeposit lets any user withdraw the deposits that they made
// in the challenged and broken epoch.
//
// This function should only be called by users who never received a balance
// proof and thus never had any balance in the system, to recover their
// deposits.
function withdrawFrozenDeposit() external {
ensureFrozen();
TokenValue[] memory tokens = appendFrozenDeposits(new TokenValue[](0));
require(tokens.length > 0, "no frozen deposit");
_withdraw(frozenEpoch, tokens);
}
// ensureFrozen ensures that the state of the contract is set to frozen if
// the last epoch has at least one unanswered challenge. It is idempotent.
//
// It is implicitly called by withdrawFrozen and withdrawFrozenDeposit but
// can be called seperately if the contract should be frozen before anyone
// wants to withdraw.
//
// ensureFrozen reverts if called too early. This also implies that the
// functions calling it cannot be called too early (withdrawFrozen and
// withdrawFrozenDeposit).
function ensureFrozen() public {
if (isFrozen()) { return; }
uint64 ep = epoch();
require(ep >= 4, "too early, no freeze possible yet");
uint64 challEpoch = ep - 3;
require(numChallenges[challEpoch] > 0, "no open challenges");
// freezing to previous, that is, last unchallenged epoch
uint64 frEpoch = challEpoch - 1;
frozenEpoch = frEpoch;
emit Frozen(frEpoch);
}
function appendFrozenDeposits(TokenValue[] memory tokens)
internal view returns (TokenValue[] memory)
{
TokenValue[] storage deps1 = deposits[frozenEpoch+1][msg.sender];
TokenValue[] storage deps2 = deposits[frozenEpoch+2][msg.sender];
TokenValue[] memory deps = new TokenValue[](tokens.length + deps1.length + deps2.length);
// Concatenate arrays
for (uint i=0; i < tokens.length; i++) {
deps[i] = tokens[i];
}
for (uint i=0; i < deps1.length; i++) {
deps[i+tokens.length] = deps1[i];
}
for (uint i=0; i < deps2.length; i++) {
deps[i+tokens.length+deps1.length] = deps2[i];
}
return deps;
}
function isFrozen() internal view returns (bool) {
return frozenEpoch != notFrozen;
}
function sealedEpoch() internal view returns (uint64) {
uint64 ep = epoch();
require(ep >= 2, "too early, no epoch sealed yet");
unchecked {
return ep-2;
}
}
// epoch returns the current epoch. It should not be used directly in public
// functions, but the fooEoch functions instead, as they account for the
// correct shifts.
function epoch() internal view returns (uint64) {
return (uint64(block.number) - bigBang) / epochDuration;
}
function verifyBalance(Balance memory balance, bytes memory sig) public view {
require(Sig.verify(encodeBalanceProof(balance), sig, tee), "invalid signature");
}
function encodeBalanceProof(Balance memory balance) public view returns (bytes memory) {
return abi.encode(
"ErdstallBalance",
address(this),
balance.epoch,
balance.account,
balance.exit,
balance.tokens);
}
function empty(string storage s) internal view returns (bool) {
return bytes(s).length == 0;
}
}
| Transfers all tokens to msg.sender, using each token's token holder. successful withdrawal of this token | function _withdraw(uint64 _epoch, TokenValue[] memory tokens) internal {
require(!withdrawn[_epoch][msg.sender], "already withdrawn");
withdrawn[_epoch][msg.sender] = true;
for (uint i=0; i < tokens.length; i++) {
TokenValue memory tv = tokens[i];
TokenHolder holder = getTokenHolder(tv.token);
try holder.transfer(tv.token, msg.sender, tv.value) {
emit WithdrawalException(_epoch, msg.sender, tv.token, tv.value, error);
}
}
emit Withdrawn(_epoch, msg.sender, tokens);
}
| 5,402,928 |
./partial_match/7700/0x2Bf57af42Cc1daB534DAe42169DdeD97f139A316/sources/dice_flat.sol | Play the game!Won!Loser! | function lottery(uint8 guess) public payable returns(bool){
require(guess == 0 || guess == 1, "Guess should be either 0 ('heads') or 1 ('tails')");
require(msg.value >= 5, "Bet at least 5");
require(msg.value < maxBet || (msg.value <= address(this).balance - msg.value), "Max bet is 50 and cannot be more than the current pot's total value.");
uint8 result = uint8(uint256(keccak256(abi.encodePacked(block.difficulty, msg.sender, block.timestamp)))%2);
bool won = false;
if (msg.value > maxBet || (msg.value > address(this).balance - msg.value)){
revert();
}
else if (guess == result) {
payable(msg.sender).transfer(msg.value * 2);
payable(target).transfer(msg.value/40);
won = true;
}
else if (guess != result){
payable(target).transfer(msg.value/40);
}
emit GameResult(result);
lastPlayedGames.push(Game(msg.sender, msg.value, guess, won, address(this).balance));
return won;
}
| 3,506,116 |
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
import 'IERC20.sol';
interface IIntegralERC20 is IERC20 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
interface IReserves {
event Sync(uint112 reserve0, uint112 reserve1);
event Fees(uint256 fee0, uint256 fee1);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 lastTimestamp
);
function getReferences()
external
view
returns (
uint112 reference0,
uint112 reference1,
uint32 epoch
);
function getFees() external view returns (uint256 fee0, uint256 fee1);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
import 'IIntegralERC20.sol';
import 'IReserves.sol';
interface IIntegralPair is IIntegralERC20, IReserves {
event Mint(address indexed sender, address indexed to);
event Burn(address indexed sender, address indexed to);
event Swap(address indexed sender, address indexed to);
event SetMintFee(uint256 fee);
event SetBurnFee(uint256 fee);
event SetSwapFee(uint256 fee);
event SetOracle(address account);
event SetTrader(address trader);
event SetToken0AbsoluteLimit(uint256 limit);
event SetToken1AbsoluteLimit(uint256 limit);
event SetToken0RelativeLimit(uint256 limit);
event SetToken1RelativeLimit(uint256 limit);
event SetPriceDeviationLimit(uint256 limit);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function oracle() external view returns (address);
function trader() external view returns (address);
function mintFee() external view returns (uint256);
function setMintFee(uint256 fee) external;
function mint(address to) external returns (uint256 liquidity);
function burnFee() external view returns (uint256);
function setBurnFee(uint256 fee) external;
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swapFee() external view returns (uint256);
function setSwapFee(uint256 fee) external;
function setOracle(address account) external;
function setTrader(address account) external;
function token0AbsoluteLimit() external view returns (uint256);
function setToken0AbsoluteLimit(uint256 limit) external;
function token1AbsoluteLimit() external view returns (uint256);
function setToken1AbsoluteLimit(uint256 limit) external;
function token0RelativeLimit() external view returns (uint256);
function setToken0RelativeLimit(uint256 limit) external;
function token1RelativeLimit() external view returns (uint256);
function setToken1RelativeLimit(uint256 limit) external;
function priceDeviationLimit() external view returns (uint256);
function setPriceDeviationLimit(uint256 limit) external;
function collect(address to) external;
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to
) external;
function sync() external;
function initialize(
address _token0,
address _token1,
address _oracle,
address _trader
) external;
function syncWithOracle() external;
function fullSync() external;
function getSpotPrice() external view returns (uint256 spotPrice);
function getSwapAmount0In(uint256 amount1Out) external view returns (uint256 swapAmount0In);
function getSwapAmount1In(uint256 amount0Out) external view returns (uint256 swapAmount1In);
function getSwapAmount0Out(uint256 amount1In) external view returns (uint256 swapAmount0Out);
function getSwapAmount1Out(uint256 amount0In) external view returns (uint256 swapAmount1Out);
function getDepositAmount0In(uint256 amount0) external view returns (uint256 depositAmount0In);
function getDepositAmount1In(uint256 amount1) external view returns (uint256 depositAmount1In);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity =0.7.5;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SM_ADD_OVERFLOW');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = sub(x, y, 'SM_SUB_UNDERFLOW');
}
function sub(
uint256 x,
uint256 y,
string memory message
) internal pure returns (uint256 z) {
require((z = x - y) <= x, message);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SM_MUL_OVERFLOW');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SM_DIV_BY_ZERO');
uint256 c = a / b;
return c;
}
function ceil_div(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = div(a, b);
if (c == mul(a, b)) {
return c;
} else {
return add(c, 1);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
interface IIntegralFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
event OwnerSet(address owner);
function owner() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(
address tokenA,
address tokenB,
address oracle,
address trader
) external returns (address pair);
function setOwner(address) external;
function setMintFee(
address tokenA,
address tokenB,
uint256 fee
) external;
function setBurnFee(
address tokenA,
address tokenB,
uint256 fee
) external;
function setSwapFee(
address tokenA,
address tokenB,
uint256 fee
) external;
function setOracle(
address tokenA,
address tokenB,
address oracle
) external;
function setTrader(
address tokenA,
address tokenB,
address trader
) external;
function collect(
address tokenA,
address tokenB,
address to
) external;
function withdraw(
address tokenA,
address tokenB,
uint256 amount,
address to
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH_APPROVE_FAILED');
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH_TRANSFER_FAILED');
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH_TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{ value: value }(new bytes(0));
require(success, 'TH_ETH_TRANSFER_FAILED');
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
import 'IERC20.sol';
import 'IWETH.sol';
import 'SafeMath.sol';
import 'TransferHelper.sol';
library TokenShares {
using SafeMath for uint256;
using TransferHelper for address;
event UnwrapFailed(address to, uint256 amount);
struct Data {
mapping(address => uint256) totalShares;
address weth;
}
function setWeth(Data storage data, address _weth) internal {
data.weth = _weth;
}
function sharesToAmount(
Data storage data,
address token,
uint256 share
) external returns (uint256) {
if (share == 0) {
return 0;
}
if (token == data.weth) {
return share;
}
require(data.totalShares[token] >= share, 'TS_INSUFFICIENT_BALANCE');
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 value = balance.mul(share).div(data.totalShares[token]);
data.totalShares[token] = data.totalShares[token].sub(share);
return value;
}
function amountToShares(
Data storage data,
address token,
uint256 amount,
bool wrap
) external returns (uint256) {
if (amount == 0) {
return 0;
}
if (token == data.weth) {
if (wrap) {
require(msg.value >= amount, 'TS_INSUFFICIENT_AMOUNT');
IWETH(token).deposit{ value: amount }();
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
return amount;
} else {
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
require(balanceBefore > 0 || data.totalShares[token] == 0, 'TS_INVALID_SHARES');
if (data.totalShares[token] == 0) {
data.totalShares[token] = balanceBefore;
}
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 balanceAfter = IERC20(token).balanceOf(address(this));
require(balanceAfter > balanceBefore, 'TS_INVALID_TRANSFER');
if (balanceBefore > 0) {
uint256 lastShares = data.totalShares[token];
data.totalShares[token] = lastShares.mul(balanceAfter).div(balanceBefore);
return data.totalShares[token] - lastShares;
} else {
data.totalShares[token] = balanceAfter;
data.totalShares[token] = balanceAfter;
return balanceAfter;
}
}
}
function onUnwrapFailed(
Data storage data,
address to,
uint256 amount
) external {
emit UnwrapFailed(to, amount);
IWETH(data.weth).deposit{ value: amount }();
TransferHelper.safeTransfer(data.weth, to, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import 'SafeMath.sol';
import 'Math.sol';
import 'IIntegralFactory.sol';
import 'IIntegralPair.sol';
import 'TokenShares.sol';
library Orders {
using SafeMath for uint256;
using TokenShares for TokenShares.Data;
using TransferHelper for address;
enum OrderType { Empty, Deposit, Withdraw, Sell, Buy }
enum OrderStatus { NonExistent, EnqueuedWaiting, EnqueuedReady, ExecutedSucceeded, ExecutedFailed, Canceled }
event MaxGasLimitSet(uint256 maxGasLimit);
event GasPriceInertiaSet(uint256 gasPriceInertia);
event MaxGasPriceImpactSet(uint256 maxGasPriceImpact);
event TransferGasCostSet(address token, uint256 gasCost);
event DepositEnqueued(uint256 indexed orderId, uint128 validAfterTimestamp, uint256 gasPrice);
event WithdrawEnqueued(uint256 indexed orderId, uint128 validAfterTimestamp, uint256 gasPrice);
event SellEnqueued(uint256 indexed orderId, uint128 validAfterTimestamp, uint256 gasPrice);
event BuyEnqueued(uint256 indexed orderId, uint128 validAfterTimestamp, uint256 gasPrice);
uint8 private constant DEPOSIT_TYPE = 1;
uint8 private constant WITHDRAW_TYPE = 2;
uint8 private constant BUY_TYPE = 3;
uint8 private constant BUY_INVERTED_TYPE = 4;
uint8 private constant SELL_TYPE = 5;
uint8 private constant SELL_INVERTED_TYPE = 6;
uint8 private constant UNWRAP_NOT_FAILED = 0;
uint8 private constant KEEP_NOT_FAILED = 1;
uint8 private constant UNWRAP_FAILED = 2;
uint8 private constant KEEP_FAILED = 3;
uint256 private constant ETHER_TRANSFER_COST = 2300;
uint256 private constant BUFFER_COST = 10000;
uint256 private constant EXECUTE_PREPARATION_COST = 55000; // dequeue + getPair in execute
uint256 public constant ETHER_TRANSFER_CALL_COST = 10000;
uint256 public constant PAIR_TRANSFER_COST = 55000;
uint256 public constant REFUND_END_COST = 2 * ETHER_TRANSFER_COST + BUFFER_COST;
uint256 public constant ORDER_BASE_COST = EXECUTE_PREPARATION_COST + REFUND_END_COST;
uint256 private constant TIMESTAMP_OFFSET = 1609455600; // 2021 Jan 1
struct PairInfo {
address pair;
address token0;
address token1;
}
struct Data {
uint256 delay;
uint256 newestOrderId;
uint256 lastProcessedOrderId;
mapping(uint256 => StoredOrder) orderQueue;
address factory;
uint256 maxGasLimit;
uint256 gasPrice;
uint256 gasPriceInertia;
uint256 maxGasPriceImpact;
mapping(uint32 => PairInfo) pairs;
mapping(address => uint256) transferGasCosts;
mapping(uint256 => bool) canceled;
mapping(address => bool) depositDisabled;
mapping(address => bool) withdrawDisabled;
mapping(address => bool) buyDisabled;
mapping(address => bool) sellDisabled;
}
struct StoredOrder {
// slot 1
uint8 orderType;
uint32 validAfterTimestamp;
uint8 unwrapAndFailure;
uint32 deadline;
uint32 gasLimit;
uint32 gasPrice;
uint112 liquidityOrRatio;
// slot 1
uint112 value0;
uint112 value1;
uint32 pairId;
// slot2
address to;
uint32 minRatioChangeToSwap;
uint32 minSwapPrice;
uint32 maxSwapPrice;
}
struct DepositOrder {
uint32 pairId;
uint256 share0;
uint256 share1;
uint256 initialRatio;
uint256 minRatioChangeToSwap;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool unwrap;
address to;
uint256 gasPrice;
uint256 gasLimit;
uint256 deadline;
}
struct WithdrawOrder {
uint32 pairId;
uint256 liquidity;
uint256 amount0Min;
uint256 amount1Min;
bool unwrap;
address to;
uint256 gasPrice;
uint256 gasLimit;
uint256 deadline;
}
struct SellOrder {
uint32 pairId;
bool inverse;
uint256 shareIn;
uint256 amountOutMin;
bool unwrap;
address to;
uint256 gasPrice;
uint256 gasLimit;
uint256 deadline;
}
struct BuyOrder {
uint32 pairId;
bool inverse;
uint256 shareInMax;
uint256 amountOut;
bool unwrap;
address to;
uint256 gasPrice;
uint256 gasLimit;
uint256 deadline;
}
function decodeType(uint256 internalType) internal pure returns (OrderType orderType) {
if (internalType == DEPOSIT_TYPE) {
orderType = OrderType.Deposit;
} else if (internalType == WITHDRAW_TYPE) {
orderType = OrderType.Withdraw;
} else if (internalType == BUY_TYPE) {
orderType = OrderType.Buy;
} else if (internalType == BUY_INVERTED_TYPE) {
orderType = OrderType.Buy;
} else if (internalType == SELL_TYPE) {
orderType = OrderType.Sell;
} else if (internalType == SELL_INVERTED_TYPE) {
orderType = OrderType.Sell;
} else {
orderType = OrderType.Empty;
}
}
function getOrder(Data storage data, uint256 orderId)
public
view
returns (OrderType orderType, uint256 validAfterTimestamp)
{
StoredOrder storage order = data.orderQueue[orderId];
uint8 internalType = order.orderType;
validAfterTimestamp = uint32ToTimestamp(order.validAfterTimestamp);
orderType = decodeType(internalType);
}
function getOrderStatus(Data storage data, uint256 orderId) external view returns (OrderStatus orderStatus) {
if (orderId > data.newestOrderId) {
return OrderStatus.NonExistent;
}
if (data.canceled[orderId]) {
return OrderStatus.Canceled;
}
if (isRefundFailed(data, orderId)) {
return OrderStatus.ExecutedFailed;
}
(OrderType orderType, uint256 validAfterTimestamp) = getOrder(data, orderId);
if (orderType == OrderType.Empty) {
return OrderStatus.ExecutedSucceeded;
}
if (validAfterTimestamp >= block.timestamp) {
return OrderStatus.EnqueuedWaiting;
}
return OrderStatus.EnqueuedReady;
}
function getPair(
Data storage data,
address tokenA,
address tokenB
)
internal
returns (
address pair,
uint32 pairId,
bool inverted
)
{
inverted = tokenA > tokenB;
(address token0, address token1) = inverted ? (tokenB, tokenA) : (tokenA, tokenB);
pair = IIntegralFactory(data.factory).getPair(token0, token1);
pairId = uint32(bytes4(keccak256(abi.encodePacked((pair)))));
require(pair != address(0), 'OS_PAIR_NONEXISTENT');
if (data.pairs[pairId].pair == address(0)) {
data.pairs[pairId] = PairInfo(pair, token0, token1);
}
}
function getPairInfo(Data storage data, uint32 pairId)
external
view
returns (
address pair,
address token0,
address token1
)
{
PairInfo storage info = data.pairs[pairId];
pair = info.pair;
token0 = info.token0;
token1 = info.token1;
}
function getDepositOrder(Data storage data, uint256 index) public view returns (DepositOrder memory order) {
StoredOrder memory stored = data.orderQueue[index];
require(stored.orderType == DEPOSIT_TYPE, 'OS_INVALID_ORDER_TYPE');
order.pairId = stored.pairId;
order.share0 = stored.value0;
order.share1 = stored.value1;
order.initialRatio = stored.liquidityOrRatio;
order.minRatioChangeToSwap = stored.minRatioChangeToSwap;
order.minSwapPrice = float32ToUint(stored.minSwapPrice);
order.maxSwapPrice = float32ToUint(stored.maxSwapPrice);
order.unwrap = getUnwrap(stored.unwrapAndFailure);
order.to = stored.to;
order.gasPrice = uint32ToGasPrice(stored.gasPrice);
order.gasLimit = stored.gasLimit;
order.deadline = uint32ToTimestamp(stored.deadline);
}
function getWithdrawOrder(Data storage data, uint256 index) public view returns (WithdrawOrder memory order) {
StoredOrder memory stored = data.orderQueue[index];
require(stored.orderType == WITHDRAW_TYPE, 'OS_INVALID_ORDER_TYPE');
order.pairId = stored.pairId;
order.liquidity = stored.liquidityOrRatio;
order.amount0Min = stored.value0;
order.amount1Min = stored.value1;
order.unwrap = getUnwrap(stored.unwrapAndFailure);
order.to = stored.to;
order.gasPrice = uint32ToGasPrice(stored.gasPrice);
order.gasLimit = stored.gasLimit;
order.deadline = uint32ToTimestamp(stored.deadline);
}
function getSellOrder(Data storage data, uint256 index) public view returns (SellOrder memory order) {
StoredOrder memory stored = data.orderQueue[index];
require(stored.orderType == SELL_TYPE || stored.orderType == SELL_INVERTED_TYPE, 'OS_INVALID_ORDER_TYPE');
order.pairId = stored.pairId;
order.inverse = stored.orderType == SELL_INVERTED_TYPE;
order.shareIn = stored.value0;
order.amountOutMin = stored.value1;
order.unwrap = getUnwrap(stored.unwrapAndFailure);
order.to = stored.to;
order.gasPrice = uint32ToGasPrice(stored.gasPrice);
order.gasLimit = stored.gasLimit;
order.deadline = uint32ToTimestamp(stored.deadline);
}
function getBuyOrder(Data storage data, uint256 index) public view returns (BuyOrder memory order) {
StoredOrder memory stored = data.orderQueue[index];
require(stored.orderType == BUY_TYPE || stored.orderType == BUY_INVERTED_TYPE, 'OS_INVALID_ORDER_TYPE');
order.pairId = stored.pairId;
order.inverse = stored.orderType == BUY_INVERTED_TYPE;
order.shareInMax = stored.value0;
order.amountOut = stored.value1;
order.unwrap = getUnwrap(stored.unwrapAndFailure);
order.to = stored.to;
order.gasPrice = uint32ToGasPrice(stored.gasPrice);
order.gasLimit = stored.gasLimit;
order.deadline = uint32ToTimestamp(stored.deadline);
}
function getFailedOrderType(Data storage data, uint256 orderId)
external
view
returns (OrderType orderType, uint256 validAfterTimestamp)
{
require(isRefundFailed(data, orderId), 'OS_NO_POSSIBLE_REFUND');
(orderType, validAfterTimestamp) = getOrder(data, orderId);
}
function getUnwrap(uint8 unwrapAndFailure) private pure returns (bool) {
return unwrapAndFailure == UNWRAP_FAILED || unwrapAndFailure == UNWRAP_NOT_FAILED;
}
function getUnwrapAndFailure(bool unwrap) private pure returns (uint8) {
return unwrap ? UNWRAP_NOT_FAILED : KEEP_NOT_FAILED;
}
function timestampToUint32(uint256 timestamp) private pure returns (uint32 timestamp32) {
if (timestamp == uint256(-1)) {
return uint32(-1);
}
timestamp32 = uintToUint32(timestamp.sub(TIMESTAMP_OFFSET));
}
function uint32ToTimestamp(uint32 timestamp32) private pure returns (uint256 timestamp) {
if (timestamp32 == uint32(-1)) {
return uint256(-1);
}
if (timestamp32 == 0) {
return 0;
}
timestamp = uint256(timestamp32) + TIMESTAMP_OFFSET;
}
function gasPriceToUint32(uint256 gasPrice) private pure returns (uint32 gasPrice32) {
require((gasPrice / 1e6) * 1e6 == gasPrice, 'OS_GAS_PRICE_PRECISION');
gasPrice32 = uintToUint32(gasPrice / 1e6);
}
function uint32ToGasPrice(uint32 gasPrice32) public pure returns (uint256 gasPrice) {
gasPrice = uint256(gasPrice32) * 1e6;
}
function uintToUint32(uint256 number) private pure returns (uint32 number32) {
number32 = uint32(number);
require(uint256(number32) == number, 'OS_OVERFLOW_32');
}
function uintToUint112(uint256 number) private pure returns (uint112 number112) {
number112 = uint112(number);
require(uint256(number112) == number, 'OS_OVERFLOW_112');
}
function uintToFloat32(uint256 number) internal pure returns (uint32 float32) {
// Number is encoded on 4 bytes. 3 bytes for mantissa and 1 for exponent.
// If the number fits in the mantissa we set the exponent to zero and return.
if (number < 2 << 24) {
return uint32(number << 8);
}
// We find the exponent by counting the number of trailing zeroes.
// Simultaneously we remove those zeroes from the number.
uint32 exponent;
for (exponent = 0; exponent < 256 - 24; exponent++) {
// Last bit is one.
if (number & 1 == 1) {
break;
}
number = number >> 1;
}
// The number must fit in the mantissa.
require(number < 2 << 24, 'OS_OVERFLOW_FLOAT_ENCODE');
// Set the first three bytes to the number and the fourth to the exponent.
float32 = uint32(number << 8) | exponent;
}
function float32ToUint(uint32 float32) internal pure returns (uint256 number) {
// Number is encoded on 4 bytes. 3 bytes for mantissa and 1 for exponent.
// We get the exponent by extracting the last byte.
uint256 exponent = float32 & 0xFF;
// Sanity check. Only triggered for values not encoded with uintToFloat32.
require(exponent <= 256 - 24, 'OS_OVERFLOW_FLOAT_DECODE');
// We get the mantissa by extracting the first three bytes and removing the fourth.
uint256 mantissa = (float32 & 0xFFFFFF00) >> 8;
// We add exponent number zeroes after the mantissa.
number = mantissa << exponent;
}
function enqueueDepositOrder(Data storage data, DepositOrder memory depositOrder) internal {
data.newestOrderId++;
uint128 validAfterTimestamp = uint128(block.timestamp + data.delay);
emit DepositEnqueued(data.newestOrderId, validAfterTimestamp, depositOrder.gasPrice);
data.orderQueue[data.newestOrderId] = StoredOrder(
DEPOSIT_TYPE,
timestampToUint32(validAfterTimestamp),
getUnwrapAndFailure(depositOrder.unwrap),
timestampToUint32(depositOrder.deadline),
uintToUint32(depositOrder.gasLimit),
gasPriceToUint32(depositOrder.gasPrice),
uintToUint112(depositOrder.initialRatio),
uintToUint112(depositOrder.share0),
uintToUint112(depositOrder.share1),
depositOrder.pairId,
depositOrder.to,
uint32(depositOrder.minRatioChangeToSwap),
uintToFloat32(depositOrder.minSwapPrice),
uintToFloat32(depositOrder.maxSwapPrice)
);
}
function enqueueWithdrawOrder(Data storage data, WithdrawOrder memory withdrawOrder) internal {
data.newestOrderId++;
uint128 validAfterTimestamp = uint128(block.timestamp + data.delay);
emit WithdrawEnqueued(data.newestOrderId, validAfterTimestamp, withdrawOrder.gasPrice);
data.orderQueue[data.newestOrderId] = StoredOrder(
WITHDRAW_TYPE,
timestampToUint32(validAfterTimestamp),
getUnwrapAndFailure(withdrawOrder.unwrap),
timestampToUint32(withdrawOrder.deadline),
uintToUint32(withdrawOrder.gasLimit),
gasPriceToUint32(withdrawOrder.gasPrice),
uintToUint112(withdrawOrder.liquidity),
uintToUint112(withdrawOrder.amount0Min),
uintToUint112(withdrawOrder.amount1Min),
withdrawOrder.pairId,
withdrawOrder.to,
0, // maxRatioChange
0, // minSwapPrice
0 // maxSwapPrice
);
}
function enqueueSellOrder(Data storage data, SellOrder memory sellOrder) internal {
data.newestOrderId++;
uint128 validAfterTimestamp = uint128(block.timestamp + data.delay);
emit SellEnqueued(data.newestOrderId, validAfterTimestamp, sellOrder.gasPrice);
data.orderQueue[data.newestOrderId] = StoredOrder(
sellOrder.inverse ? SELL_INVERTED_TYPE : SELL_TYPE,
timestampToUint32(validAfterTimestamp),
getUnwrapAndFailure(sellOrder.unwrap),
timestampToUint32(sellOrder.deadline),
uintToUint32(sellOrder.gasLimit),
gasPriceToUint32(sellOrder.gasPrice),
0, // liquidityOrRatio
uintToUint112(sellOrder.shareIn),
uintToUint112(sellOrder.amountOutMin),
sellOrder.pairId,
sellOrder.to,
0, // maxRatioChange
0, // minSwapPrice
0 // maxSwapPrice
);
}
function enqueueBuyOrder(Data storage data, BuyOrder memory buyOrder) internal {
data.newestOrderId++;
uint128 validAfterTimestamp = uint128(block.timestamp + data.delay);
emit BuyEnqueued(data.newestOrderId, validAfterTimestamp, buyOrder.gasPrice);
data.orderQueue[data.newestOrderId] = StoredOrder(
buyOrder.inverse ? BUY_INVERTED_TYPE : BUY_TYPE,
timestampToUint32(validAfterTimestamp),
getUnwrapAndFailure(buyOrder.unwrap),
timestampToUint32(buyOrder.deadline),
uintToUint32(buyOrder.gasLimit),
gasPriceToUint32(buyOrder.gasPrice),
0, // liquidityOrRatio
uintToUint112(buyOrder.shareInMax),
uintToUint112(buyOrder.amountOut),
buyOrder.pairId,
buyOrder.to,
0, // maxRatioChange
0, // minSwapPrice
0 // maxSwapPrice
);
}
function isRefundFailed(Data storage data, uint256 index) internal view returns (bool) {
uint8 unwrapAndFailure = data.orderQueue[index].unwrapAndFailure;
return unwrapAndFailure == UNWRAP_FAILED || unwrapAndFailure == KEEP_FAILED;
}
function markRefundFailed(Data storage data) internal {
StoredOrder storage stored = data.orderQueue[data.lastProcessedOrderId];
stored.unwrapAndFailure = stored.unwrapAndFailure == UNWRAP_NOT_FAILED ? UNWRAP_FAILED : KEEP_FAILED;
}
function getNextOrder(Data storage data) internal view returns (OrderType orderType, uint256 validAfterTimestamp) {
return getOrder(data, data.lastProcessedOrderId + 1);
}
function dequeueCanceledOrder(Data storage data) external {
data.lastProcessedOrderId++;
}
function dequeueDepositOrder(Data storage data) external returns (DepositOrder memory order) {
data.lastProcessedOrderId++;
order = getDepositOrder(data, data.lastProcessedOrderId);
}
function dequeueWithdrawOrder(Data storage data) external returns (WithdrawOrder memory order) {
data.lastProcessedOrderId++;
order = getWithdrawOrder(data, data.lastProcessedOrderId);
}
function dequeueSellOrder(Data storage data) external returns (SellOrder memory order) {
data.lastProcessedOrderId++;
order = getSellOrder(data, data.lastProcessedOrderId);
}
function dequeueBuyOrder(Data storage data) external returns (BuyOrder memory order) {
data.lastProcessedOrderId++;
order = getBuyOrder(data, data.lastProcessedOrderId);
}
function forgetOrder(Data storage data, uint256 orderId) internal {
delete data.orderQueue[orderId];
}
function forgetLastProcessedOrder(Data storage data) internal {
delete data.orderQueue[data.lastProcessedOrderId];
}
struct DepositParams {
address token0;
address token1;
uint256 amount0;
uint256 amount1;
uint256 initialRatio;
uint256 minRatioChangeToSwap;
uint256 minSwapPrice;
uint256 maxSwapPrice;
bool wrap;
address to;
uint256 gasLimit;
uint256 submitDeadline;
uint256 executionDeadline;
}
function deposit(
Data storage data,
DepositParams calldata depositParams,
TokenShares.Data storage tokenShares
) external {
require(
data.transferGasCosts[depositParams.token0] != 0 && data.transferGasCosts[depositParams.token1] != 0,
'OS_TOKEN_TRANSFER_GAS_COST_UNSET'
);
checkOrderParams(
data,
depositParams.to,
depositParams.gasLimit,
depositParams.submitDeadline,
depositParams.executionDeadline,
ORDER_BASE_COST.add(data.transferGasCosts[depositParams.token0]).add(
data.transferGasCosts[depositParams.token1]
)
);
require(depositParams.amount0 != 0 || depositParams.amount1 != 0, 'OS_NO_AMOUNT');
(address pair, uint32 pairId, bool inverted) = getPair(data, depositParams.token0, depositParams.token1);
require(!data.depositDisabled[pair], 'OS_DEPOSIT_DISABLED');
uint256 value = msg.value;
// allocate gas refund
if (depositParams.token0 == tokenShares.weth && depositParams.wrap) {
value = value.sub(depositParams.amount0, 'OS_NOT_ENOUGH_FUNDS');
} else if (depositParams.token1 == tokenShares.weth && depositParams.wrap) {
value = value.sub(depositParams.amount1, 'OS_NOT_ENOUGH_FUNDS');
}
allocateGasRefund(data, value, depositParams.gasLimit);
uint256 shares0 = tokenShares.amountToShares(depositParams.token0, depositParams.amount0, depositParams.wrap);
uint256 shares1 = tokenShares.amountToShares(depositParams.token1, depositParams.amount1, depositParams.wrap);
IIntegralPair(pair).syncWithOracle();
enqueueDepositOrder(
data,
DepositOrder(
pairId,
inverted ? shares1 : shares0,
inverted ? shares0 : shares1,
depositParams.initialRatio,
depositParams.minRatioChangeToSwap,
depositParams.minSwapPrice,
depositParams.maxSwapPrice,
depositParams.wrap,
depositParams.to,
data.gasPrice,
depositParams.gasLimit,
depositParams.executionDeadline
)
);
}
struct WithdrawParams {
address token0;
address token1;
uint256 liquidity;
uint256 amount0Min;
uint256 amount1Min;
bool unwrap;
address to;
uint256 gasLimit;
uint256 submitDeadline;
uint256 executionDeadline;
}
function withdraw(Data storage data, WithdrawParams calldata withdrawParams) external {
(address pair, uint32 pairId, bool inverted) = getPair(data, withdrawParams.token0, withdrawParams.token1);
require(!data.withdrawDisabled[pair], 'OS_WITHDRAW_DISABLED');
checkOrderParams(
data,
withdrawParams.to,
withdrawParams.gasLimit,
withdrawParams.submitDeadline,
withdrawParams.executionDeadline,
ORDER_BASE_COST.add(PAIR_TRANSFER_COST)
);
require(withdrawParams.liquidity != 0, 'OS_NO_LIQUIDITY');
allocateGasRefund(data, msg.value, withdrawParams.gasLimit);
pair.safeTransferFrom(msg.sender, address(this), withdrawParams.liquidity);
IIntegralPair(pair).syncWithOracle();
enqueueWithdrawOrder(
data,
WithdrawOrder(
pairId,
withdrawParams.liquidity,
inverted ? withdrawParams.amount1Min : withdrawParams.amount0Min,
inverted ? withdrawParams.amount0Min : withdrawParams.amount1Min,
withdrawParams.unwrap,
withdrawParams.to,
data.gasPrice,
withdrawParams.gasLimit,
withdrawParams.executionDeadline
)
);
}
struct SellParams {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOutMin;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint256 submitDeadline;
uint256 executionDeadline;
}
function sell(
Data storage data,
SellParams calldata sellParams,
TokenShares.Data storage tokenShares
) external {
require(data.transferGasCosts[sellParams.tokenIn] != 0, 'OS_TOKEN_TRANSFER_GAS_COST_UNSET');
checkOrderParams(
data,
sellParams.to,
sellParams.gasLimit,
sellParams.submitDeadline,
sellParams.executionDeadline,
ORDER_BASE_COST.add(data.transferGasCosts[sellParams.tokenIn])
);
require(sellParams.amountIn != 0, 'OS_NO_AMOUNT_IN');
(address pair, uint32 pairId, bool inverted) = getPair(data, sellParams.tokenIn, sellParams.tokenOut);
require(!data.sellDisabled[pair], 'OS_SELL_DISABLED');
uint256 value = msg.value;
// allocate gas refund
if (sellParams.tokenIn == tokenShares.weth && sellParams.wrapUnwrap) {
value = value.sub(sellParams.amountIn, 'OS_NOT_ENOUGH_FUNDS');
}
allocateGasRefund(data, value, sellParams.gasLimit);
uint256 shares = tokenShares.amountToShares(sellParams.tokenIn, sellParams.amountIn, sellParams.wrapUnwrap);
IIntegralPair(pair).syncWithOracle();
enqueueSellOrder(
data,
SellOrder(
pairId,
inverted,
shares,
sellParams.amountOutMin,
sellParams.wrapUnwrap,
sellParams.to,
data.gasPrice,
sellParams.gasLimit,
sellParams.executionDeadline
)
);
}
struct BuyParams {
address tokenIn;
address tokenOut;
uint256 amountInMax;
uint256 amountOut;
bool wrapUnwrap;
address to;
uint256 gasLimit;
uint256 submitDeadline;
uint256 executionDeadline;
}
function buy(
Data storage data,
BuyParams calldata buyParams,
TokenShares.Data storage tokenShares
) external {
require(data.transferGasCosts[buyParams.tokenIn] != 0, 'OS_TOKEN_TRANSFER_GAS_COST_UNSET');
checkOrderParams(
data,
buyParams.to,
buyParams.gasLimit,
buyParams.submitDeadline,
buyParams.executionDeadline,
ORDER_BASE_COST.add(data.transferGasCosts[buyParams.tokenIn])
);
require(buyParams.amountOut != 0, 'OS_NO_AMOUNT_OUT');
(address pair, uint32 pairId, bool inverted) = getPair(data, buyParams.tokenIn, buyParams.tokenOut);
require(!data.buyDisabled[pair], 'OS_BUY_DISABLED');
uint256 value = msg.value;
// allocate gas refund
if (buyParams.tokenIn == tokenShares.weth && buyParams.wrapUnwrap) {
value = value.sub(buyParams.amountInMax, 'OS_NOT_ENOUGH_FUNDS');
}
allocateGasRefund(data, value, buyParams.gasLimit);
uint256 shares = tokenShares.amountToShares(buyParams.tokenIn, buyParams.amountInMax, buyParams.wrapUnwrap);
IIntegralPair(pair).syncWithOracle();
enqueueBuyOrder(
data,
BuyOrder(
pairId,
inverted,
shares,
buyParams.amountOut,
buyParams.wrapUnwrap,
buyParams.to,
data.gasPrice,
buyParams.gasLimit,
buyParams.executionDeadline
)
);
}
function checkOrderParams(
Data storage data,
address to,
uint256 gasLimit,
uint256 submitDeadline,
uint256 executionDeadline,
uint256 minGasLimit
) private view {
require(submitDeadline >= block.timestamp, 'OS_EXPIRED');
require(executionDeadline > block.timestamp.add(data.delay), 'OS_INVALID_DEADLINE');
require(gasLimit <= data.maxGasLimit, 'OS_GAS_LIMIT_TOO_HIGH');
require(gasLimit >= minGasLimit, 'OS_GAS_LIMIT_TOO_LOW');
require(to != address(0), 'OS_NO_ADDRESS');
}
function allocateGasRefund(
Data storage data,
uint256 value,
uint256 gasLimit
) private returns (uint256 futureFee) {
futureFee = data.gasPrice.mul(gasLimit);
require(value >= futureFee, 'OS_NOT_ENOUGH_FUNDS');
if (value > futureFee) {
msg.sender.transfer(value.sub(futureFee));
}
}
function updateGasPrice(Data storage data, uint256 gasUsed) external {
uint256 scale = Math.min(gasUsed, data.maxGasPriceImpact);
uint256 updated = data.gasPrice.mul(data.gasPriceInertia.sub(scale)).add(tx.gasprice.mul(scale)).div(
data.gasPriceInertia
);
// we lower the precision for gas savings in order queue
data.gasPrice = updated - (updated % 1e6);
}
function setMaxGasLimit(Data storage data, uint256 _maxGasLimit) external {
require(_maxGasLimit <= 10000000, 'OS_MAX_GAS_LIMIT_TOO_HIGH');
data.maxGasLimit = _maxGasLimit;
emit MaxGasLimitSet(_maxGasLimit);
}
function setGasPriceInertia(Data storage data, uint256 _gasPriceInertia) external {
require(_gasPriceInertia >= 1, 'OS_INVALID_INERTIA');
data.gasPriceInertia = _gasPriceInertia;
emit GasPriceInertiaSet(_gasPriceInertia);
}
function setMaxGasPriceImpact(Data storage data, uint256 _maxGasPriceImpact) external {
require(_maxGasPriceImpact <= data.gasPriceInertia, 'OS_INVALID_MAX_GAS_PRICE_IMPACT');
data.maxGasPriceImpact = _maxGasPriceImpact;
emit MaxGasPriceImpactSet(_maxGasPriceImpact);
}
function setTransferGasCost(
Data storage data,
address token,
uint256 gasCost
) external {
data.transferGasCosts[token] = gasCost;
emit TransferGasCostSet(token, gasCost);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Deployed with donations via Gitcoin GR9
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import 'IIntegralPair.sol';
import 'IWETH.sol';
import 'Orders.sol';
library WithdrawHelper {
using SafeMath for uint256;
function _transferToken(
uint256 balanceBefore,
address token,
address to
) internal {
uint256 tokenAmount = IERC20(token).balanceOf(address(this)).sub(balanceBefore);
TransferHelper.safeTransfer(token, to, tokenAmount);
}
function _unwrapWeth(
uint256 ethAmount,
address weth,
address to
) internal returns (bool) {
IWETH(weth).withdraw(ethAmount);
(bool success, ) = to.call{ value: ethAmount, gas: Orders.ETHER_TRANSFER_CALL_COST }('');
return success;
}
function withdrawAndUnwrap(
address token0,
address token1,
address pair,
address weth,
address to
)
external
returns (
bool,
uint256,
uint256,
uint256
)
{
bool isToken0Weth = token0 == weth;
address otherToken = isToken0Weth ? token1 : token0;
uint256 balanceBefore = IERC20(otherToken).balanceOf(address(this));
(uint256 amount0, uint256 amount1) = IIntegralPair(pair).burn(address(this));
_transferToken(balanceBefore, otherToken, to);
bool success = _unwrapWeth(isToken0Weth ? amount0 : amount1, weth, to);
return (success, isToken0Weth ? amount0 : amount1, amount0, amount1);
}
}
| bytes4(keccak256(bytes('transfer(address,uint256)'))); | function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TH_TRANSFER_FAILED');
}
| 283,806 |
./full_match/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/api/Processor.sol | Submitted Pyth price is bound by the Chainlink price | ) internal pure returns (bool) {
if (chainlinkPrice == 0 || maxDeviation == 0) return true;
if (
price >= (chainlinkPrice * (BPS_DIVIDER - maxDeviation)) / BPS_DIVIDER &&
price <= (chainlinkPrice * (BPS_DIVIDER + maxDeviation)) / BPS_DIVIDER
function _boundPriceWithChainlink(
uint256 maxDeviation,
uint256 chainlinkPrice,
uint256 price
) {
return true;
}
return false;
}
| 11,525,736 |
pragma solidity 0.4.18;
/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
/// @author Stefan George - <[email protected]>
contract MultiSigWallet {
uint constant public MAX_OWNER_COUNT = 50;
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
modifier onlyWallet() {
require (msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require (!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require (isOwner[owner]);
_;
}
modifier transactionExists(uint transactionId) {
require (transactions[transactionId].destination != 0);
_;
}
modifier confirmed(uint transactionId, address owner) {
require (confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require (!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint transactionId) {
require (!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require (_address != 0);
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require (ownerCount <= MAX_OWNER_COUNT);
require (_required <= ownerCount);
require (_required != 0);
require (ownerCount != 0);
_;
}
/// @dev Fallback function allows to deposit ether.
function()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
function MultiSigWallet(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
require ( !isOwner[_owners[i]]);
require (_owners[i] != 0);
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param owner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
/// @title Multisignature wallet with daily limit - Allows an owner to withdraw a daily limit without multisig.
/// @author Stefan George - <[email protected]>
contract MultiSigWalletWithDailyLimit is MultiSigWallet {
event DailyLimitChange(uint dailyLimit);
uint public dailyLimit;
uint public lastDay;
uint public spentToday;
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners, required number of confirmations and daily withdraw limit.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
/// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis.
function MultiSigWalletWithDailyLimit(address[] _owners, uint _required, uint _dailyLimit)
public
MultiSigWallet(_owners, _required)
{
dailyLimit = _dailyLimit;
}
/// @dev Allows to change the daily limit. Transaction has to be sent by wallet.
/// @param _dailyLimit Amount in wei.
function changeDailyLimit(uint _dailyLimit)
public
onlyWallet
{
dailyLimit = _dailyLimit;
DailyLimitChange(_dailyLimit);
}
/// @dev Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
Transaction storage txn = transactions[transactionId];
bool confirmed = isConfirmed(transactionId);
if (confirmed || txn.data.length == 0 && isUnderLimit(txn.value)) {
txn.executed = true;
if (!confirmed)
spentToday += txn.value;
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
if (!confirmed)
spentToday -= txn.value;
}
}
}
/*
* Internal functions
*/
/// @dev Returns if amount is within daily limit and resets spentToday after one day.
/// @param amount Amount to withdraw.
/// @return Returns if amount is under daily limit.
function isUnderLimit(uint amount)
internal
returns (bool)
{
if (now > lastDay + 24 hours) {
lastDay = now;
spentToday = 0;
}
if (spentToday + amount > dailyLimit || spentToday + amount < spentToday)
return false;
return true;
}
/*
* Web3 call functions
*/
/// @dev Returns maximum withdraw amount.
/// @return Returns amount.
function calcMaxWithdraw()
public
constant
returns (uint)
{
if (now > lastDay + 24 hours)
return dailyLimit;
if (dailyLimit < spentToday)
return 0;
return dailyLimit - spentToday;
}
} | Allows to add a new owner. Transaction has to be sent by wallet. owner Address of new owner. | function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
| 39,642 |
./partial_match/1/0xE6B3C373380896e671c5a94E3f74cd2527324466/sources/contracts/feeding/Feeding.sol | Calculates the minimum amount of tokens to receive from a swap, accounting for slippage. _tokenIn Token to be swapped _amountIn Amount of tokens to be swapped _slippage Maximum allowable slippage for the swap return Minimum amount of tokens to receive/ | function _calculateAmountOutMin(
address _tokenIn,
uint256 _amountIn,
uint256 _slippage
) internal view returns (uint256) {
uint256[] memory amountsOut = IUniswapV2Router02(routerAddress).getAmountsOut(_amountIn, tokenPath[_tokenIn]);
uint256 amount = amountsOut[amountsOut.length - 1];
return (amount -
intoUint256(ud(amount) * ud((_slippage * 1e14) / 100)));
}
| 4,083,742 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// Part: IAlphaV2
interface IAlphaV2 {
// ERC20 part
function balanceOf(address) external view returns (uint256);
// AlphaV2 view interface
function cToken() external view returns (address);
// VaultV2 user interface
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
function claim(uint256 totalReward, bytes32[] memory proof) external;
}
// Part: ICErc20
interface ICErc20 {
function exchangeRateStored() external view returns (uint256);
}
// Part: IFund
interface IFund {
function underlying() external view returns (address);
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdraw(uint256 numberOfShares) external;
function getPricePerShare() external view returns (uint256);
function totalValueLocked() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder)
external
view
returns (uint256);
}
// Part: IGovernable
interface IGovernable {
function governance() external view returns (address);
}
// Part: IStrategy
interface IStrategy {
function underlying() external view returns (address);
function fund() external view returns (address);
function creator() external view returns (address);
function withdrawAllToFund() external;
function withdrawToFund(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256);
function doHardWork() external;
function depositArbCheck() external view returns (bool);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @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");
}
}
}
// Part: AlphaV2LendingStrategyBase
/**
* This strategy takes an asset (DAI, USDC), lends to AlphaV2 Lending Box.
*/
contract AlphaV2LendingStrategyBase is IStrategy {
enum TokenIndex {DAI, USDC}
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public override underlying;
address public override fund;
address public override creator;
// the matching enum record used to determine the index
TokenIndex tokenIndex;
// the alphasafebox corresponding to the underlying asset
address public aBox;
// these tokens cannot be claimed by the governance
mapping(address => bool) public canNotSweep;
bool public investActivated;
constructor(
address _fund,
address _aBox,
uint256 _tokenIndex
) public {
require(_fund != address(0), "Fund cannot be empty");
fund = _fund;
underlying = IFund(fund).underlying();
tokenIndex = TokenIndex(_tokenIndex);
aBox = _aBox;
creator = msg.sender;
// restricted tokens, can not be swept
canNotSweep[underlying] = true;
canNotSweep[aBox] = true;
investActivated = true;
}
function governance() internal view returns (address) {
return IGovernable(fund).governance();
}
modifier onlyFundOrGovernance() {
require(
msg.sender == fund || msg.sender == governance(),
"The sender has to be the governance or fund"
);
_;
}
/**
* TODO
*/
function depositArbCheck() public view override returns (bool) {
return true;
}
/**
* Allows Governance to withdraw partial shares to reduce slippage incurred
* and facilitate migration / withdrawal / strategy switch
*/
function withdrawPartialShares(uint256 shares)
external
onlyFundOrGovernance
{
IAlphaV2(aBox).withdraw(shares);
}
function setInvestActivated(bool _investActivated)
external
onlyFundOrGovernance
{
investActivated = _investActivated;
}
/**
* Withdraws an underlying asset from the strategy to the fund in the specified amount.
* It tries to withdraw from the strategy contract if this has enough balance.
* Otherwise, we withdraw shares from the Alpha V2 Lending Box. Transfer the required underlying amount to fund,
* and reinvest the rest. We can make it better by calculating the correct amount and withdrawing only that much.
*/
function withdrawToFund(uint256 underlyingAmount)
external
override
onlyFundOrGovernance
{
uint256 underlyingBalanceBefore =
IERC20(underlying).balanceOf(address(this));
if (underlyingBalanceBefore >= underlyingAmount) {
IERC20(underlying).safeTransfer(fund, underlyingAmount);
return;
}
uint256 shares =
shareValueFromUnderlying(
underlyingAmount.sub(underlyingBalanceBefore)
);
IAlphaV2(aBox).withdraw(shares);
// we can transfer the asset to the fund
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeTransfer(
fund,
Math.min(underlyingAmount, underlyingBalance)
);
}
}
/**
* Withdraws all assets from the Alpha V2 Lending Box and transfers to Fund.
*/
function withdrawAllToFund() external override onlyFundOrGovernance {
uint256 shares = IAlphaV2(aBox).balanceOf(address(this));
IAlphaV2(aBox).withdraw(shares);
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeTransfer(fund, underlyingBalance);
}
}
/**
* Invests all underlying assets into our Alpha V2 Lending Box.
*/
function investAllUnderlying() internal {
if (!investActivated) {
return;
}
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(aBox, 0);
IERC20(underlying).safeApprove(aBox, underlyingBalance);
// deposits the entire balance to Alpha V2 Lending Box
IAlphaV2(aBox).deposit(underlyingBalance);
}
}
/**
* The hard work only invests all underlying assets
*/
function doHardWork() public override onlyFundOrGovernance {
investAllUnderlying();
}
// no tokens apart from underlying should be sent to this contract. Any tokens that are sent here by mistake are recoverable by governance
function sweep(address _token, address _sweepTo) external {
require(governance() == msg.sender, "Not governance");
require(!canNotSweep[_token], "Token is restricted");
IERC20(_token).safeTransfer(
_sweepTo,
IERC20(_token).balanceOf(address(this))
);
}
/**
* Keeping this here as I did not find how to get totalReward
*/
function claim(uint256 totalReward, bytes32[] memory proof)
external
onlyFundOrGovernance
{
IAlphaV2(aBox).claim(totalReward, proof);
}
/**
* Returns the underlying invested balance. This is the underlying amount based on yield bearing token balance,
* plus the current balance of the underlying asset.
*/
function investedUnderlyingBalance()
external
view
override
returns (uint256)
{
uint256 shares = IERC20(aBox).balanceOf(address(this));
address cToken = IAlphaV2(aBox).cToken();
uint256 exchangeRate = ICErc20(cToken).exchangeRateStored();
uint256 precision = 10**18;
uint256 underlyingBalanceinABox =
shares.mul(exchangeRate).div(precision);
return
underlyingBalanceinABox.add(
IERC20(underlying).balanceOf(address(this))
);
}
/**
* Returns the value of the underlying token in aBox ibToken
*/
function shareValueFromUnderlying(uint256 underlyingAmount)
internal
view
returns (uint256)
{
return
underlyingAmount.mul(10**18).div(
ICErc20(IAlphaV2(aBox).cToken()).exchangeRateStored()
);
}
}
// File: AlphaV2LendingStrategyMainnet.sol
/**
* Adds the mainnet addresses to the AlphaV2LendingStrategyBase
*/
contract AlphaV2LendingStrategyMainnet is AlphaV2LendingStrategyBase {
// token addresses
address public constant dai =
address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public constant ibdaiv2 =
address(0xee8389d235E092b2945fE363e97CDBeD121A0439);
address public constant usdc =
address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address public constant ibusdcv2 =
address(0x08bd64BFC832F1C2B3e07e634934453bA7Fa2db2);
// pre-defined constant mapping: underlying -> aBox
mapping(address => address) public aBoxes;
constructor(address _fund)
public
AlphaV2LendingStrategyBase(_fund, address(0), 0)
{
aBoxes[dai] = ibdaiv2;
aBoxes[usdc] = ibusdcv2;
aBox = aBoxes[underlying];
require(
aBox != address(0),
"underlying not supported: aBox is not defined"
);
if (underlying == dai) {
tokenIndex = TokenIndex.DAI;
} else if (underlying == usdc) {
tokenIndex = TokenIndex.USDC;
} else {
revert("Asset not supported");
}
}
}
| Returns the underlying invested balance. This is the underlying amount based on yield bearing token balance, plus the current balance of the underlying asset./ | function investedUnderlyingBalance()
external
view
override
returns (uint256)
{
uint256 shares = IERC20(aBox).balanceOf(address(this));
address cToken = IAlphaV2(aBox).cToken();
uint256 exchangeRate = ICErc20(cToken).exchangeRateStored();
uint256 precision = 10**18;
uint256 underlyingBalanceinABox =
shares.mul(exchangeRate).div(precision);
return
underlyingBalanceinABox.add(
IERC20(underlying).balanceOf(address(this))
);
}
| 12,087,541 |
// SPDX-License-Identifier: MIT
/**
* @title obscurityDAO
* @email [email protected]
* @dev Nov 3, 2020
* ERC-20
* obscurityDAO Copyright and Disclaimer Notice:
*/
pragma solidity ^0.8.7 <0.9.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "./founders.sol";
contract crowdsalePhaseZero is IERC20Upgradeable, FounderWallets, ReentrancyGuardUpgradeable { // ContextUpgradeable,
event DepositFunds(address indexed sender, uint amount, uint balance);
IERC20Upgradeable private _token;
address private _wallet;
address payable _walletAddress;
uint256 private _rate;
uint256 private _ethAmountForSale;
uint256 private _currentPhase;
uint256 private initializedPhaseTwo;
uint256 private initializedPhaseThree;
uint256 private initializedPhaseFour;
uint256 private _weiRaised;
uint256 private phaseTwoETHAmount; // change before release depending on ETH price
uint256 private phaseThreeETHAmount; // change before release depending on ETH price
uint256 private phaseFourETHAmount; // change before release depending on ETH price
uint256 _crowdSalePaused;
uint256 private _crowdSalePhaseZeroInitialized;
mapping(address => bytes32[]) usedMessages;
function initialize() initializer public {
require(_crowdSalePhaseZeroInitialized == 0);
_crowdSalePhaseZeroInitialized = 1;
_founders_init();
__Context_init();
__ReentrancyGuard_init();
_ethAmountForSale = 200;
setPhase(1);
_rate = 5; //1;
_walletAddress = payable(address(0x920Bf81087C296D57B4F7f5fCfd96cA71582F066)); // company wallet proxy address
_wallet = address(0x920Bf81087C296D57B4F7f5fCfd96cA71582F066); // company wallet proxy address
_token = IERC20Upgradeable(address(0x1d036Bbb3535a112186103a51A93B452307Ebd30)); // OBSC token proxy address
_setupRole(DEFAULT_ADMIN_ROLE, tx.origin);
_setupRole(globals.ADMIN_ROLE, tx.origin);
_grantRole(globals.UPGRADER_ROLE, tx.origin);
_setupRole(globals.PAUSER_ROLE, address(0x60A7A4Ce65e314642991C46Bed7C1845588F6cD0));
_setupRole(globals.PAUSER_ROLE, address(0x6188b15bAE64416d779560D302546e5dE15E5d1E));
phaseTwoETHAmount = 600;
phaseThreeETHAmount = 4000;
phaseFourETHAmount = 20000;
}
receive() external payable {
emit DepositFunds(tx.origin, msg.value, _wallet.balance);
_forwardFunds();
}
function _forwardFunds() internal {
(bool success, ) = _wallet.call{value:msg.value}("");
require(success, "Transfer failed.");
}
function getPhaseZeroAddress() public view returns(address)
{
return address(this);
}
function getTokenAddress() public view returns(IERC20Upgradeable)
{
return _token;
}
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
fallback() external payable {
buyTokens(_msgSender());
}
function token() public view returns (IERC20Upgradeable) {
return _token;
}
function rate() public view returns (uint256) {
return _rate;
}
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
function buyTokens(address beneficiary) public payable nonReentrant() {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised + weiAmount;
_processPurchase(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "0");
require(weiAmount != 0, "1");
require(_crowdSalePaused == 0);
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
}
function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// solhint-disable-previous-line no-empty-blocks
}
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.transferForCrowdSale(address(ADMIN_ADDRESS), beneficiary, tokenAmount);
}
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// solhint-disable-previous-line no-empty-blocks
}
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount * ((10**9) * _rate / _ethAmountForSale); // 10^7 * 5 5B 1 eth 200eth 2500/eth
//return weiAmount * ((10**9) * _rate / 600); // 10^7 * 9 9B 1 eth 600eth 2500/eth
}
function pauseSale()
public {
require(hasRole(PAUSER_ROLE, msg.sender), "C");
_crowdSalePaused = 1;
}
function unpauseSale()
public {
require(hasRole(PAUSER_ROLE, msg.sender), "C");
_crowdSalePaused = 0;
}
function setPhaseTwoRate(uint256 ethAmount)
public {
require(hasRole(PAUSER_ROLE, msg.sender), "C");
require(_currentPhase == 1);
phaseTwoETHAmount = ethAmount;
}
function setPhaseThreeRate(uint256 ethAmount)
public {
require(hasRole(PAUSER_ROLE, msg.sender), "C");
require(_currentPhase == 2);
phaseThreeETHAmount = ethAmount;
}
function setPhaseFourRate(uint256 ethAmount)
public {
require(hasRole(PAUSER_ROLE, msg.sender), "C");
require(_currentPhase == 3);
phaseFourETHAmount = ethAmount;
}
function initiatePhaseTwo()
public {
require(hasRole(PAUSER_ROLE, msg.sender), "C");
require(initializedPhaseTwo != 1, "A.");
require(_currentPhase == 1);
initializedPhaseTwo = 1;
pauseSale();
setRate(9);
setETHAmount(phaseTwoETHAmount);
setPhase(2);
unpauseSale();
}
function initiatePhaseThree()
public {
require(hasRole(globals.PAUSER_ROLE, msg.sender), "C");
require(initializedPhaseThree != 1);
initializedPhaseThree = 1;
require(_currentPhase == 2);
pauseSale();
setRate(36);
setETHAmount(phaseThreeETHAmount);
setPhase(3);
unpauseSale();
}
function initiatePhaseFour()
public {
require(hasRole(PAUSER_ROLE, msg.sender), "C");
require(initializedPhaseFour != 1);
require(_currentPhase == 3);
initializedPhaseFour = 1;
pauseSale();
setRate(50);
setETHAmount(phaseFourETHAmount);
setPhase(4);
unpauseSale();
}
function getPhaseTwoETHRate() public view returns (uint256) {
return phaseTwoETHAmount;
}
function getPhaseThreeETHRate() public view returns (uint256) {
return phaseThreeETHAmount;
}
function getPhaseFourETHRate() public view returns (uint256) {
return phaseFourETHAmount;
}
function getSalePhase() public view returns (uint256) {
return _currentPhase;
}
function getSaleRate() public view returns (uint256) {
return _rate;
}
function getSaleETHAmount() public view returns (uint256) {
return _ethAmountForSale;
}
function setPhase(uint256 newPhase) internal {
_currentPhase = newPhase;
}
function setRate(uint256 newRate) internal {
_rate = newRate;
}
function setETHAmount(uint256 newAmount) internal {
_ethAmountForSale = newAmount;
}
/*overrides*/
function allowance(address owner, address spender) external override view returns (uint256) {
_token.allowance(owner, spender);
}
function approve(address spender, uint256 amount) external override returns (bool) {
return _token.approve(spender, amount);
}
function totalSupply() external override view returns (uint256) {
return _token.totalSupply();
}
function balanceOf(address account) external override view returns (uint256) {
return _token.balanceOf(account);
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _token.transfer(recipient, amount);
}
function transferForCrowdSale(
address sender,
address recipient,
uint256 amount
) external override {
_token.transferForCrowdSale(sender, recipient, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_token.transferFrom(sender, recipient, amount);
}
/*Founder functions - ETH Amount*/
function completeETHAmountChangeProposal(uint256 proposalID)
public
virtual onlyRole(PAUSER_ROLE) {
if(founderExecution(proposalID) == 1)
{
setETHAmount(proposalVotes[proposalID].newAmount);
}
}
function createETHAmountChangeProposal(uint256 newAmount, bytes32 desc)
public
virtual
nonReentrant()
onlyRole(PAUSER_ROLE) {
_createETHAmountProposal(newAmount, desc);
}
function getPState(uint256 proposalID)
public
view returns (uint256) {
return gPState(proposalID);
}
function getPDesc(uint256 proposalID)
public
view returns (bytes32) {
return gPDesc(proposalID);
}
function founderETHAmountChangeVote(
uint256 proposalID,
uint256 vote,
address to,
uint256 amount,
string memory message,
uint nonce,
bytes memory signature
) external
nonReentrant()
onlyRole(PAUSER_ROLE) {
if (tx.origin == founderOne.founderAddress) {
require(verify(founderOne.founderAddress, to, amount, message, nonce, signature) == true, "O");
f1VoteOnETHAmountChangeProposal(vote, proposalID);
}
if (tx.origin == founderTwo.founderAddress) {
require(verify(founderTwo.founderAddress, to, amount, message, nonce, signature) == true, "T");
f2VoteOnETHAmountChangeProposal(vote, proposalID);
}
}
/*Founder Functions - Addr*/
function completeAddrTransferProposal(uint256 proposalID)
public
virtual onlyRole(PAUSER_ROLE) {
addressSwapExecution(proposalID);
}
function createAddrTransferProposal(address payable oldAddr, address payable newAddr, bytes32 desc)
public
virtual
nonReentrant()
onlyRole(PAUSER_ROLE) {
_createAddressSwapProposal(oldAddr, newAddr, desc);
}
function getAddrPState(uint256 proposalID)
public
view returns (uint256) {
return gPSwapState(proposalID);
}
function getAddrPDesc(uint256 proposalID)
public
view returns (bytes32) {
return gPSwapDesc(proposalID);
}
function founderAddrVote(
uint256 proposalID,
uint256 vote,
address to,
uint256 amount,
string memory message,
uint nonce,
bytes memory signature
) external
nonReentrant()
onlyRole(PAUSER_ROLE) {
if (tx.origin == founderOne.founderAddress) {
require(verify(founderOne.founderAddress, to, amount, message, nonce, signature) == true);
f1VoteOnSwapProposal(vote, proposalID);
}
if (tx.origin == founderTwo.founderAddress) {
require(verify(founderTwo.founderAddress, to, amount, message, nonce, signature) == true);
f2VoteOnSwapProposal(vote, proposalID);
}
}
/*Signature Methods*/
function getMessageHash(
address _to,
uint _amount,
string memory _message,
uint _nonce
)
public
pure returns (bytes32) {
return keccak256(abi.encode(_to, _amount, _message, _nonce));
}
function verify(
address _signer,
address _to,
uint _amount,
string memory _message,
uint _nonce,
bytes memory signature
)
public returns (bool) {
bytes32 messageHash = getMessageHash(_to, _amount, _message, _nonce);
for(uint i = 0; i < usedMessages[tx.origin].length; i++) {
require(usedMessages[tx.origin][i] != messageHash);
}
bool temp = recoverSigner(messageHash, signature) == _signer;
if (temp)
usedMessages[tx.origin].push(messageHash);
return temp;
}
function recoverSigner(bytes32 msgHash, bytes memory _signature)
public
pure returns (address) {
bytes32 _temp = ECDSAUpgradeable.toEthSignedMessageHash(msgHash);
address tempAddr = ECDSAUpgradeable.recover(_temp, _signature);
return tempAddr;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function transferForCrowdSale(
address sender,
address recipient,
uint256 amount
) external;
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
/**
* @title obscurityDAO
* @email [email protected]
* @dev Nov 3, 2020
* ERC-20
* obscurityDAO Copyright and Disclaimer Notice:
*/
pragma solidity ^0.8.7 <0.9.0;
import "./globals.sol";
abstract contract FounderWallets is globals {
enum fps {
Active,
Defeated,
Succeeded,
ExecutedByFounders,
Queued
}
struct FounderWallet {
string founderAlias;
address payable founderAddress;
}
struct FounderETHAmountProposal {
uint256 f1Vote;
uint256 f2Vote;
bytes32 pDesc;
fps pState;
uint256 newAmount;
bool exists;
}
struct AddressSwapProposal {
uint256 f1Vote;
uint256 f2Vote;
bytes32 pDesc;
fps sState;
address payable swapOld;
address payable swapNew;
bool exists;
uint256 createdTime;
}
event ETHAmountProposalCreated(address indexed _from, uint256 _id, string _value);
event SwapAddressProposalCreated(address indexed _from, uint256 _id, string _value);
mapping(uint256 => FounderETHAmountProposal) proposalVotes;
mapping(uint256 => AddressSwapProposal) addressSwapProposalVotes;
FounderWallet founderOne;
FounderWallet founderTwo;
uint256 lastPID;
uint256 lastSwapPID;
function _founders_init()
internal
onlyInitializing {
globals_init();
addFounderOne(
"FO",
payable(address(0x60A7A4Ce65e314642991C46Bed7C1845588F6cD0))
// "FounderOne"
);
addFounderTwo(
"FT",
payable(address(0x6188b15bAE64416d779560D302546e5dE15E5d1E))
// "FounderTwo"
);
lastPID = 0;
lastSwapPID = 0;
}
function _createAddressSwapProposal(address payable oldAddr, address payable newAddr, bytes32 desc)
internal
virtual {
require(oldAddr == founderOne.founderAddress ||
oldAddr == founderTwo.founderAddress ||
oldAddr == globals.ADMIN_ADDRESS
);
if(!addressSwapProposalVotes[lastSwapPID + 1].exists) {
}
else require(1 == 0);
addressSwapProposalVotes[++lastSwapPID] = AddressSwapProposal( 0, 0,
desc, fps.Queued, oldAddr, newAddr, true, block.timestamp);
emit SwapAddressProposalCreated(msg.sender, lastSwapPID, "C");
}
function _createETHAmountProposal(uint256 newAmount, bytes32 desc)
internal
virtual {
if(!proposalVotes[lastPID + 1].exists) {
}
else require(1 == 0);
proposalVotes[++lastPID] = FounderETHAmountProposal(0, 0,
desc, fps.Queued, newAmount, true);
emit ETHAmountProposalCreated(msg.sender, lastPID, "C");
}
function sFOneAddress(address payable _newAddress)
private
onlyRole(globals.ADMIN_ROLE) {
founderOne.founderAddress = _newAddress;
}
function sFTwoAddress(address payable _newAddress)
private
onlyRole(globals.ADMIN_ROLE) {
founderOne.founderAddress = _newAddress;
}
function addFounderOne(
string memory _fAlias,
address payable _fAddress)
private {
if (
(keccak256(bytes(founderOne.founderAlias))) != keccak256(bytes("O"))
) {
founderOne = FounderWallet(_fAlias, _fAddress);
}
}
function addFounderTwo(
string memory _fAlias,
address payable _fAddress)
private {
if (
(keccak256(bytes(founderTwo.founderAlias))) != keccak256(bytes("T"))
) {
founderTwo = FounderWallet(_fAlias, _fAddress);
}
}
/*Functions on proposals to change address*/
function f1VoteOnSwapProposal(uint256 vote, uint256 proposalID)
internal
virtual {
AddressSwapProposal memory p = addressSwapProposalVotes[proposalID];
if(p.sState == fps.Defeated) {
require(1 == 0);
}
if(p.sState == fps.Queued)
addressSwapProposalVotes[proposalID].sState = fps.Active;
if(vote != 1) {
addressSwapProposalVotes[proposalID].f1Vote = vote;
addressSwapProposalVotes[proposalID].sState = fps.Defeated;
require(1 == 0);
}
if(vote == 1) {
addressSwapProposalVotes[proposalID].f1Vote = vote;
}
}
function f2VoteOnSwapProposal(uint256 vote, uint256 proposalID)
internal
virtual {
AddressSwapProposal memory p = addressSwapProposalVotes[proposalID];
if(p.sState == fps.Defeated) {
require(1 == 0);
}
if(p.sState == fps.Queued)
addressSwapProposalVotes[proposalID].sState = fps.Active;
if(vote != 1)
{
addressSwapProposalVotes[proposalID].f2Vote = vote;
addressSwapProposalVotes[proposalID].sState = fps.Defeated;
require(1 == 0);
}
if(vote == 1)
{
addressSwapProposalVotes[proposalID].f2Vote = vote;
}
}
function addressSwapExecution(uint256 proposalID)
internal
virtual {
addrSwapFinalState(proposalID);
AddressSwapProposal memory p = addressSwapProposalVotes[proposalID];
if (p.sState != fps.Succeeded)
require(1 == 0, "0");
if (founderOne.founderAddress == p.swapOld) {
founderOne.founderAddress = p.swapNew;
_revokeRole(globals.PAUSER_ROLE, p.swapOld);
_grantRole(globals.PAUSER_ROLE, p.swapNew);
}
else if(founderTwo.founderAddress == p.swapOld) {
founderTwo.founderAddress = p.swapNew;
_revokeRole(globals.PAUSER_ROLE, p.swapOld);
_grantRole(globals.PAUSER_ROLE, p.swapNew);
}
else if(globals.ADMIN_ADDRESS == p.swapOld)
{
_grantRole(globals.UPGRADER_ROLE, p.swapNew);
_grantRole(globals.ADMIN_ROLE, p.swapNew);
_grantRole(DEFAULT_ADMIN_ROLE, p.swapNew);
globals.ADMIN_ADDRESS == p.swapNew;
_revokeRole(globals.UPGRADER_ROLE, globals.ADMIN_ADDRESS);
_revokeRole(globals.ADMIN_ROLE, globals.ADMIN_ADDRESS);
_revokeRole(DEFAULT_ADMIN_ROLE, globals.ADMIN_ADDRESS);
}
addressSwapProposalVotes[proposalID].sState = fps.ExecutedByFounders;
}
function addrSwapFinalState(uint256 proposalID)
private {
AddressSwapProposal memory p = addressSwapProposalVotes[proposalID];
if(p.sState == fps.Defeated)
{
require(1 == 0, "1");
}
if (block.timestamp < p.createdTime + 30 days) {
require(p.f1Vote + p.f2Vote == 2, "N");
{
addressSwapProposalVotes[proposalID].sState = fps.Succeeded;
}
}
else {
addressSwapProposalVotes[proposalID].sState = fps.Succeeded;
}
}
function gPSwapState(uint256 proposalID)
public
view
returns (uint256) {
AddressSwapProposal memory p = addressSwapProposalVotes[proposalID];
if (p.sState == fps.Active)
return 1;
else if (p.sState == fps.Defeated)
return 4;
else if (p.sState == fps.Succeeded)
return 2;
else if (p.sState == fps.ExecutedByFounders)
return 3;
else
return 0;
}
function gPSwapDesc(uint256 proposalID)
public
view
returns (bytes32) {
AddressSwapProposal memory p = addressSwapProposalVotes[proposalID];
return p.pDesc;
}
/*Functions on proposals to change amount for current phase*/
function f1VoteOnETHAmountChangeProposal(uint256 vote, uint256 proposalID)
internal
virtual {
FounderETHAmountProposal memory p = proposalVotes[proposalID];
if(p.pState == fps.Defeated)
{
require(1 == 0, "C");
}
if(p.pState == fps.Queued)
p.pState = fps.Active;
if(vote != 1)
{
p.f1Vote = vote;
p.pState = fps.Defeated;
}
if(vote == 1)
{
p.f1Vote = vote;
}
proposalVotes[proposalID] = p;
}
function f2VoteOnETHAmountChangeProposal(uint256 vote, uint256 proposalID)
internal
virtual {
FounderETHAmountProposal memory p = proposalVotes[proposalID];
if(p.pState == fps.Defeated)
{
require(1 == 0);
}
if(p.pState == fps.Queued)
proposalVotes[proposalID].pState = fps.Active;
if(vote != 1)
{
proposalVotes[proposalID].f2Vote = vote;
proposalVotes[proposalID].pState = fps.Defeated;
}
if(vote == 1)
{
proposalVotes[proposalID].f2Vote = vote;
}
}
function founderExecution(uint256 proposalID)
internal
virtual returns (uint256) {
sFinalState(proposalID);
FounderETHAmountProposal memory p = proposalVotes[proposalID];
if (p.pState != fps.Succeeded)
require(1 == 0, "!");
proposalVotes[proposalID].pState = fps.ExecutedByFounders;
return 1;
}
function sFinalState(uint256 proposalID)
private {
FounderETHAmountProposal memory p = proposalVotes[proposalID];
if(p.pState == fps.Defeated) {
require(0 == 1);
}
else{
require(p.f1Vote + p.f2Vote == 2, "N");
proposalVotes[proposalID].pState = fps.Succeeded;
}
}
function gPState(uint256 proposalID)
public
view returns (uint256) {
FounderETHAmountProposal memory p = proposalVotes[proposalID];
if (p.pState == fps.Active)
return 1;
else if (p.pState == fps.Defeated)
return 4;
else if (p.pState == fps.Succeeded)
return 2;
else if(p.pState == fps.ExecutedByFounders)
return 3;
else
return 0;
}
function gPDesc(uint256 proposalID)
public
view returns (bytes32) {
FounderETHAmountProposal memory p = proposalVotes[proposalID];
return p.pDesc;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: 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: LGPL-3.0-or-later
/**
* @title obscurityDAO
* @email [email protected]
* @dev Nov 3, 2020
* ERC-20
* obscurityDAO Copyright and Disclaimer Notice:
*/
pragma solidity ^0.8.7 <0.9.0;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
abstract contract globals is AccessControlUpgradeable{
address payable ADMIN_ADDRESS;
bytes32 PAUSER_ROLE; // can pause the network
bytes32 UPGRADER_ROLE; // see admin
bytes32 ADMIN_ROLE; // COMPANY WALLET ROLE USED AS ADDITIONAL LAYER OFF PROTECTION initiats upgrades, founder wallet changes
bytes32 FOUNDER_ROLE; // USED AS ADDITIONAL LAYER OFF PROTECTION (WE CANT LOSE ACCESS TO THESE WALLETS) approves new charites
function globals_init() internal onlyInitializing{
__AccessControl_init();
ADMIN_ADDRESS = payable(address(0x00d807590d776bA30Db945C775aeED85ABFa7020));
PAUSER_ROLE = keccak256("P_R"); // can pause the network
UPGRADER_ROLE = keccak256("U_R"); // see admin
FOUNDER_ROLE = keccak256("F_R"); // USED AS ADDITIONAL LAYER OFF PROTECTION (WE CANT LOSE ACCESS TO THESE WALLETS) approves new charites
}
//UNITS
modifier contains (string memory what, string memory where) {
bytes memory whatBytes = bytes (what);
bytes memory whereBytes = bytes (where);
uint256 found = 0;
for (uint i = 0; i < whereBytes.length - whatBytes.length; i++) {
bool flag = true;
for (uint j = 0; j < whatBytes.length; j++)
if (whereBytes [i + j] != whatBytes [j]) {
flag = false;
break;
}
if (flag) {
found = 1;
break;
}
}
require (found == 1);
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
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 override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been 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());
}
}
uint256[49] private __gap;
}
// 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/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | SPDX-License-Identifier: MIT OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) Interface of the ERC20 standard as defined in the EIP./ | interface IERC20Upgradeable {
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);
function transferForCrowdSale(
address sender,
address recipient,
uint256 amount
) external;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 14,546,423 |
./full_match/7700/0x6eA48824253f64662945Ae77A790331D7183f8c0/sources/project_/contracts/digidaemons.sol | this is a public getter for ETH blance on contract | function getBalance()
external
view
returns (uint) {
return address(this).balance;
}
| 4,661,605 |
pragma solidity =0.5.16;
pragma experimental ABIEncoderV2;
/**
* ______ ____ __ ______
* / ____/____ _ ____ ___ ___ / __ \ ___ ____ _ ____/ /___ _____ / ____/____ _____
* / / __ / __ `// __ `__ \ / _ \ / /_/ // _ \ / __ `// __ // _ \ / ___/ / /_ / __ \ / ___/
* / /_/ // /_/ // / / / / // __/ / _, _// __// /_/ // /_/ // __// / / __/ / /_/ // /
* \____/ \__,_//_/ /_/ /_/ \___/ /_/ |_| \___/ \__,_/ \__,_/ \___//_/ /_/ \____//_/
* _____ _____ __ __ _ ___ __ __
* / ___/ ____ _ __ __/ ___/ ____ ____ ___ ___ / /_ / /_ (_)____ ____ _|__ \ _ __ ____ _____ / /____/ /
* \__ \ / __ `// / / /\__ \ / __ \ / __ `__ \ / _ \ / __// __ \ / // __ \ / __ `/__/ / | | /| / // __ \ / ___// // __ /
* ___/ // /_/ // /_/ /___/ // /_/ // / / / / // __// /_ / / / // // / / // /_/ // __/ _ | |/ |/ // /_/ // / / // /_/ /
* /____/ \__,_/ \__, //____/ \____//_/ /_/ /_/ \___/ \__//_/ /_//_//_/ /_/ \__, //____/(_)|__/|__/ \____//_/ /_/ \__,_/
* /____/ /____/
*/
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0)
{
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256)
{
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of GAME
*/
interface IGame {
function block2timestamp(uint256 blockNumber) external view returns (uint256);
function serial2player(uint256 serial) external view returns (address payable);
function getStatus() external view
returns (
uint256 timer,
uint256 roundCounter,
uint256 playerCounter,
uint256 messageCounter,
uint256 cookieCounter,
uint256 cookieFund,
uint256 winnerFund,
uint256 surpriseIssued,
uint256 bonusIssued,
uint256 cookieIssued,
uint256 shareholderIssued
);
function getPlayer(address account) external view
returns (
uint256 serial,
bytes memory name,
bytes memory adviserName,
address payable adviser,
uint256 messageCounter,
uint256 cookieCounter,
uint256 followerCounter,
uint256 followerMessageCounter,
uint256 followerCookieCounter,
uint256 bonusWeis,
uint256 surpriseWeis
);
function getPlayerPrime(address account) external view
returns (
bytes memory playerName,
uint256 pinnedMessageSerial,
uint8 topPlayerPosition,
uint8 shareholderPosition,
uint256 shareholderStakingWeis,
uint256 shareholderProfitWeis,
uint256 shareholderFirstBlockNumber
);
function getPlayerDisplay(address account) external view
returns (
uint256 messageCounter,
uint256 pinnedMessageSerial,
uint256 messageSerial,
bytes memory text,
uint256 blockNumber
);
function getPlayerMessage(address account, uint256 serial) external view
returns (
uint256 messageSerial,
bytes memory text,
uint256 blockNumber
);
function getPlayerCookie(address account, uint256 serial) external view
returns (
uint256 cookieSerial,
address payable player,
address payable adviser,
bytes memory playerName,
bytes memory adviserName,
uint256 playerWeis,
uint256 adviserWeis,
uint256 messageSerial,
bytes memory text,
uint256 blockNumber
);
function getPlayerFollowerCookie(address account, uint256 serial) external view
returns (
uint256 cookieSerial,
address payable player,
address payable adviser,
bytes memory playerName,
bytes memory adviserName,
uint256 playerWeis,
uint256 adviserWeis,
uint256 messageSerial,
bytes memory text,
uint256 blockNumber
);
function getPlayerFollower(address account, uint256 serial) external view
returns (address payable);
}
/**
* @dev Structs of game.
*/
library GameLib {
struct Message {
uint256 serial;
address account;
bytes name;
bytes text;
uint256 blockNumber;
}
struct Cookie {
uint256 serial;
address payable player;
address payable adviser;
bytes playerName;
bytes adviserName;
uint256 playerWeis;
uint256 adviserWeis;
uint256 messageSerial;
bytes text;
uint256 blockNumber;
}
struct Round {
uint256 openedBlock;
uint256 closingBlock;
uint256 closedTimestamp;
uint256 openingWinnerFund;
uint256 closingWinnerFund;
address payable opener;
uint256 openerBonus;
}
}
/**
* @dev Structs of player.
*/
library PlayerLib {
struct Player {
uint256 serial;
bytes name;
bytes adviserName;
address payable adviser;
uint256 messageCounter;
uint256 cookieCounter;
uint256 followerCounter;
uint256 followerMessageCounter;
uint256 followerCookieCounter;
uint256 bonusWeis;
uint256 surpriseWeis;
}
}
/**
* @title GameReaderB contract.
*/
contract ReaderB {
using SafeMath for uint256;
using PlayerLib for PlayerLib.Player;
IGame private _game;
uint8 constant SM_PAGE = 10;
uint8 constant LG_PAGE = 20;
uint8 constant SHAREHOLDER_MAX_POSITION = 6;
uint8 constant TOP_PLAYER_MAX_POSITION = 20;
uint8 constant WINNERS_PER_ROUND = 10;
/**
* @dev Constructor
*/
constructor ()
public
{
_game = IGame(0x1234567B172f040f45D7e924C0a7d088016191A6);
}
function () external payable {
revert("Cannot deposit");
}
function game()
public
view
returns (address)
{
return address(_game);
}
/**
* @dev Returns player info of `account`.
*/
function player(address account)
public
view
returns (
uint256 serial,
bytes memory name,
bytes memory adviserName,
address payable adviser,
uint256 messageCounter,
uint256 cookieCounter,
uint256 followerCounter,
uint256 followerMessageCounter,
uint256 followerCookieCounter,
uint256 bonusWeis,
uint256 surpriseWeis,
uint256 firstMessageTimestamp
)
{
PlayerLib.Player memory thePlayer = _player(account);
serial = thePlayer.serial;
name = thePlayer.name;
adviserName = thePlayer.adviserName;
adviser = thePlayer.adviser;
messageCounter = thePlayer.messageCounter;
cookieCounter = thePlayer.cookieCounter;
followerCounter = thePlayer.followerCounter;
followerMessageCounter = thePlayer.followerMessageCounter;
followerCookieCounter = thePlayer.followerCookieCounter;
bonusWeis = thePlayer.bonusWeis;
surpriseWeis = thePlayer.surpriseWeis;
(, firstMessageTimestamp) = _playerFirstMessageBT(account);
}
/**
* @dev Returns player info @ `playerSerial`.
*/
function playerAt(uint256 playerSerial)
public
view
returns (
bytes memory name,
bytes memory adviserName,
address payable account,
address payable adviser,
uint256 messageCounter,
uint256 cookieCounter,
uint256 followerCounter,
uint256 followerMessageCounter,
uint256 followerCookieCounter,
uint256 bonusWeis,
uint256 surpriseWeis,
uint256 firstMessageTimestamp
)
{
if (playerSerial > 0)
{
account =_game.serial2player(playerSerial);
PlayerLib.Player memory thePlayer = _player(account);
adviser = thePlayer.adviser;
name = thePlayer.name;
adviserName = thePlayer.adviserName;
messageCounter = thePlayer.messageCounter;
cookieCounter = thePlayer.cookieCounter;
followerCounter = thePlayer.followerCounter;
followerMessageCounter = thePlayer.followerMessageCounter;
followerCookieCounter = thePlayer.followerCookieCounter;
bonusWeis = thePlayer.bonusWeis;
surpriseWeis = thePlayer.surpriseWeis;
(, firstMessageTimestamp) = _playerFirstMessageBT(account);
}
}
/**
* Return player top-player and shareholder position, of `account`.
*/
function playerPrime(address account)
public
view
returns (
uint256 pinnedMessageSerial,
uint256 firstMessageBlockNumber,
uint256 firstMessageTimestamp,
uint8 topPlayerPosition,
uint8 shareholderPosition,
uint256 shareholderStakingWeis,
uint256 shareholderProfitWeis,
uint256 shareholderFirstBlockNumber,
uint256 shareholderFirstTimestamp
)
{
(
firstMessageBlockNumber,
firstMessageTimestamp
)
= _playerFirstMessageBT(account);
(
, // bytes memory playerName,
pinnedMessageSerial,
topPlayerPosition,
shareholderPosition,
shareholderStakingWeis,
shareholderProfitWeis,
shareholderFirstBlockNumber
)
= _game.getPlayerPrime(account);
shareholderFirstTimestamp = _game.block2timestamp(shareholderFirstBlockNumber);
}
/**
* @dev Returns messages of `account`, `till` a serial.
*
* till > 0: history
* till == 0: latest
*/
function playerMessages(address account, uint256 till)
public
view
returns (
uint256[SM_PAGE] memory serials,
uint256[SM_PAGE] memory messageSerials,
bytes[SM_PAGE] memory texts,
uint256[SM_PAGE] memory blockNumbers,
uint256[SM_PAGE] memory timestamps
)
{
PlayerLib.Player memory thePlayer = _player(account);
if (thePlayer.messageCounter > 0)
{
if (till == 0)
{
till = thePlayer.messageCounter;
}
if (till <= thePlayer.messageCounter)
{
for (uint256 i = 0; i < SM_PAGE; i++)
{
uint256 serial = till.sub(i);
if (serial < 1)
{
break;
}
GameLib.Message memory theMessage = _playerMessage(account, serial);
serials[i] = serial;
messageSerials[i] = theMessage.serial;
texts[i] = theMessage.text;
blockNumbers[i] = theMessage.blockNumber;
timestamps[i] = _game.block2timestamp(theMessage.blockNumber);
}
}
}
}
/**
* @dev Returns cookies of `account`, `till` a serial.
*
* till > 0: history
* till == 0: latest
*/
function playerCookies(address account, uint256 till)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory advisers,
bytes[SM_PAGE] memory adviserNames,
uint256[SM_PAGE] memory playerWeis,
uint256[SM_PAGE] memory adviserWeis,
uint256[SM_PAGE] memory messageSerials,
bytes[SM_PAGE] memory texts,
uint256[SM_PAGE] memory blockNumbers,
uint256[SM_PAGE] memory timestamps
)
{
PlayerLib.Player memory thePlayer = _player(account);
if (thePlayer.cookieCounter > 0)
{
if (till == 0)
{
till = thePlayer.cookieCounter;
}
if (till <= thePlayer.cookieCounter)
{
for (uint256 i = 0; i < SM_PAGE; i++)
{
uint256 serial = till.sub(i);
if (serial < 1)
{
break;
}
GameLib.Cookie memory cookie = _playerCookie(account, serial);
serials[i] = cookie.serial;
advisers[i] = cookie.adviser;
adviserNames[i] = cookie.adviserName;
playerWeis[i] = cookie.playerWeis;
adviserWeis[i] = cookie.adviserWeis;
messageSerials[i] = cookie.messageSerial;
texts[i] = cookie.text;
blockNumbers[i] = cookie.blockNumber;
timestamps[i] = _game.block2timestamp(cookie.blockNumber);
}
}
}
}
/**
* @dev Returns follower-cookies of `account`, `till` a serial.
*
* till > 0: history
* till == 0: latest
*/
function playerFollowerCookies(address account, uint256 till)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory players,
bytes[SM_PAGE] memory playerNames,
uint256[SM_PAGE] memory playerWeis,
uint256[SM_PAGE] memory adviserWeis,
uint256[SM_PAGE] memory messageSerials,
bytes[SM_PAGE] memory texts,
uint256[SM_PAGE] memory blockNumbers,
uint256[SM_PAGE] memory timestamps
)
{
PlayerLib.Player memory thePlayer = _player(account);
if (thePlayer.followerCookieCounter > 0)
{
if (till == 0)
{
till = thePlayer.followerCookieCounter;
}
if (till <= thePlayer.followerCookieCounter)
{
for (uint256 i = 0; i < SM_PAGE; i++)
{
uint256 serial = till.sub(i);
if (serial < 1)
{
break;
}
GameLib.Cookie memory cookie = _playerFollowerCookie(account, serial);
serials[i] = cookie.serial;
players[i] = cookie.player;
// advisers[i] = cookie.adviser;
playerNames[i] = cookie.playerName;
// adviserNames[i] = cookie.adviserName;
playerWeis[i] = cookie.playerWeis;
adviserWeis[i] = cookie.adviserWeis;
messageSerials[i] = cookie.messageSerial;
texts[i] = cookie.text;
blockNumbers[i] = cookie.blockNumber;
timestamps[i] = _game.block2timestamp(cookie.blockNumber);
}
}
}
}
/**
* @dev Returns followers of `account`, `till` a serial.
*
* till > 0: history
* till == 0: latest
*/
function playerFollowersA(address account, uint256 till)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory playerSerials,
bytes[SM_PAGE] memory names,
bytes[SM_PAGE] memory adviserNames,
address[SM_PAGE] memory advisers,
uint256[SM_PAGE] memory bonusWeis,
uint256[SM_PAGE] memory surpriseWeis,
uint256[SM_PAGE] memory messageSerials,
uint256[SM_PAGE] memory messageBlockNumbers,
uint256[SM_PAGE] memory messageTimestamps,
bytes[SM_PAGE] memory messageTexts
)
{
(serials, accounts) = _playerFollowerAccounts(account, till);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
PlayerLib.Player memory thePlayer = _player(accounts[i]);
playerSerials[i] = thePlayer.serial;
names[i] = thePlayer.name;
adviserNames[i] = thePlayer.adviserName;
advisers[i] = thePlayer.adviser;
bonusWeis[i] = thePlayer.bonusWeis;
surpriseWeis[i] = thePlayer.surpriseWeis;
(
, // uint256 messageCounter,
, // uint256 pinnedMessageSerial,
messageSerials[i],
messageTexts[i],
messageBlockNumbers[i]
)
= _game.getPlayerDisplay(accounts[i]);
messageTimestamps[i] = _game.block2timestamp(messageBlockNumbers[i]);
}
}
}
function playerFollowersB(address account, uint256 till)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory messageCounters,
uint256[SM_PAGE] memory cookieCounters,
uint256[SM_PAGE] memory followerCounters,
uint256[SM_PAGE] memory followerMessageCounters,
uint256[SM_PAGE] memory followerCookieCounters,
uint256[SM_PAGE] memory firstMessageBlockNumbers,
uint256[SM_PAGE] memory firstMessageTimestamps
)
{
(serials, accounts) = _playerFollowerAccounts(account, till);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
PlayerLib.Player memory thePlayer = _player(accounts[i]);
messageCounters[i] = thePlayer.messageCounter;
cookieCounters[i] = thePlayer.cookieCounter;
followerCounters[i] = thePlayer.followerCounter;
followerMessageCounters[i] = thePlayer.followerMessageCounter;
followerCookieCounters[i] = thePlayer.followerCookieCounter;
(
firstMessageBlockNumbers[i],
firstMessageTimestamps[i]
)
= _playerFirstMessageBT(accounts[i]);
}
}
}
function playerFollowersC(address account, uint256 till)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory pinnedMessageSerials,
uint8[SM_PAGE] memory topPlayerPositions,
uint8[SM_PAGE] memory shareholderPositions,
uint256[SM_PAGE] memory shareholderStakingWeis,
uint256[SM_PAGE] memory shareholderProfitWeis,
uint256[SM_PAGE] memory shareholderFirstBlockNumbers,
uint256[SM_PAGE] memory shareholderFirstTimestamps
)
{
(serials, accounts) = _playerFollowerAccounts(account, till);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
(
pinnedMessageSerials[i],
, // uint256 firstMessageBlockNumber,
, // uint256 firstMessageTimestamp,
topPlayerPositions[i],
shareholderPositions[i],
shareholderStakingWeis[i],
shareholderProfitWeis[i],
shareholderFirstBlockNumbers[i],
shareholderFirstTimestamps[i]
)
= playerPrime(accounts[i]);
}
}
}
/**
* @dev Returns advisers of `account`.
*/
function playerAdvisersA(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory playerSerials,
bytes[SM_PAGE] memory names,
bytes[SM_PAGE] memory adviserNames,
address[SM_PAGE] memory advisers,
uint256[SM_PAGE] memory bonusWeis,
uint256[SM_PAGE] memory surpriseWeis,
uint256[SM_PAGE] memory messageSerials,
uint256[SM_PAGE] memory messageBlockNumbers,
uint256[SM_PAGE] memory messageTimestamps,
bytes[SM_PAGE] memory messageTexts
)
{
(serials, accounts) = _playerAdviserAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
PlayerLib.Player memory thePlayer = _player(accounts[i]);
playerSerials[i] = thePlayer.serial;
names[i] = thePlayer.name;
adviserNames[i] = thePlayer.adviserName;
advisers[i] = thePlayer.adviser;
bonusWeis[i] = thePlayer.bonusWeis;
surpriseWeis[i] = thePlayer.surpriseWeis;
(
, // uint256 messageCounter,
, // uint256 pinnedMessageSerial,
messageSerials[i],
messageTexts[i],
messageBlockNumbers[i]
)
= _game.getPlayerDisplay(accounts[i]);
messageTimestamps[i] = _game.block2timestamp(messageBlockNumbers[i]);
}
}
}
function playerAdvisersB(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory messageCounters,
uint256[SM_PAGE] memory cookieCounters,
uint256[SM_PAGE] memory followerCounters,
uint256[SM_PAGE] memory followerMessageCounters,
uint256[SM_PAGE] memory followerCookieCounters,
uint256[SM_PAGE] memory firstMessageBlockNumbers,
uint256[SM_PAGE] memory firstMessageTimestamps
)
{
(serials, accounts) = _playerAdviserAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
PlayerLib.Player memory thePlayer = _player(accounts[i]);
messageCounters[i] = thePlayer.messageCounter;
cookieCounters[i] = thePlayer.cookieCounter;
followerCounters[i] = thePlayer.followerCounter;
followerMessageCounters[i] = thePlayer.followerMessageCounter;
followerCookieCounters[i] = thePlayer.followerCookieCounter;
(
firstMessageBlockNumbers[i],
firstMessageTimestamps[i]
)
= _playerFirstMessageBT(accounts[i]);
}
}
}
function playerAdvisersC(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory pinnedMessageSerials,
uint8[SM_PAGE] memory topPlayerPositions,
uint8[SM_PAGE] memory shareholderPositions,
uint256[SM_PAGE] memory shareholderStakingWeis,
uint256[SM_PAGE] memory shareholderProfitWeis,
uint256[SM_PAGE] memory shareholderFirstBlockNumbers,
uint256[SM_PAGE] memory shareholderFirstTimestamps
)
{
(serials, accounts) = _playerAdviserAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
(
pinnedMessageSerials[i],
, // uint256 firstMessageBlockNumber,
, // uint256 firstMessageTimestamp,
topPlayerPositions[i],
shareholderPositions[i],
shareholderStakingWeis[i],
shareholderProfitWeis[i],
shareholderFirstBlockNumbers[i],
shareholderFirstTimestamps[i]
)
= playerPrime(accounts[i]);
}
}
}
/**
* @dev Returns previous of `account`.
*/
function playerPreviousA(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory playerSerials,
bytes[SM_PAGE] memory names,
bytes[SM_PAGE] memory adviserNames,
address[SM_PAGE] memory advisers,
uint256[SM_PAGE] memory bonusWeis,
uint256[SM_PAGE] memory surpriseWeis,
uint256[SM_PAGE] memory messageSerials,
uint256[SM_PAGE] memory messageBlockNumbers,
uint256[SM_PAGE] memory messageTimestamps,
bytes[SM_PAGE] memory messageTexts
)
{
(serials, accounts) = _playerPreviousAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
PlayerLib.Player memory thePlayer = _player(accounts[i]);
playerSerials[i] = thePlayer.serial;
names[i] = thePlayer.name;
adviserNames[i] = thePlayer.adviserName;
advisers[i] = thePlayer.adviser;
bonusWeis[i] = thePlayer.bonusWeis;
surpriseWeis[i] = thePlayer.surpriseWeis;
(
, // uint256 messageCounter,
, // uint256 pinnedMessageSerial,
messageSerials[i],
messageTexts[i],
messageBlockNumbers[i]
)
= _game.getPlayerDisplay(accounts[i]);
messageTimestamps[i] = _game.block2timestamp(messageBlockNumbers[i]);
}
}
}
function playerPreviousB(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory messageCounters,
uint256[SM_PAGE] memory cookieCounters,
uint256[SM_PAGE] memory followerCounters,
uint256[SM_PAGE] memory followerMessageCounters,
uint256[SM_PAGE] memory followerCookieCounters,
uint256[SM_PAGE] memory firstMessageBlockNumbers,
uint256[SM_PAGE] memory firstMessageTimestamps
)
{
(serials, accounts) = _playerPreviousAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
PlayerLib.Player memory thePlayer = _player(accounts[i]);
messageCounters[i] = thePlayer.messageCounter;
cookieCounters[i] = thePlayer.cookieCounter;
followerCounters[i] = thePlayer.followerCounter;
followerMessageCounters[i] = thePlayer.followerMessageCounter;
followerCookieCounters[i] = thePlayer.followerCookieCounter;
(
firstMessageBlockNumbers[i],
firstMessageTimestamps[i]
)
= _playerFirstMessageBT(accounts[i]);
}
}
}
function playerPreviousC(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory pinnedMessageSerials,
uint8[SM_PAGE] memory topPlayerPositions,
uint8[SM_PAGE] memory shareholderPositions,
uint256[SM_PAGE] memory shareholderStakingWeis,
uint256[SM_PAGE] memory shareholderProfitWeis,
uint256[SM_PAGE] memory shareholderFirstBlockNumbers,
uint256[SM_PAGE] memory shareholderFirstTimestamps
)
{
(serials, accounts) = _playerPreviousAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
(
pinnedMessageSerials[i],
, // uint256 firstMessageBlockNumber,
, // uint256 firstMessageTimestamp,
topPlayerPositions[i],
shareholderPositions[i],
shareholderStakingWeis[i],
shareholderProfitWeis[i],
shareholderFirstBlockNumbers[i],
shareholderFirstTimestamps[i]
)
= playerPrime(accounts[i]);
}
}
}
/**
* @dev Returns next of `account`.
*/
function playerNextA(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory playerSerials,
bytes[SM_PAGE] memory names,
bytes[SM_PAGE] memory adviserNames,
address[SM_PAGE] memory advisers,
uint256[SM_PAGE] memory bonusWeis,
uint256[SM_PAGE] memory surpriseWeis,
uint256[SM_PAGE] memory messageSerials,
uint256[SM_PAGE] memory messageBlockNumbers,
uint256[SM_PAGE] memory messageTimestamps,
bytes[SM_PAGE] memory messageTexts
)
{
(serials, accounts) = _playerNextAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
PlayerLib.Player memory thePlayer = _player(accounts[i]);
playerSerials[i] = thePlayer.serial;
names[i] = thePlayer.name;
adviserNames[i] = thePlayer.adviserName;
advisers[i] = thePlayer.adviser;
bonusWeis[i] = thePlayer.bonusWeis;
surpriseWeis[i] = thePlayer.surpriseWeis;
(
, // uint256 messageCounter,
, // uint256 pinnedMessageSerial,
messageSerials[i],
messageTexts[i],
messageBlockNumbers[i]
)
= _game.getPlayerDisplay(accounts[i]);
messageTimestamps[i] = _game.block2timestamp(messageBlockNumbers[i]);
}
}
}
function playerNextB(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory messageCounters,
uint256[SM_PAGE] memory cookieCounters,
uint256[SM_PAGE] memory followerCounters,
uint256[SM_PAGE] memory followerMessageCounters,
uint256[SM_PAGE] memory followerCookieCounters,
uint256[SM_PAGE] memory firstMessageBlockNumbers,
uint256[SM_PAGE] memory firstMessageTimestamps
)
{
(serials, accounts) = _playerNextAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
PlayerLib.Player memory thePlayer = _player(accounts[i]);
messageCounters[i] = thePlayer.messageCounter;
cookieCounters[i] = thePlayer.cookieCounter;
followerCounters[i] = thePlayer.followerCounter;
followerMessageCounters[i] = thePlayer.followerMessageCounter;
followerCookieCounters[i] = thePlayer.followerCookieCounter;
(
firstMessageBlockNumbers[i],
firstMessageTimestamps[i]
)
= _playerFirstMessageBT(accounts[i]);
}
}
}
function playerNextC(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory pinnedMessageSerials,
uint8[SM_PAGE] memory topPlayerPositions,
uint8[SM_PAGE] memory shareholderPositions,
uint256[SM_PAGE] memory shareholderStakingWeis,
uint256[SM_PAGE] memory shareholderProfitWeis,
uint256[SM_PAGE] memory shareholderFirstBlockNumbers,
uint256[SM_PAGE] memory shareholderFirstTimestamps
)
{
(serials, accounts) = _playerNextAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
(
pinnedMessageSerials[i],
, // uint256 firstMessageBlockNumber,
, // uint256 firstMessageTimestamp,
topPlayerPositions[i],
shareholderPositions[i],
shareholderStakingWeis[i],
shareholderProfitWeis[i],
shareholderFirstBlockNumbers[i],
shareholderFirstTimestamps[i]
)
= playerPrime(accounts[i]);
}
}
}
/**
* --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- ---------
* ____ _ __ ______ __ _
* / __ \ _____ (_)_ __ ____ _ / /_ ___ / ____/__ __ ____ _____ / /_ (_)____ ____ _____
* / /_/ // ___// /| | / // __ `// __// _ \ / /_ / / / // __ \ / ___// __// // __ \ / __ \ / ___/
* / ____// / / / | |/ // /_/ // /_ / __/ / __/ / /_/ // / / // /__ / /_ / // /_/ // / / /(__ )
* /_/ /_/ /_/ |___/ \__,_/ \__/ \___/ /_/ \__,_//_/ /_/ \___/ \__//_/ \____//_/ /_//____/
*
* --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- ---------
*/
/**
* @dev Returns first message `blockNumber` and `timestamp` of `account`.
*/
function _playerFirstMessageBT(address account)
private
view
returns (
uint256 blockNumber,
uint256 timestamp
)
{
PlayerLib.Player memory thePlayer = _player(account);
if (thePlayer.messageCounter > 0)
{
GameLib.Message memory theMessage = _playerMessage(account, 1);
blockNumber = theMessage.blockNumber;
timestamp = _game.block2timestamp(blockNumber);
}
}
/**
* @dev Returns follower accounts, of player `account`, `till` a serial.
*/
function _playerFollowerAccounts(address account, uint256 till)
private
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts
)
{
PlayerLib.Player memory thePlayer = _player(account);
if (thePlayer.followerCounter > 0)
{
if (till == 0)
{
till = thePlayer.followerCounter;
}
if (till <= thePlayer.followerCounter)
{
for (uint256 i = 0; i < SM_PAGE; i++)
{
uint256 serial = till.sub(i);
if (serial < 1)
{
break;
}
address payable follower = _game.getPlayerFollower(account, serial);
serials[i] = serial;
accounts[i] = follower;
}
}
}
}
/**
* @dev Returns follower accounts, of player `account`.
*/
function _playerAdviserAccounts(address account)
private
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts
)
{
if (account != address(0))
{
for (uint8 i = 0; i < SM_PAGE; i++)
{
address adviser = _player(account).adviser;
if (adviser == account || adviser == address(0))
{
break;
}
serials[i] = i + 1;
accounts[i] = adviser;
account = adviser;
}
}
}
/**
* @dev Returns previous accounts, of player `account`.
*/
function _playerPreviousAccounts(address account)
private
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts
)
{
uint256 previousPlayerSerial;
uint8 i = 0;
if (account == address(0))
{
(
, // uint256 timer,
, // uint256 roundCounter,
previousPlayerSerial,
, // uint256 messageCounter,
, // uint256 cookieCounter,
, // uint256 cookieFund,
, // uint256 winnerFund,
, // uint256 surpriseIssued,
, // uint256 bonusIssued,
, // uint256 cookieIssued,
// uint256 shareholderIssued
)
= _game.getStatus();
serials[i] = 1;
accounts[i] = _game.serial2player(previousPlayerSerial);
i++;
} else {
previousPlayerSerial = _player(account).serial.sub(1);
}
uint256 playerSerial;
for (i; i < SM_PAGE; i++)
{
playerSerial = previousPlayerSerial.sub(i);
if (playerSerial < 1)
{
break;
}
serials[i] = i + 1;
accounts[i] = _game.serial2player(playerSerial);
}
}
/**
* @dev Returns next accounts, of player `account`.
*/
function _playerNextAccounts(address account)
private
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts
)
{
(
, // uint256 timer,
, // uint256 roundCounter,
uint256 playerCounter,
, // uint256 messageCounter,
, // uint256 cookieCounter,
, // uint256 cookieFund,
, // uint256 winnerFund,
, // uint256 surpriseIssued,
, // uint256 bonusIssued,
, // uint256 cookieIssued,
// uint256 shareholderIssued
)
= _game.getStatus();
uint256 nextPlayerSerial = _player(account).serial.add(1);
uint256 playerSerial;
for (uint8 i = 0; i < SM_PAGE; i++)
{
playerSerial = nextPlayerSerial.add(i);
if (playerSerial > playerCounter)
{
break;
}
serials[i] = i + 1;
accounts[i] = _game.serial2player(playerSerial);
}
}
/**
* @dev Returns player {PlayerLib.Player} of `account`.
*/
function _player(address account)
private
view
returns (PlayerLib.Player memory)
{
(
uint256 serial,
bytes memory name,
bytes memory adviserName,
address payable adviser,
uint256 messageCounter,
uint256 cookieCounter,
uint256 followerCounter,
uint256 followerMessageCounter,
uint256 followerCookieCounter,
uint256 bonusWeis,
uint256 surpriseWeis
)
= _game.getPlayer(account);
return PlayerLib.Player(
serial,
name,
adviserName,
adviser,
messageCounter,
cookieCounter,
followerCounter,
followerMessageCounter,
followerCookieCounter,
bonusWeis,
surpriseWeis
);
}
/**
* @dev Returns message of `account` {GameLib.Message} @ `serial`.
*/
function _playerMessage(address account, uint256 serial)
private
view
returns (GameLib.Message memory)
{
(
uint256 messageSerial,
bytes memory text,
uint256 blockNumber
)
= _game.getPlayerMessage(account, serial);
PlayerLib.Player memory thePlayer = _player(account);
return GameLib.Message(messageSerial, account, thePlayer.name, text, blockNumber);
}
/**
* @dev Returns cookie of `account` {GameLib.Cookie} @ `serial`.
*/
function _playerCookie(address account, uint256 serial)
private
view
returns (GameLib.Cookie memory)
{
(
uint256 cookieSerial,
address payable playerAccount,
address payable adviserAccount,
bytes memory playerName,
bytes memory adviserName,
uint256 playerWeis,
uint256 adviserWeis,
uint256 messageSerial,
bytes memory text,
uint256 blockNumber
)
= _game.getPlayerCookie(account, serial);
return GameLib.Cookie(cookieSerial, playerAccount, adviserAccount, playerName, adviserName, playerWeis, adviserWeis, messageSerial, text, blockNumber);
}
/**
* @dev Returns follower-cookie of `account` {GameLib.Cookie} @ `serial`.
*/
function _playerFollowerCookie(address account, uint256 serial)
private
view
returns (GameLib.Cookie memory)
{
(
uint256 cookieSerial,
address payable playerAccount,
address payable adviserAccount,
bytes memory playerName,
bytes memory adviserName,
uint256 playerWeis,
uint256 adviserWeis,
uint256 messageSerial,
bytes memory text,
uint256 blockNumber
)
= _game.getPlayerFollowerCookie(account, serial);
return GameLib.Cookie(cookieSerial, playerAccount, adviserAccount, playerName, adviserName, playerWeis, adviserWeis, messageSerial, text, blockNumber);
}
}
| Returns next of `account`./ | function playerNextA(address account)
public
view
returns (
uint256[SM_PAGE] memory serials,
address[SM_PAGE] memory accounts,
uint256[SM_PAGE] memory playerSerials,
bytes[SM_PAGE] memory names,
bytes[SM_PAGE] memory adviserNames,
address[SM_PAGE] memory advisers,
uint256[SM_PAGE] memory bonusWeis,
uint256[SM_PAGE] memory surpriseWeis,
uint256[SM_PAGE] memory messageSerials,
uint256[SM_PAGE] memory messageBlockNumbers,
uint256[SM_PAGE] memory messageTimestamps,
bytes[SM_PAGE] memory messageTexts
)
{
(serials, accounts) = _playerNextAccounts(account);
for (uint256 i = 0; i < accounts.length; i++)
{
if (accounts[i] != address(0))
{
PlayerLib.Player memory thePlayer = _player(accounts[i]);
playerSerials[i] = thePlayer.serial;
names[i] = thePlayer.name;
adviserNames[i] = thePlayer.adviserName;
advisers[i] = thePlayer.adviser;
bonusWeis[i] = thePlayer.bonusWeis;
surpriseWeis[i] = thePlayer.surpriseWeis;
(
messageSerials[i],
messageTexts[i],
messageBlockNumbers[i]
)
= _game.getPlayerDisplay(accounts[i]);
messageTimestamps[i] = _game.block2timestamp(messageBlockNumbers[i]);
}
}
}
| 12,693,134 |
pragma solidity 0.4.25;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/ERC20.sol
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/ERC20Basic.sol
//
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function allowance(address approver, address spender) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed approver, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*
* Source: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
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 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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* A version of the Trustee contract (https://www.investopedia.com/terms/r/regulationd.asp) with the
* added role of Transfer Agent to perform specialised actions.
*
* Part of the kycware.com ICO by Horizon-Globex.com of Switzerland.
*
* Author: Horizon Globex GmbH Development Team
*/
contract Trustee {
using SafeMath for uint256;
/**
* The details of the tokens bought.
*/
struct Holding {
// The number of tokens purchased.
uint256 quantity;
// The date and time when the tokens are no longer restricted.
uint256 releaseDate;
// Whether the holder is an affiliate of the company or not.
bool isAffiliate;
}
// Restrict functionality to the creator of the contract - the token issuer.
modifier onlyIssuer {
require(msg.sender == issuer, "You must be issuer/owner to execute this function.");
_;
}
// Restrict functionaly to the official Transfer Agent.
modifier onlyTransferAgent {
require(msg.sender == transferAgent, "You must be the Transfer Agent to execute this function.");
_;
}
// The creator/owner of this contract, set at contract creation to the address that created the contract.
address public issuer;
// The collection of all held tokens by user.
mapping(address => Holding) public heldTokens;
// The ERC20 Token contract, needed to transfer tokens back to their original owner when the holding
// period ends.
address public tokenContract;
// The authorised Transfer Agent who performs specialist actions on this contract.
address public transferAgent;
// Number of seconds in one standard year.
uint256 public oneYear = 0;//31536000;
// Emitted when someone subject to Regulation D buys tokens and they are held here.
event TokensHeld(address indexed who, uint256 tokens, uint256 releaseDate);
// Emitted when the tokens have passed their release date and have been returned to the original owner.
event TokensReleased(address indexed who, uint256 tokens);
// The Transfer Agent moved tokens from an address to a new wallet, for escheatment obligations.
event TokensTransferred(address indexed from, address indexed to, uint256 tokens);
// The Transfer Agent was unable to verify a token holder and needed to push out the release date.
event ReleaseDateExtended(address who, uint256 newReleaseDate);
// Extra restrictions apply to company affiliates, notify when the status of an address changes.
event AffiliateStatusChanged(address who, bool isAffiliate);
/**
* @notice Create this contract and assign the ERC20 contract where the tokens are returned once the
* holding period has complete.
*
* @param erc20Contract The address of the ERC20 contract.
*/
constructor(address erc20Contract) public {
issuer = msg.sender;
tokenContract = erc20Contract;
}
/**
* @notice Set the address of the Transfer Agent.
*/
function setTransferAgent(address who) public onlyIssuer {
transferAgent = who;
}
/**
* @notice Keep a US Citizen's tokens for one year.
*
* @param who The wallet of the US Citizen.
* @param quantity The number of tokens to store.
*/
function hold(address who, uint256 quantity) public onlyIssuer {
require(who != 0x0, "The null address cannot own tokens.");
require(quantity != 0, "Quantity must be greater than zero.");
require(!isExistingHolding(who), "Cannot overwrite an existing holding, use a new wallet.");
Holding memory holding = Holding(quantity, block.timestamp+oneYear, false);
heldTokens[who] = holding;
emit TokensHeld(who, holding.quantity, holding.releaseDate);
}
/**
* @notice Hold tokens post-ICO with a variable release date on those tokens.
*
* @param who The wallet of the US Citizen.
* @param quantity The number of tokens to store.
* @param addedTime The number of seconds to add to the current date to calculate the release date.
*/
function postIcoHold(address who, uint256 quantity, uint256 addedTime) public onlyTransferAgent {
require(who != 0x0, "The null address cannot own tokens.");
require(quantity != 0, "Quantity must be greater than zero.");
require(!isExistingHolding(who), "Cannot overwrite an existing holding, use a new wallet.");
Holding memory holding = Holding(quantity, block.timestamp+addedTime, false);
heldTokens[who] = holding;
emit TokensHeld(who, holding.quantity, holding.releaseDate);
}
/**
* @notice Check if a user's holding are eligible for release.
*
* @param who The user to check the holding of.
* @return True if can be released, false if not.
*/
function canRelease(address who) public view returns (bool) {
Holding memory holding = heldTokens[who];
if(holding.releaseDate == 0 || holding.quantity == 0)
return false;
return block.timestamp > holding.releaseDate;
}
/**
* @notice Release the tokens once the holding period expires, transferring them back to the ERC20 contract to the holder.
*
* NOTE: This function preserves the isAffiliate flag of the holder.
*
* @param who The owner of the tokens.
* @return True on successful release, false on error.
*/
function release(address who) public onlyTransferAgent returns (bool) {
Holding memory holding = heldTokens[who];
require(!holding.isAffiliate, "To release tokens for an affiliate use partialRelease().");
if(block.timestamp > holding.releaseDate) {
bool res = ERC20Interface(tokenContract).transfer(who, holding.quantity);
if(res) {
heldTokens[who] = Holding(0, 0, holding.isAffiliate);
emit TokensReleased(who, holding.quantity);
return true;
}
}
return false;
}
/**
* @notice Release some of an affiliate's tokens to a broker/trading wallet.
*
* @param who The owner of the tokens.
* @param tradingWallet The broker/trader receiving the tokens.
* @param amount The number of tokens to release to the trading wallet.
*/
function partialRelease(address who, address tradingWallet, uint256 amount) public onlyTransferAgent returns (bool) {
require(tradingWallet != 0, "The destination wallet cannot be null.");
require(!isExistingHolding(tradingWallet), "The destination wallet must be a new fresh wallet.");
Holding memory holding = heldTokens[who];
require(holding.isAffiliate, "Only affiliates can use this function; use release() for non-affiliates.");
require(amount <= holding.quantity, "The holding has less than the specified amount of tokens.");
if(block.timestamp > holding.releaseDate) {
// Send the tokens currently held by this contract on behalf of 'who' to the nominated wallet.
bool res = ERC20Interface(tokenContract).transfer(tradingWallet, amount);
if(res) {
heldTokens[who] = Holding(holding.quantity.sub(amount), holding.releaseDate, holding.isAffiliate);
emit TokensReleased(who, amount);
return true;
}
}
return false;
}
/**
* @notice Under special circumstances the Transfer Agent needs to move tokens around.
*
* @dev As the release date is accurate to one second it is very unlikely release dates will
* match so an address that does not have a holding in this contract is required as the target.
*
* @param from The current holder of the tokens.
* @param to The recipient of the tokens - must be a 'clean' address.
* @param amount The number of tokens to move.
*/
function transfer(address from, address to, uint256 amount) public onlyTransferAgent returns (bool) {
require(to != 0x0, "Cannot transfer tokens to the null address.");
require(amount > 0, "Cannot transfer zero tokens.");
Holding memory fromHolding = heldTokens[from];
require(fromHolding.quantity >= amount, "Not enough tokens to perform the transfer.");
require(!isExistingHolding(to), "Cannot overwrite an existing holding, use a new wallet.");
heldTokens[from] = Holding(fromHolding.quantity.sub(amount), fromHolding.releaseDate, fromHolding.isAffiliate);
heldTokens[to] = Holding(amount, fromHolding.releaseDate, false);
emit TokensTransferred(from, to, amount);
return true;
}
/**
* @notice The Transfer Agent may need to add time to the release date if they are unable to verify
* the holder in a timely manner.
*
* @param who The holder of the tokens.
* @param sconds The number of seconds to add to the release date. NOTE: 'seconds' appears to
* be a reserved word.
*/
function addTime(address who, uint sconds) public onlyTransferAgent returns (bool) {
require(sconds > 0, "Time added cannot be zero.");
Holding memory holding = heldTokens[who];
heldTokens[who] = Holding(holding.quantity, holding.releaseDate.add(sconds), holding.isAffiliate);
emit ReleaseDateExtended(who, heldTokens[who].releaseDate);
return true;
}
/**
* @notice Company affiliates have added restriction, allow the Transfer Agent set/clear this flag
* as needed.
*
* @param who The address being affiliated/unaffiliated.
* @param isAffiliate Whether the address is an affiliate or not.
*/
function setAffiliate(address who, bool isAffiliate) public onlyTransferAgent returns (bool) {
require(who != 0, "The null address cannot be used.");
Holding memory holding = heldTokens[who];
require(holding.isAffiliate != isAffiliate, "Attempt to set the same affiliate status that is already set.");
heldTokens[who] = Holding(holding.quantity, holding.releaseDate, isAffiliate);
emit AffiliateStatusChanged(who, isAffiliate);
return true;
}
/**
* @notice Check if a wallet is already in use, only new/fresh/clean wallets can hold tokens.
*
* @param who The wallet to check.
* @return True if the wallet is in use, false otherwise.
*/
function isExistingHolding(address who) public view returns (bool) {
Holding memory h = heldTokens[who];
return (h.quantity != 0 || h.releaseDate != 0);
}
} | Release the tokens once the holding period expires, transferring them back to the ERC20 contract to the holder. NOTE: This function preserves the isAffiliate flag of the holder. who The owner of the tokens. return True on successful release, false on error./ | function release(address who) public onlyTransferAgent returns (bool) {
Holding memory holding = heldTokens[who];
require(!holding.isAffiliate, "To release tokens for an affiliate use partialRelease().");
if(block.timestamp > holding.releaseDate) {
bool res = ERC20Interface(tokenContract).transfer(who, holding.quantity);
if(res) {
heldTokens[who] = Holding(0, 0, holding.isAffiliate);
emit TokensReleased(who, holding.quantity);
return true;
}
}
return false;
}
| 2,545,288 |
./full_match/1/0xFE0D22E6516643e2cB3C9Cc3b8D6A1fAb9B8aAF3/sources/contracts/blindBackrun.sol | Executes an arbitrage transaction between Uniswap V3-V2 pairs. Approve the firstPair to spend the contract's WETH. swap WETH for token1 swap WETH for token0 | function executeArbitrage(
bool isWETHZero,
address secondPairAddress,
uint amountIn,
uint finalAmountOut,
address token0,
address token1,
uint24 actualUniV3Fee,
uint percentageToPayToCoinbase
) external onlyOwner {
uint256 balanceBefore = IERC20(WETH_ADDRESS).balanceOf(address(this));
address tokenOut;
IERC20(WETH_ADDRESS).approve(address(swapRouter), amountIn);
if (isWETHZero == true) {
tokenOut = token1;
tokenOut = token0;
}
);
swapRouter.exactInputSingle(params);
IUniswapV2Pair secondPair = IUniswapV2Pair(secondPairAddress);
if (tokenOut == secondPair.token0()) {
secondPair.swap(
);
secondPair.swap(
);
}
uint256 balanceAfter = IERC20(WETH_ADDRESS).balanceOf(address(this));
require(balanceAfter > balanceBefore, "Arbitrage failed");
uint profit = balanceAfter.sub(balanceBefore);
uint profitToCoinbase = profit.mul(percentageToPayToCoinbase).div(100);
IWETH(WETH_ADDRESS).withdraw(profitToCoinbase);
block.coinbase.transfer(profitToCoinbase);
}
| 3,154,593 |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, 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.
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
// File: contracts/utils/InitializableERC20Detailed.sol
pragma solidity 0.5.11;
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
contract InitializableERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/utils/InitializableToken.sol
pragma solidity 0.5.11;
contract InitializableToken is ERC20, InitializableERC20Detailed {
/**
* @dev Initialization function for implementing contract
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(string memory _nameArg, string memory _symbolArg)
internal
{
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
}
}
// File: contracts/utils/StableMath.sol
pragma solidity 0.5.11;
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17
*/
function scaleBy(uint256 x, int8 adjustment)
internal
pure
returns (uint256)
{
if (adjustment > 0) {
x = x.mul(10**uint256(adjustment));
} else if (adjustment < 0) {
x = x.div(10**uint256(adjustment * -1));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// File: contracts/governance/Governable.sol
pragma solidity 0.5.11;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
//keccak256("OUSD.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
//keccak256("OUSD.pending.governor");
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: contracts/token/OUSD.sol
pragma solidity 0.5.11;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
contract OUSD is Initializable, InitializableToken, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 public rebasingCredits;
// Exchange rate between internal credits and OUSD
uint256 public rebasingCreditsPerToken;
mapping(address => uint256) private _creditBalances;
// Allowances denominated in OUSD
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingCredits;
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => bool) public rebaseOptInList;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableToken._initialize(_nameArg, _symbolArg);
_totalSupply = 0;
rebasingCredits = 0;
rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
nonRebasingCredits = 0;
nonRebasingSupply = 0;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the _amount of base units owned by the
* specified address.
*/
function balanceOf(address _account) public view returns (uint256) {
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
return (_creditBalances[_account], _creditsPerToken(_account));
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the _amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The _amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
bool isNonRebasingTo = _isNonRebasingAddress(_to);
bool isNonRebasingFrom = _isNonRebasingAddress(_from);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingCredits = nonRebasingCredits.add(creditsCredited);
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingCredits = nonRebasingCredits.sub(creditsDeducted);
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
rebasingCredits = rebasingCredits.add(creditsCredited);
} else if (isNonRebasingTo && isNonRebasingFrom) {
// Transfer between two non rebasing accounts. They may have
// different exchange rates so update the count of non rebasing
// credits with the difference
nonRebasingCredits =
nonRebasingCredits +
creditsCredited -
creditsDeducted;
}
// Make sure the fixed credits per token get set for to/from accounts if
// they have not been
if (isNonRebasingTo && nonRebasingCreditsPerToken[_to] == 0) {
nonRebasingCreditsPerToken[_to] = rebasingCreditsPerToken;
}
if (isNonRebasingFrom && nonRebasingCreditsPerToken[_from] == 0) {
nonRebasingCreditsPerToken[_from] = rebasingCreditsPerToken;
}
}
/**
* @dev Function to check the _amount of tokens that an owner has allowed to a _spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified _amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param _spender The address which will spend the funds.
* @param _value The _amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the _amount of tokens that an owner has allowed to a _spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param _spender The address which will spend the funds.
* @param _addedValue The _amount of tokens to increase the allowance by.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
public
returns (bool)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the _amount of tokens that an owner has allowed to a _spender.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The _amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
return _mint(_account, _amount);
}
/**
* @dev Creates `_amount` tokens and assigns them to `_account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address _account, uint256 _amount) internal {
require(_account != address(0), "Mint to the zero address");
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
bool isNonRebasingAccount = _isNonRebasingAddress(_account);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
if (nonRebasingCreditsPerToken[_account] == 0) {
nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken;
}
nonRebasingCredits = nonRebasingCredits.add(creditAmount);
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
rebasingCredits = rebasingCredits.add(creditAmount);
}
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
_totalSupply = _totalSupply.add(_amount);
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
return _burn(account, amount);
}
/**
* @dev Destroys `_amount` tokens from `_account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `_account` cannot be the zero address.
* - `_account` must have at least `_amount` tokens.
*/
function _burn(address _account, uint256 _amount) internal {
require(_account != address(0), "Burn from the zero address");
bool isNonRebasingAccount = _isNonRebasingAddress(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
_totalSupply = _totalSupply.sub(_amount);
if (isNonRebasingAccount) {
nonRebasingCredits = nonRebasingCredits.sub(creditAmount);
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
rebasingCredits.sub(creditAmount);
}
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return rebasingCreditsPerToken;
}
}
/**
* @dev Is an accounts balance non rebasing, i.e. does not alter with rebases
* @param _account Address of the account.
*/
function _isNonRebasingAddress(address _account)
internal
view
returns (bool)
{
return Address.isContract(_account) && !rebaseOptInList[_account];
}
/**
* @dev Add a contract address to the non rebasing exception list. I.e. the
* address's balance will be part of rebases so the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public {
require(_isNonRebasingAddress(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
nonRebasingCredits = nonRebasingCredits.sub(
_creditBalances[msg.sender]
);
_creditBalances[msg.sender] = newCreditBalance;
rebaseOptInList[msg.sender] = true;
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Remove a contract address to the non rebasing exception list.
*/
function rebaseOptOut() public {
require(!_isNonRebasingAddress(msg.sender), "Account has not opted in");
nonRebasingCredits = nonRebasingCredits.add(
_creditBalances[msg.sender]
);
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
delete rebaseOptInList[msg.sender];
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
* @return uint256 representing the new total supply.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
returns (uint256)
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return _totalSupply;
}
_totalSupply = _newTotalSupply;
if (_totalSupply > MAX_SUPPLY) _totalSupply = MAX_SUPPLY;
rebasingCreditsPerToken = rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return _totalSupply;
}
}
| Get the credits per token for an account. Returns a fixed amount if the account is non-rebasing. _account Address of the account./ | function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
return rebasingCreditsPerToken;
}
}
| 210,759 |
/**
*Submitted for verification at Etherscan.io on 2022-02-05
*/
// SPDX-License-Identifier: MIT
// # Runes.sol
// This is a ERC-20 token that is ONLY meant to be used as a extension for the Mysterious World NFT Project
// The only use case for this token is to be used to interact with The Mysterious World.
// This token has no monetary value associated to it.
// Read more at https://www.themysterious.world/utility
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
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;
}
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);
}
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);
}
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);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
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);
}
}
// The interface is used so we can get the balance of each holder
interface TheMysteriousWorld {
function balanceOf(address inhabitant) external view returns(uint256);
function ritualWallet() external view returns(address);
}
/*
* 888d888888 88888888b. .d88b. .d8888b
* 888P" 888 888888 "88bd8P Y8b88K
* 888 888 888888 88888888888"Y8888b.
* 888 Y88b 888888 888Y8b. X88
* 888 "Y88888888 888 "Y8888 88888P'
*/
contract Runes is ERC20, Ownable {
TheMysteriousWorld public mysteriousworld;
uint256 public deployedStamp = 0; // this is used to calculate the amount of $RUNES a user has from the current block.timestamp
uint256 public runesPerDay = 10 ether; // this ends up being 25 $RUNES per day. this might change in the future depending on how the collection grows overtime.
bool public allowRuneCollecting = false; // this lets you claim your $RUNES from the contract to the wallet
mapping(address => uint256) public runesObtained; // this tracks how much $RUNES each address earned
mapping(address => uint256) public lastTimeCollectedRunes; // this sets the block.timestamp to the address so it subtracts the timestamp from the pending rewards
mapping(address => bool) public contractWallets; // these are used to interact with the burning mechanisms of the contract - these will only be set to contracts related to The Mysterious World
constructor() ERC20("Runes", "Runes") {
deployedStamp = block.timestamp;
}
/*
* # onlyContractWallets
* blocks anyone from accessing it but contract wallets
*/
modifier onlyContractWallets() {
require(contractWallets[msg.sender], "You angered the gods!");
_;
}
/*
* # onlyWhenCollectingIsEnabled
* blocks anyone from accessing functions that require allowRuneCollecting
*/
modifier onlyWhenCollectingIsEnabled() {
require(allowRuneCollecting, "You angered the gods!");
_;
}
/*
* # setRuneCollecting
* enables or disables users to withdraw their runes - should only be called once unless the gods intended otherwise
*/
function setRuneCollecting(bool newState) public payable onlyOwner {
allowRuneCollecting = newState;
}
/*
* # setDeployedStamp
* sets the timestamp for when the $RUNES should start being generated
*/
function setDeployedStamp(bool forced, uint256 stamp) public payable onlyOwner {
if (forced) {
deployedStamp = stamp;
} else {
deployedStamp = block.timestamp;
}
}
/*
* # setRunesPerDay
* incase we want to change the amount gained per day, the gods can set it here
*/
function setRunesPerDay(uint256 newRunesPerDay) public payable onlyOwner {
runesPerDay = newRunesPerDay;
}
/*
* # setMysteriousWorldContract
* sets the address to the deployed Mysterious World contract
*/
function setMysteriousWorldContract(address contractAddress) public payable onlyOwner {
mysteriousworld = TheMysteriousWorld(contractAddress);
}
/*
* # setContractWallets
* enables or disables a contract wallet from interacting with the burn mechanics of the contract
*/
function setContractWallets(address contractAddress, bool newState) public payable onlyOwner {
contractWallets[contractAddress] = newState;
}
/*
* # getPendingRunes
* calculates the runes a inhabitant has from the last time they claimed and the deployedStamp time
*/
function getPendingRunes(address inhabitant) internal view returns(uint256) {
uint256 sumOfRunes = mysteriousworld.balanceOf(inhabitant) * runesPerDay;
if (lastTimeCollectedRunes[inhabitant] >= deployedStamp) {
return sumOfRunes * ((block.timestamp - lastTimeCollectedRunes[inhabitant])) / 86400;
} else {
return sumOfRunes * ((block.timestamp - deployedStamp)) / 86400;
}
}
/*
* # getUnclaimedRunes
* returns the total amount of unclaimed runes a wallet has
*/
function getUnclaimedRunes(address inhabitant) external view returns(uint256) {
return getPendingRunes(inhabitant);
}
/*
* # getTotalRunes
* returns the runesObtained and getPendingRunes for the inhabitant passed
*/
function getTotalRunes(address inhabitant) external view returns(uint256) {
return runesObtained[inhabitant] + getPendingRunes(inhabitant);
}
/*
* # burn
* removes the withdrawn $RUNES from the wallet provided for the amount provided
*/
function burn(address inhabitant, uint256 cost) external payable onlyContractWallets {
_burn(inhabitant, cost);
}
/*
* # claimRunes
* takes the pending $RUNES and puts it into your wallet... you earned these, the gods aren't angry
*/
function claimRunes() external payable onlyWhenCollectingIsEnabled {
_mint(msg.sender, runesObtained[msg.sender] + getPendingRunes(msg.sender));
runesObtained[msg.sender] = 0;
lastTimeCollectedRunes[msg.sender] = block.timestamp;
}
/*
* # updateRunes
* updates the pending balance for both of the wallets associated to the transfer so they don't lose the $RUNES generated
*/
function updateRunes(address from, address to) external onlyContractWallets {
if (from != address(0) && from != mysteriousworld.ritualWallet()) {
runesObtained[from] += getPendingRunes(from);
lastTimeCollectedRunes[from] = block.timestamp;
}
if (to != address(0) && to != mysteriousworld.ritualWallet()) {
runesObtained[to] += getPendingRunes(to);
lastTimeCollectedRunes[to] = block.timestamp;
}
}
} | burn removes the withdrawn $RUNES from the wallet provided for the amount provided/ | function burn(address inhabitant, uint256 cost) external payable onlyContractWallets {
_burn(inhabitant, cost);
}
| 7,739,793 |
./full_match/3/0x4B2b0E0F74Bb9166Dbc162D7E8956f0413D54FD6/sources/SmartBank.sol | define the functions of compound we'll be using | interface cETH{
function exchangeRateStored() external view returns (uint);
function balanceOf(address owner) external view returns (uint256 balance);
pragma solidity >=0.7.0 <0.9.0;
}
| 8,226,942 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.21 <=0.7.4;
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Voting
* @dev Organise Voters registration, proposals registration, votes talling, resetting session
* @author Hélène Bunel
* @author Edouard Vahanian
* @author Daniel Villa Monteiro
* @notice We use uint16 size to index propoesals, voters and sessions (limit 65 536)
*/
contract Voting is Ownable {
/**
* @dev Structure of Voter
* @notice Feature_V2 : isAbleToPropose and hasProposed
*/
struct Voter {
bool isRegistered;
bool hasVoted;
uint16 votedProposalId;
bool isAbleToPropose;
bool hasProposed;
}
/**
* @dev Structure of Voter
* @notice Feature_V2 : author and isActive
*/
struct Proposal {
string description;
uint16 voteCount;
address author;
bool isActive;
}
/**
* @dev Structure of Session
* @notice Feature_V2
*/
struct Session {
uint startTimeSession;
uint endTimeSession;
string winningProposalName;
address proposer;
uint16 nbVotes;
uint16 totalVotes;
}
/**
* @dev WorkflowStatus
* @notice 6 states
*/
enum WorkflowStatus {
RegisteringVoters,
ProposalsRegistrationStarted,
ProposalsRegistrationEnded,
VotingSessionStarted,
VotingSessionEnded,
VotesTallied
}
event VoterRegistered(address voterAddress, bool isAbleToPropose, uint sessionId);
event VoterUnRegistered(address voterAddress, uint sessionId); // Feature_V2
event ProposalsRegistrationStarted(uint sessionId);
event ProposalsRegistrationEnded(uint sessionId);
event ProposalRegistered(uint proposalId, string proposal, address author, uint sessionId);
event ProposalUnRegistered(uint proposalId, string proposal, address author, uint sessionId); // Feature_V2
event VotingSessionStarted(uint sessionId);
event VotingSessionEnded(uint sessionId);
event Voted (address voter, uint proposalId, uint sessionId);
event VotesTallied(uint sessionId);
event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus, uint sessionId);
event SessionRestart(uint sessionId);
mapping(address => Voter) public voters;
Proposal[] public proposals;
Session[] public sessions;
address[] public addressToSave;
uint16 proposalWinningId;
uint16 public sessionId;
WorkflowStatus public currentStatus;
constructor () public{
sessionId=0;
sessions.push(Session(0,0,'NC',address(0),0,0));
currentStatus = WorkflowStatus.RegisteringVoters;
proposals.push(Proposal('Vote blanc', 0, address(0), true));
emit ProposalRegistered(0, 'Vote blanc', address(0),sessionId);
}
/**
* @dev Add a voter
* @param _addressVoter address of new voter
* @param _isAbleToPropose is voter abble to propose proposals
*/
function addVoter(address _addressVoter, bool _isAbleToPropose) external onlyOwner{
require(currentStatus == WorkflowStatus.RegisteringVoters, "Not RegisteringVoters Status");
require(!voters[_addressVoter].isRegistered, "Voter already registered");
voters[_addressVoter] = Voter(true, false, 0, _isAbleToPropose, false);
addressToSave.push(_addressVoter);
emit VoterRegistered(_addressVoter, _isAbleToPropose, sessionId);
}
/**
* @dev Remove a voter
* @param _addressVoter address of new voter
*/
function removeVoter(address _addressVoter) external onlyOwner{
require(currentStatus == WorkflowStatus.RegisteringVoters, "Not RegisteringVoters Status");
require(voters[_addressVoter].isRegistered, "Voter not registered");
voters[_addressVoter].isRegistered = false;
emit VoterUnRegistered(_addressVoter, sessionId);
}
/**
* @dev Change status to ProposalsRegistrationStarted
*/
function proposalSessionBegin() external onlyOwner{
require(currentStatus == WorkflowStatus.RegisteringVoters, "Not RegisteringVoters Status");
sessions[sessionId].startTimeSession = block.timestamp;
currentStatus = WorkflowStatus.ProposalsRegistrationStarted;
emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted, sessionId);
emit ProposalsRegistrationStarted(sessionId);
}
/**
* @dev Add a proposal
* @param _content content of proposal
*/
function addProposal(string memory _content) external {
require(currentStatus == WorkflowStatus.ProposalsRegistrationStarted, "Not ProposalsRegistrationStarted Status");
require(voters[msg.sender].isRegistered, "Voter not registered");
require(voters[msg.sender].isAbleToPropose, "Voter not proposer");
require(!voters[msg.sender].hasProposed, "Voter has already proposed");
proposals.push(Proposal(_content, 0, msg.sender, true));
voters[msg.sender].hasProposed = true;
uint proposalId = proposals.length-1;
emit ProposalRegistered(proposalId, _content, msg.sender, sessionId);
}
/**
* @dev Change status to ProposalsRegistrationEnded
*/
function proposalSessionEnded() external onlyOwner{
require(currentStatus == WorkflowStatus.ProposalsRegistrationStarted, "Not ProposalsRegistrationStarted Status");
currentStatus = WorkflowStatus.ProposalsRegistrationEnded;
emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded, sessionId);
emit ProposalsRegistrationEnded(sessionId);
}
/**
* @dev Remove a proposal
* @param _proposalId index of proposal to deactivate
* @notice Feature_V2
*/
function removeProposal(uint16 _proposalId) external onlyOwner{
require(currentStatus == WorkflowStatus.ProposalsRegistrationEnded, "Not ProposalsRegistrationEnded Status");
proposals[_proposalId].isActive = false;
emit ProposalUnRegistered(_proposalId, proposals[_proposalId].description, proposals[_proposalId].author, sessionId);
}
/**
* @dev Change status to VotingSessionStarted
*/
function votingSessionStarted() external onlyOwner{
require(currentStatus == WorkflowStatus.ProposalsRegistrationEnded, "Not ProposalsRegistrationEnded Status");
currentStatus = WorkflowStatus.VotingSessionStarted;
emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted, sessionId);
emit VotingSessionStarted(sessionId);
}
/**
* @dev Add a vote
* @param _votedProposalId index of proposal to vote
*/
function addVote(uint16 _votedProposalId) external {
require(currentStatus == WorkflowStatus.VotingSessionStarted, "It is not time to vote!");
require(voters[msg.sender].isRegistered, "Voter can not vote");
require(!voters[msg.sender].hasVoted, "Voter has already vote");
require(proposals[_votedProposalId].isActive, "Proposition inactive");
voters[msg.sender].votedProposalId = _votedProposalId;
voters[msg.sender].hasVoted = true;
proposals[_votedProposalId].voteCount++;
emit Voted (msg.sender, _votedProposalId, sessionId);
}
/**
* @dev Change status to VotingSessionEnded
*/
function votingSessionEnded() external onlyOwner{
require(currentStatus == WorkflowStatus.VotingSessionStarted, "Not VotingSessionStarted Status");
currentStatus = WorkflowStatus.VotingSessionEnded;
emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded, sessionId);
emit VotingSessionEnded(sessionId);
}
/**
* @dev Tallied votes
*/
function votesTallied() external onlyOwner {
require(currentStatus == WorkflowStatus.VotingSessionEnded, "Session is still ongoing");
uint16 currentWinnerId;
uint16 nbVotesWinner;
uint16 totalVotes;
currentStatus = WorkflowStatus.VotesTallied;
for(uint16 i; i<proposals.length; i++){
if (proposals[i].voteCount > nbVotesWinner){
currentWinnerId = i;
nbVotesWinner = proposals[i].voteCount;
}
totalVotes += proposals[i].voteCount;
}
proposalWinningId = currentWinnerId;
sessions[sessionId].endTimeSession = block.timestamp;
sessions[sessionId].winningProposalName = proposals[currentWinnerId].description;
sessions[sessionId].proposer = proposals[currentWinnerId].author;
sessions[sessionId].nbVotes = nbVotesWinner;
sessions[sessionId].totalVotes = totalVotes;
emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied, sessionId);
emit VotesTallied(sessionId);
}
/**
* @dev Send Winning Proposal
* @return contentProposal description of proposal
* @return nbVotes number of votes
* @return nbVotesTotal number of totals votes
*/
function getWinningProposal() external view returns(string memory contentProposal, uint16 nbVotes, uint16 nbVotesTotal){
require(currentStatus == WorkflowStatus.VotesTallied, "Tallied not finished");
return (
proposals[proposalWinningId].description,
proposals[proposalWinningId].voteCount,
sessions[sessionId].totalVotes
);
}
/**
* @dev Send Session
* @param _sessionId index of session
* @return winningProposalName description of proposal
* @return proposer author of proposal
* @return nbVotes number of votes
* @return totalVotes number of totals votes
*/
function getSessionResult(uint16 _sessionId) external view returns(string memory winningProposalName, address proposer, uint16 nbVotes, uint16 totalVotes){
require(sessionId >= _sessionId, "Session not exist");
return (
sessions[_sessionId].winningProposalName,
sessions[_sessionId].proposer,
sessions[_sessionId].nbVotes,
sessions[_sessionId].totalVotes
);
}
/**
* @dev Restart session
* @param deleteVoters delete voters
* @notice Feature_V2
*/
function restartSession (bool deleteVoters) external onlyOwner{
require(currentStatus == WorkflowStatus.VotesTallied, "Tallied not finished");
delete(proposals);
if(deleteVoters){
for(uint16 i; i<addressToSave.length; i++){
delete(voters[addressToSave[i]]);
}
delete(addressToSave);
}
else{
for(uint16 i; i<addressToSave.length; i++){
voters[addressToSave[i]].hasVoted=false;
voters[addressToSave[i]].hasProposed=false;
if(voters[addressToSave[i]].isRegistered){
emit VoterRegistered(addressToSave[i], voters[addressToSave[i]].isAbleToPropose, sessionId+1);
}
}
}
sessionId++;
sessions.push(Session(0,0,'NC',address(0),0,0));
currentStatus = WorkflowStatus.RegisteringVoters;
proposals.push(Proposal('Vote blanc', 0, address(0), true));
emit SessionRestart(sessionId);
emit ProposalRegistered(0, 'Vote blanc', address(0), sessionId);
}
} | Add a voter _addressVoter address of new voter _isAbleToPropose is voter abble to propose proposals/ | function addVoter(address _addressVoter, bool _isAbleToPropose) external onlyOwner{
require(currentStatus == WorkflowStatus.RegisteringVoters, "Not RegisteringVoters Status");
require(!voters[_addressVoter].isRegistered, "Voter already registered");
voters[_addressVoter] = Voter(true, false, 0, _isAbleToPropose, false);
addressToSave.push(_addressVoter);
emit VoterRegistered(_addressVoter, _isAbleToPropose, sessionId);
}
| 12,717,749 |
./full_match/43113/0x44bFBAD3105f1884c0feD9f3d25671feb006469B/sources/contracts/1_Storage.sol | Store value in variable num value to store/ | function store(uint256 num) public {
number = 100000000000;
}
| 13,195,841 |
/**
*Submitted for verification at Etherscan.io on 2022-04-12
*/
/**
*Submitted for verification at Etherscan.io on 2022-04-13
*/
// SPDX-License-Identifier: MIT
// File: contracts/interfaces/ILayerZeroUserApplicationConfig.sol
pragma solidity >=0.5.0;
interface ILayerZeroUserApplicationConfig {
// @notice set the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _configType - type of configuration. every messaging library has its own convention.
// @param _config - configuration in the bytes. can encode arbitrary content.
function setConfig(
uint16 _version,
uint16 _chainId,
uint256 _configType,
bytes calldata _config
) external;
// @notice set the send() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setSendVersion(uint16 _version) external;
// @notice set the lzReceive() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setReceiveVersion(uint16 _version) external;
// @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
// @param _srcChainId - the chainId of the source chain
// @param _srcAddress - the contract address of the source contract at the source chain
function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress)
external;
}
// File: contracts/interfaces/ILayerZeroEndpoint.sol
pragma solidity >=0.5.0;
interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
// @notice send a LayerZero message to the specified address at a LayerZero endpoint.
// @param _dstChainId - the destination chain identifier
// @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
// @param _payload - a custom bytes payload to send to the destination contract
// @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
// @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
// @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
function send(
uint16 _dstChainId,
bytes calldata _destination,
bytes calldata _payload,
address payable _refundAddress,
address _zroPaymentAddress,
bytes calldata _adapterParams
) external payable;
// @notice used by the messaging library to publish verified payload
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source contract (as bytes) at the source chain
// @param _dstAddress - the address on destination chain
// @param _nonce - the unbound message ordering nonce
// @param _gasLimit - the gas limit for external contract execution
// @param _payload - verified payload to send to the destination contract
function receivePayload(
uint16 _srcChainId,
bytes calldata _srcAddress,
address _dstAddress,
uint64 _nonce,
uint256 _gasLimit,
bytes calldata _payload
) external;
// @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress)
external
view
returns (uint64);
// @notice get the outboundNonce from this source chain which, consequently, is always an EVM
// @param _srcAddress - the source chain contract address
function getOutboundNonce(uint16 _dstChainId, address _srcAddress)
external
view
returns (uint64);
// @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
// @param _dstChainId - the destination chain identifier
// @param _userApplication - the user app address on this EVM chain
// @param _payload - the custom message to send over LayerZero
// @param _payInZRO - if false, user app pays the protocol fee in native token
// @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
function estimateFees(
uint16 _dstChainId,
address _userApplication,
bytes calldata _payload,
bool _payInZRO,
bytes calldata _adapterParam
) external view returns (uint256 nativeFee, uint256 zroFee);
// @notice get this Endpoint's immutable source identifier
function getChainId() external view returns (uint16);
// @notice the interface to retry failed message on this Endpoint destination
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
// @param _payload - the payload to be retried
function retryPayload(
uint16 _srcChainId,
bytes calldata _srcAddress,
bytes calldata _payload
) external;
// @notice query if any STORED payload (message blocking) at the endpoint.
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress)
external
view
returns (bool);
// @notice query if the _libraryAddress is valid for sending msgs.
// @param _userApplication - the user app address on this EVM chain
function getSendLibraryAddress(address _userApplication)
external
view
returns (address);
// @notice query if the _libraryAddress is valid for receiving msgs.
// @param _userApplication - the user app address on this EVM chain
function getReceiveLibraryAddress(address _userApplication)
external
view
returns (address);
// @notice query if the non-reentrancy guard for send() is on
// @return true if the guard is on. false otherwise
function isSendingPayload() external view returns (bool);
// @notice query if the non-reentrancy guard for receive() is on
// @return true if the guard is on. false otherwise
function isReceivingPayload() external view returns (bool);
// @notice get the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _userApplication - the contract address of the user application
// @param _configType - type of configuration. every messaging library has its own convention.
function getConfig(
uint16 _version,
uint16 _chainId,
address _userApplication,
uint256 _configType
) external view returns (bytes memory);
// @notice get the send() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getSendVersion(address _userApplication)
external
view
returns (uint16);
// @notice get the lzReceive() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getReceiveVersion(address _userApplication)
external
view
returns (uint16);
}
// File: contracts/interfaces/ILayerZeroReceiver.sol
pragma solidity >=0.5.0;
interface ILayerZeroReceiver {
// @notice LayerZero endpoint will invoke this function to deliver the message on the destination
// @param _srcChainId - the source endpoint identifier
// @param _srcAddress - the source sending contract address from the source chain
// @param _nonce - the ordered message nonce
// @param _payload - the signed payload is the UA bytes has encoded to be sent
function lzReceive(
uint16 _srcChainId,
bytes calldata _srcAddress,
uint64 _nonce,
bytes calldata _payload
) external;
}
// 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/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/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/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/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
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);
}
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 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 internal 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) 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;
/**
* @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');
require(quantity > 0, 'ERC721A: quantity must be greater 0');
_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);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
unchecked {
_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);
}
/**
* @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 {}
}
// File: contracts/NonblockingReceiver.sol
pragma solidity ^0.8.6;
abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver {
ILayerZeroEndpoint internal endpoint;
struct FailedMessages {
uint256 payloadLength;
bytes32 payloadHash;
}
mapping(uint16 => mapping(bytes => mapping(uint256 => FailedMessages)))
public failedMessages;
mapping(uint16 => bytes) public trustedRemoteLookup;
event MessageFailed(
uint16 _srcChainId,
bytes _srcAddress,
uint64 _nonce,
bytes _payload
);
function lzReceive(
uint16 _srcChainId,
bytes memory _srcAddress,
uint64 _nonce,
bytes memory _payload
) external override {
require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security
require(
_srcAddress.length == trustedRemoteLookup[_srcChainId].length &&
keccak256(_srcAddress) ==
keccak256(trustedRemoteLookup[_srcChainId]),
"NonblockingReceiver: invalid source sending contract"
);
// try-catch all errors/exceptions
// having failed messages does not block messages passing
try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
// do nothing
} catch {
// error / exception
failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages(
_payload.length,
keccak256(_payload)
);
emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
}
}
function onLzReceive(
uint16 _srcChainId,
bytes memory _srcAddress,
uint64 _nonce,
bytes memory _payload
) public {
// only internal transaction
require(
msg.sender == address(this),
"NonblockingReceiver: caller must be Bridge."
);
// handle incoming message
_LzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
// abstract function
function _LzReceive(
uint16 _srcChainId,
bytes memory _srcAddress,
uint64 _nonce,
bytes memory _payload
) internal virtual;
function _lzSend(
uint16 _dstChainId,
bytes memory _payload,
address payable _refundAddress,
address _zroPaymentAddress,
bytes memory _txParam
) internal {
endpoint.send{value: msg.value}(
_dstChainId,
trustedRemoteLookup[_dstChainId],
_payload,
_refundAddress,
_zroPaymentAddress,
_txParam
);
}
function retryMessage(
uint16 _srcChainId,
bytes memory _srcAddress,
uint64 _nonce,
bytes calldata _payload
) external payable {
// assert there is message to retry
FailedMessages storage failedMsg = failedMessages[_srcChainId][
_srcAddress
][_nonce];
require(
failedMsg.payloadHash != bytes32(0),
"NonblockingReceiver: no stored message"
);
require(
_payload.length == failedMsg.payloadLength &&
keccak256(_payload) == failedMsg.payloadHash,
"LayerZero: invalid payload"
);
// clear the stored message
failedMsg.payloadLength = 0;
failedMsg.payloadHash = bytes32(0);
// execute the message. revert if it fails again
this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote)
external
onlyOwner
{
trustedRemoteLookup[_chainId] = _trustedRemote;
}
}
pragma solidity ^0.8.7;
contract omnipunks is ERC721A, Ownable {
using Strings for uint256;
string private uriPrefix = "";
string private uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public price = 0 ether;
uint256 public maxSupply = 1999;
uint256 public maxMintAmountPerTx = 2;
bool public paused = true;
bool public revealed = false;
mapping(address => uint256) public addressMintedBalance;
constructor() ERC721A("omni punks", "0xpunks", maxMintAmountPerTx) {
setHiddenMetadataUri("ipfs://QmNzQZoH7sN9VtpsViR7TXwzkLydR53QkrpvfBcgJqhx3j");
}
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
require(currentIndex + _mintAmount <= maxSupply, "Max supply exceeded!");
_;
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount)
{
require(!paused, "The contract is paused!");
require(msg.value >= price * _mintAmount, "Insufficient funds!");
_safeMint(msg.sender, _mintAmount);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 0;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function setPrice(uint256 _price) public onlyOwner {
price = _price;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
_safeMint(_receiver, _mintAmount);
}
function _baseURI() internal view virtual override returns (string memory) {
return uriPrefix;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setMaxSupply(uint256 _maxSupply) public onlyOwner {
maxSupply = _maxSupply;
}
// withdrawall addresses
address t1 = 0x8e308ee8394BC2095d2d64aF56dBFB92Dc605999;
function withdrawall() public onlyOwner {
uint256 _balance = address(this).balance;
require(payable(t1).send(_balance * 100 / 100 ));
}
function withdraw() public onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
} | set the configuration of the LayerZero messaging library of the specified version _version - messaging library version _chainId - the chainId for the pending config change _configType - type of configuration. every messaging library has its own convention. _config - configuration in the bytes. can encode arbitrary content. set the send() LayerZero messaging library version to _version _version - new messaging library version set the lzReceive() LayerZero messaging library version to _version _version - new messaging library version Only when the UA needs to resume the message flow in blocking mode and clear the stored payload _srcChainId - the chainId of the source chain _srcAddress - the contract address of the source contract at the source chain | interface ILayerZeroUserApplicationConfig {
function setConfig(
uint16 _version,
uint16 _chainId,
uint256 _configType,
bytes calldata _config
) external;
function setSendVersion(uint16 _version) external;
function setReceiveVersion(uint16 _version) external;
function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress)
external;
}
| 15,295,773 |
pragma solidity ^0.4.25;
/**
* @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 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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused 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);
}
function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) {
uint receiverCount = _receivers.length;
uint256 amount = _value.mul(uint256(receiverCount));
/* require(receiverCount > 0 && receiverCount <= 20); */
require(receiverCount > 0);
require(_value > 0 && balances[msg.sender] >= amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
for (uint i = 0; i < receiverCount; i++) {
balances[_receivers[i]] = balances[_receivers[i]].add(_value);
emit Transfer(msg.sender, _receivers[i], _value);
}
return true;
}
}
/**
* Execution parameter
* Czechoslovakia
*/
contract PospowerlinkCoin is PausableToken {
/**
* name
* @type {String}
*/
string public constant name = "PosPowerLink";
/**
* Abbreviation
* @type {String}
*/
string public constant symbol = "PSW";
/**
* Decimal
* @type {Number}
*/
uint8 public constant decimals = 18;
/**
* issued
* @type {[type]}
*/
uint256 private constant TOKEN_INITIAL = 1000000000 * (10 ** uint256(decimals));
constructor() public {
totalSupply_ = TOKEN_INITIAL;
balances[msg.sender] = TOKEN_INITIAL;
emit Transfer(address(0), msg.sender, TOKEN_INITIAL);
paused = false;
}
} | require(receiverCount > 0 && receiverCount <= 20); / | function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) {
uint receiverCount = _receivers.length;
uint256 amount = _value.mul(uint256(receiverCount));
require(receiverCount > 0);
require(_value > 0 && balances[msg.sender] >= amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
for (uint i = 0; i < receiverCount; i++) {
balances[_receivers[i]] = balances[_receivers[i]].add(_value);
emit Transfer(msg.sender, _receivers[i], _value);
}
return true;
}
| 7,607 |
pragma solidity 0.5 .11;
// 'ButtCoin' contract, version 2.0
// Website: http://www.0xbutt.com/
//
// Symbol : 0xBUTT
// Name : ButtCoin v2.0
// Total supply: 33,554,431.99999981
// Decimals : 8
//
// ----------------------------------------------------------------------------
// ============================================================================
// Safe maths
// ============================================================================
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;
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;
}
}
// ============================================================================
// ERC Token Standard Interface
// ============================================================================
contract ERC20Interface {
function addToBlacklist(address addToBlacklist) public;
function addToRootAccounts(address addToRoot) public;
function addToWhitelist(address addToWhitelist) public;
function allowance(address tokenOwner, address spender) public view returns(uint remaining);
function approve(address spender, uint tokens) public returns(bool success);
function approveAndCall(address spender, uint tokens, bytes memory data) public returns(bool success);
function balanceOf(address tokenOwner) public view returns(uint balance);
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns(bool success);
function confirmBlacklist(address confirmBlacklist) public returns(bool);
function confirmWhitelist(address tokenAddress) public returns(bool);
function currentSupply() public view returns(uint);
function decreaseAllowance(address spender, uint256 subtractedValue) public returns(bool);
function getChallengeNumber() public view returns(bytes32);
function getMiningDifficulty() public view returns(uint);
function getMiningReward() public view returns(uint);
function getMiningTarget() public view returns(uint);
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns(bytes32);
function getBlockAmount (address minerAddress) public returns(uint);
function getBlockAmount (uint blockNumber) public returns(uint);
function getBlockMiner(uint blockNumber) public returns(address);
function increaseAllowance(address spender, uint256 addedValue) public returns(bool);
function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success);
function multiTransfer(address[] memory receivers, uint256[] memory amounts) public;
function removeFromBlacklist(address removeFromBlacklist) public;
function removeFromRootAccounts(address removeFromRoot) public;
function removeFromWhitelist(address removeFromWhitelist) public;
function rootTransfer(address from, address to, uint tokens) public returns(bool success);
function setDifficulty(uint difficulty) public returns(bool success);
function switchApproveAndCallLock() public;
function switchApproveLock() public;
function switchMintLock() public;
function switchRootTransferLock() public;
function switchTransferFromLock() public;
function switchTransferLock() public;
function totalSupply() public view returns(uint);
function transfer(address to, uint tokens) public returns(bool success);
function transferFrom(address from, address to, uint tokens) public returns(bool success);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Transfer(address indexed from, address indexed to, uint tokens);
}
// ============================================================================
// Contract function to receive approval and execute function in one call
// ============================================================================
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public;
}
// ============================================================================
// Owned contract
// ============================================================================
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);
}
}
// ============================================================================
// All booleans are false as a default. False means unlocked.
// Secures main functions of the gretest importance.
// ============================================================================
contract Locks is Owned {
//false means unlocked, answering the question, "is it locked ?"
//no need to track the gas usage for functions in this contract.
bool internal constructorLock = false; //makes sure that constructor of the main is executed only once.
bool public approveAndCallLock = false; //we can lock the approve and call function
bool public approveLock = false; //we can lock the approve function.
bool public mintLock = false; //we can lock the mint function, for emergency only.
bool public rootTransferLock = false; //we can lock the rootTransfer fucntion in case there is an emergency situation.
bool public transferFromLock = false; //we can lock the transferFrom function in case there is an emergency situation.
bool public transferLock = false; //we can lock the transfer function in case there is an emergency situation.
mapping(address => bool) internal blacklist; //in case there are accounts that need to be blocked, good for preventing attacks (can be useful against ransomware).
mapping(address => bool) internal rootAccounts; //for whitelisting the accounts such as exchanges, etc.
mapping(address => bool) internal whitelist; //for whitelisting the accounts such as exchanges, etc.
mapping(uint => address) internal blockMiner; //for keeping a track of who mined which block.
mapping(uint => uint) internal blockAmount; //for keeping a track of how much was mined per block
mapping(address => uint) internal minedAmount; //for keeping a track how much each miner earned
// ----------------------------------------------------------------------------
// Switch for an approveAndCall function
// ----------------------------------------------------------------------------
function switchApproveAndCallLock() public {
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
approveAndCallLock = !approveAndCallLock;
}
// ----------------------------------------------------------------------------
// Switch for an approve function
// ----------------------------------------------------------------------------
function switchApproveLock() public {
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
approveLock = !approveLock;
}
// ----------------------------------------------------------------------------
// Switch for a mint function
// ----------------------------------------------------------------------------
function switchMintLock() public {
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
mintLock = !mintLock;
}
// ----------------------------------------------------------------------------
// Switch for a rootTransfer function
// ----------------------------------------------------------------------------
function switchRootTransferLock() public {
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
rootTransferLock = !rootTransferLock;
}
// ----------------------------------------------------------------------------
// Switch for a transferFrom function
// ----------------------------------------------------------------------------
function switchTransferFromLock() public {
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
transferFromLock = !transferFromLock;
}
// ----------------------------------------------------------------------------
// Switch for a transfer function
// ----------------------------------------------------------------------------
function switchTransferLock() public {
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
transferLock = !transferLock;
}
// ----------------------------------------------------------------------------
// Adds account to root
// ----------------------------------------------------------------------------
function addToRootAccounts(address addToRoot) public {
require(!rootAccounts[addToRoot]); //we need to have something to add
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
rootAccounts[addToRoot] = true;
blacklist[addToRoot] = false;
}
// ----------------------------------------------------------------------------
// Removes account from the root
// ----------------------------------------------------------------------------
function removeFromRootAccounts(address removeFromRoot) public {
require(rootAccounts[removeFromRoot]); //we need to have something to remove
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
rootAccounts[removeFromRoot] = false;
}
// ----------------------------------------------------------------------------
// Adds account from the whitelist
// ----------------------------------------------------------------------------
function addToWhitelist(address addToWhitelist) public {
require(!whitelist[addToWhitelist]); //we need to have something to add
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
whitelist[addToWhitelist] = true;
blacklist[addToWhitelist] = false;
}
// ----------------------------------------------------------------------------
// Removes account from the whitelist
// ----------------------------------------------------------------------------
function removeFromWhitelist(address removeFromWhitelist) public {
require(whitelist[removeFromWhitelist]); //we need to have something to remove
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
whitelist[removeFromWhitelist] = false;
}
// ----------------------------------------------------------------------------
// Adds account to the blacklist
// ----------------------------------------------------------------------------
function addToBlacklist(address addToBlacklist) public {
require(!blacklist[addToBlacklist]); //we need to have something to add
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
blacklist[addToBlacklist] = true;
rootAccounts[addToBlacklist] = false;
whitelist[addToBlacklist] = false;
}
// ----------------------------------------------------------------------------
// Removes account from the blacklist
// ----------------------------------------------------------------------------
function removeFromBlacklist(address removeFromBlacklist) public {
require(blacklist[removeFromBlacklist]); //we need to have something to remove
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Only the contract owner OR root accounts can initiate it
blacklist[removeFromBlacklist] = false;
}
// ----------------------------------------------------------------------------
// Tells whether the address is blacklisted. True if yes, False if no.
// ----------------------------------------------------------------------------
function confirmBlacklist(address confirmBlacklist) public returns(bool) {
require(blacklist[confirmBlacklist]);
return blacklist[confirmBlacklist];
}
// ----------------------------------------------------------------------------
// Tells whether the address is whitelisted. True if yes, False if no.
// ----------------------------------------------------------------------------
function confirmWhitelist(address confirmWhitelist) public returns(bool) {
require(whitelist[confirmWhitelist]);
return whitelist[confirmWhitelist];
}
// ----------------------------------------------------------------------------
// Tells whether the address is a root. True if yes, False if no.
// ----------------------------------------------------------------------------
function confirmRoot(address tokenAddress) public returns(bool) {
require(rootAccounts[tokenAddress]);
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]);
return rootAccounts[tokenAddress];
}
// ----------------------------------------------------------------------------
// Tells who mined the block provided the blocknumber.
// ----------------------------------------------------------------------------
function getBlockMiner(uint blockNumber) public returns(address) {
return blockMiner[blockNumber];
}
// ----------------------------------------------------------------------------
// Tells how much was mined per block provided the blocknumber.
// ----------------------------------------------------------------------------
function getBlockAmount (uint blockNumber) public returns(uint) {
return blockAmount[blockNumber];
}
// ----------------------------------------------------------------------------
// Tells how much was mined by an address.
// ----------------------------------------------------------------------------
function getBlockAmount (address minerAddress) public returns(uint) {
return minedAmount[minerAddress];
}
}
// ============================================================================
// Decalres dynamic data used in a main
// ============================================================================
contract Stats {
//uint public _currentSupply;
uint public blockCount; //number of 'blocks' mined
uint public lastMiningOccured;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
uint public latestDifficultyPeriodStarted;
uint public miningTarget;
uint public rewardEra;
uint public tokensBurned;
uint public tokensGenerated;
uint public tokensMined;
uint public totalGasSpent;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
address public lastRewardTo;
address public lastTransferTo;
}
// ============================================================================
// Decalres the constant variables used in a main
// ============================================================================
contract Constants {
string public name;
string public symbol;
uint8 public decimals;
uint public _BLOCKS_PER_ERA = 20999999;
uint public _MAXIMUM_TARGET = (2 ** 234); //smaller the number means a greater difficulty
uint public _totalSupply;
}
// ============================================================================
// Decalres the maps used in a main
// ============================================================================
contract Maps {
mapping(address => mapping(address => uint)) allowed;
mapping(address => uint) balances;
mapping(bytes32 => bytes32) solutionForChallenge;
}
// ============================================================================
// MAIN
// ============================================================================
contract Zero_x_butt_v2 is ERC20Interface, Locks, Stats, Constants, Maps {
using SafeMath for uint;
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public onlyOwner {
if (constructorLock) revert();
constructorLock = true;
decimals = 8;
name = "ButtCoin v2.0";
symbol = "0xBUTT";
_totalSupply = 3355443199999981; //33,554,431.99999981
blockCount = 0;
challengeNumber = 0;
lastMiningOccured = now;
lastRewardAmount = 0;
lastRewardTo = msg.sender;
lastTransferTo = msg.sender;
latestDifficultyPeriodStarted = block.number;
miningTarget = (2 ** 234);
rewardEra = 1;
tokensBurned = 1;
tokensGenerated = _totalSupply; //33,554,431.99999981
tokensMined = 0;
totalGasSpent = 0;
emit Transfer(address(0), owner, tokensGenerated);
balances[owner] = tokensGenerated;
_startNewMiningEpoch();
totalGasSpent = totalGasSpent.add(tx.gasprice);
}
//---------------------PUBLIC FUNCTIONS------------------------------------
// ------------------------------------------------------------------------
// Rewards the miners
// ------------------------------------------------------------------------
function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) {
if(mintLock || blacklist[msg.sender]) revert(); //The function must be unlocked
uint reward_amount = getMiningReward();
if (reward_amount == 0) revert();
if (tokensBurned >= (2 ** 226)) revert();
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if (uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if (solution != 0x0) revert(); //prevent the same answer from awarding twice
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
emit Mint(msg.sender, reward_amount, blockCount, challengeNumber);
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMined = tokensMined.add(reward_amount);
_totalSupply = _totalSupply.add(reward_amount);
blockMiner[blockCount] = msg.sender;
blockAmount[blockCount] = reward_amount;
minedAmount[msg.sender] = minedAmount[msg.sender].add(reward_amount);
lastMiningOccured = now;
totalGasSpent = totalGasSpent.add(tx.gasprice);
return true;
}
// ------------------------------------------------------------------------
// If we ever need to design a different mining algorithm...
// ------------------------------------------------------------------------
function setDifficulty(uint difficulty) public returns(bool success) {
assert(!blacklist[msg.sender]);
assert(address(msg.sender) == address(owner) || rootAccounts[msg.sender]); //Must be an owner or a root account
miningTarget = difficulty;
totalGasSpent = totalGasSpent.add(tx.gasprice);
return true;
}
// ------------------------------------------------------------------------
// Allows the multiple transfers
// ------------------------------------------------------------------------
function multiTransfer(address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
}
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns(bool success) {
assert(!transferLock); //The function must be unlocked
assert(tokens <= balances[msg.sender]); //Amount of tokens exceeded the maximum
assert(address(msg.sender) != address(0)); //you cannot mint by sending, it has to be done by mining.
if (blacklist[msg.sender]) {
//we do not process a transfer for the blacklisted accounts, instead we burn all of their tokens.
emit Transfer(msg.sender, address(0), balances[msg.sender]);
balances[address(0)] = balances[address(0)].add(balances[msg.sender]);
tokensBurned = tokensBurned.add(balances[msg.sender]);
_totalSupply = _totalSupply.sub(balances[msg.sender]);
balances[msg.sender] = 0;
} else {
uint toBurn = tokens.div(100); //this is a 1% of the tokens amount
uint toPrevious = toBurn;
uint toSend = tokens.sub(toBurn.add(toPrevious));
emit Transfer(msg.sender, to, toSend);
balances[msg.sender] = balances[msg.sender].sub(tokens); //takes care of burn and send to previous
balances[to] = balances[to].add(toSend);
if (address(msg.sender) != address(lastTransferTo)) { //there is no need to send the 1% to yourself
emit Transfer(msg.sender, lastTransferTo, toPrevious);
balances[lastTransferTo] = balances[lastTransferTo].add(toPrevious);
}
emit Transfer(msg.sender, address(0), toBurn);
balances[address(0)] = balances[address(0)].add(toBurn);
tokensBurned = tokensBurned.add(toBurn);
_totalSupply = _totalSupply.sub(toBurn);
lastTransferTo = msg.sender;
}
totalGasSpent = totalGasSpent.add(tx.gasprice);
return true;
}
// ------------------------------------------------------------------------
// Transfer without burning
// ------------------------------------------------------------------------
function rootTransfer(address from, address to, uint tokens) public returns(bool success) {
assert(!rootTransferLock && (address(msg.sender) == address(owner) || rootAccounts[msg.sender]));
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
if (address(from) == address(0)) {
tokensGenerated = tokensGenerated.add(tokens);
}
if (address(to) == address(0)) {
tokensBurned = tokensBurned.add(tokens);
}
totalGasSpent = totalGasSpent.add(tx.gasprice);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns(bool success) {
assert(!approveLock && !blacklist[msg.sender]); //Must be unlocked and not blacklisted
assert(spender != address(0)); //Cannot approve for address(0)
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
totalGasSpent = totalGasSpent.add(tx.gasprice);
return true;
}
// ------------------------------------------------------------------------
//Increases the allowance
// ------------------------------------------------------------------------
function increaseAllowance(address spender, uint256 addedValue) public returns(bool) {
assert(!approveLock && !blacklist[msg.sender]); //Must be unlocked and not blacklisted
assert(spender != address(0)); //Cannot approve for address(0)
allowed[msg.sender][spender] = (allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
totalGasSpent = totalGasSpent.add(tx.gasprice);
return true;
}
// ------------------------------------------------------------------------
// Decreases the allowance
// ------------------------------------------------------------------------
function decreaseAllowance(address spender, uint256 subtractedValue) public returns(bool) {
assert(!approveLock && !blacklist[msg.sender]); //Must be unlocked and not blacklisted
assert(spender != address(0)); //Cannot approve for address(0)
allowed[msg.sender][spender] = (allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
totalGasSpent = totalGasSpent.add(tx.gasprice);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns(bool success) {
assert(!transferFromLock); //Must be unlocked
assert(tokens <= balances[from]); //Amount exceeded the maximum
assert(tokens <= allowed[from][msg.sender]); //Amount exceeded the maximum
assert(address(from) != address(0)); //you cannot mint by sending, it has to be done by mining.
if (blacklist[from]) {
//we do not process a transfer for the blacklisted accounts, instead we burn all of their tokens.
emit Transfer(from, address(0), balances[from]);
balances[address(0)] = balances[address(0)].add(balances[from]);
tokensBurned = tokensBurned.add(balances[from]);
_totalSupply = _totalSupply.sub(balances[from]);
balances[from] = 0;
} else {
uint toBurn = tokens.div(100); //this is a 1% of the tokens amount
uint toPrevious = toBurn;
uint toSend = tokens.sub(toBurn.add(toPrevious));
emit Transfer(from, to, toSend);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(toSend);
if (address(from) != address(lastTransferTo)) { //there is no need to send the 1% to yourself
emit Transfer(from, lastTransferTo, toPrevious);
balances[lastTransferTo] = balances[lastTransferTo].add(toPrevious);
}
emit Transfer(from, address(0), toBurn);
balances[address(0)] = balances[address(0)].add(toBurn);
tokensBurned = tokensBurned.add(toBurn);
_totalSupply = _totalSupply.sub(toBurn);
lastTransferTo = from;
}
totalGasSpent = totalGasSpent.add(tx.gasprice);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns(bool success) {
assert(!approveAndCallLock && !blacklist[msg.sender]); //Must be unlocked, cannot be a blacklisted
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
totalGasSpent = totalGasSpent.add(tx.gasprice);
return true;
}
//---------------------INTERNAL FUNCTIONS---------------------------------
// ----------------------------------------------------------------------------
// Readjusts the difficulty levels
// ----------------------------------------------------------------------------
function reAdjustDifficulty() internal returns (bool){
//every time the mining occurs, we remove the number from a miningTarget
//lets say we have 337 eras, which means 7076999663 blocks in total
//This means that we are subtracting 3900944849764118909177207268874798844229425801045364020480003 each time we mine a block
//If every block took 1 second, it would take 200 years to mine all tokens !
miningTarget = miningTarget.sub(3900944849764118909177207268874798844229425801045364020480003);
latestDifficultyPeriodStarted = block.number;
return true;
}
// ----------------------------------------------------------------------------
// A new block epoch to be mined
// ----------------------------------------------------------------------------
function _startNewMiningEpoch() internal {
blockCount = blockCount.add(1);
if ((blockCount.mod(_BLOCKS_PER_ERA) == 0)) {
rewardEra = rewardEra + 1;
}
reAdjustDifficulty();
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = blockhash(block.number - 1);
}
//---------------------VIEW FUNCTIONS-------------------------------------
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns(uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns(uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Current supply
// ------------------------------------------------------------------------
function currentSupply() public view returns(uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns(uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// This is a recent ethereum block hash, used to prevent pre-mining future blocks
// ------------------------------------------------------------------------
function getChallengeNumber() public view returns(bytes32) {
return challengeNumber;
}
// ------------------------------------------------------------------------
// The number of zeroes the digest of the PoW solution requires. Auto adjusts
// ------------------------------------------------------------------------
function getMiningDifficulty() public view returns(uint) {
return _MAXIMUM_TARGET.div(miningTarget);
}
// ------------------------------------------------------------------------
// Returns the mining target
// ------------------------------------------------------------------------
function getMiningTarget() public view returns(uint) {
return miningTarget;
}
// ------------------------------------------------------------------------
// Gets the mining reward
// ------------------------------------------------------------------------
function getMiningReward() public view returns(uint) {
if (tokensBurned >= (2 ** 226)) return 0; //we have burned too many tokens, we can't keep a track of it anymore!
if(tokensBurned<=tokensMined) return 0; //this cannot happen
uint reward_amount = (tokensBurned.sub(tokensMined)).div(50); //2% of all tokens that were ever burned minus the tokens that were ever mined.
return reward_amount;
}
//---------------------EXTERNAL FUNCTIONS----------------------------------
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external payable {
revert();
}
//---------------------OTHER-----------------------------------------------
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns(bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
//help debug mining software
// ------------------------------------------------------------------------
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns(bytes32 digesttest) {
bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce));
return digest;
}
// ------------------------------------------------------------------------
//help debug mining software
// ------------------------------------------------------------------------
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns(bool success) {
bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce));
if (uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
} | ---------------------------------------------------------------------------- Removes account from the whitelist ---------------------------------------------------------------------------- | function removeFromWhitelist(address removeFromWhitelist) public {
whitelist[removeFromWhitelist] = false;
}
| 14,015,813 |
// 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));
}
} | 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;
}
| 1,641,532 |
./partial_match/5/0xdE4c870F36a614E44bd00f987B22F4c4D48718F3/sources/contracts/base/MetawinERC721.sol | [Tx][External][Restricted] Set final provenance record _hash Provenance hash/ | function setProvenance(string calldata _hash) external onlyMetadataProvider {
require(bytes(PROVENANCE).length == 0, "Override not allowed");
require(bytes(_hash).length > 0, "Empty provenance not allowed");
PROVENANCE = _hash;
}
| 16,866,948 |
//Address: 0x5301f1ec2f48f86bbd5291dfd7998a3d733a3245
//Contract name: RentAuction
//Balance: 0 Ether
//Verification Date: 1/28/2018
//Transacion Count: 4
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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 Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
/// @title Interface for contracts conforming to ERC-721: Deed Standard
/// @author William Entriken (https://phor.net), et al.
/// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT)
interface ERC721 {
// COMPLIANCE WITH ERC-165 (DRAFT) /////////////////////////////////////////
/// @dev ERC-165 (draft) interface signature for itself
// bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7
// bytes4(keccak256('supportsInterface(bytes4)'));
/// @dev ERC-165 (draft) interface signature for ERC721
// bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b
// bytes4(keccak256('ownerOf(uint256)')) ^
// bytes4(keccak256('countOfDeeds()')) ^
// bytes4(keccak256('countOfDeedsByOwner(address)')) ^
// bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^
// bytes4(keccak256('approve(address,uint256)')) ^
// bytes4(keccak256('takeOwnership(uint256)'));
/// @notice Query a contract to see if it supports a certain interface
/// @dev Returns `true` the interface is supported and `false` otherwise,
/// returns `true` for INTERFACE_SIGNATURE_ERC165 and
/// INTERFACE_SIGNATURE_ERC721, see ERC-165 for other interface signatures.
function supportsInterface(bytes4 _interfaceID) external pure returns (bool);
// PUBLIC QUERY FUNCTIONS //////////////////////////////////////////////////
/// @notice Find the owner of a deed
/// @param _deedId The identifier for a deed we are inspecting
/// @dev Deeds assigned to zero address are considered destroyed, and
/// queries about them do throw.
/// @return The non-zero address of the owner of deed `_deedId`, or `throw`
/// if deed `_deedId` is not tracked by this contract
function ownerOf(uint256 _deedId) external view returns (address _owner);
/// @notice Count deeds tracked by this contract
/// @return A count of the deeds tracked by this contract, where each one of
/// them has an assigned and queryable owner
function countOfDeeds() public view returns (uint256 _count);
/// @notice Count all deeds assigned to an owner
/// @dev Throws if `_owner` is the zero address, representing destroyed deeds.
/// @param _owner An address where we are interested in deeds owned by them
/// @return The number of deeds owned by `_owner`, possibly zero
function countOfDeedsByOwner(address _owner) public view returns (uint256 _count);
/// @notice Enumerate deeds assigned to an owner
/// @dev Throws if `_index` >= `countOfDeedsByOwner(_owner)` or if
/// `_owner` is the zero address, representing destroyed deeds.
/// @param _owner An address where we are interested in deeds owned by them
/// @param _index A counter between zero and `countOfDeedsByOwner(_owner)`,
/// inclusive
/// @return The identifier for the `_index`th deed assigned to `_owner`,
/// (sort order not specified)
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId);
// TRANSFER MECHANISM //////////////////////////////////////////////////////
/// @dev This event emits when ownership of any deed changes by any
/// mechanism. This event emits when deeds are created (`from` == 0) and
/// destroyed (`to` == 0). Exception: during contract creation, any
/// transfers may occur without emitting `Transfer`.
event Transfer(address indexed from, address indexed to, uint256 indexed deedId);
/// @dev This event emits on any successful call to
/// `approve(address _spender, uint256 _deedId)`. Exception: does not emit
/// if an owner revokes approval (`_to` == 0x0) on a deed with no existing
/// approval.
event Approval(address indexed owner, address indexed approved, uint256 indexed deedId);
/// @notice Approve a new owner to take your deed, or revoke approval by
/// setting the zero address. You may `approve` any number of times while
/// the deed is assigned to you, only the most recent approval matters.
/// @dev Throws if `msg.sender` does not own deed `_deedId` or if `_to` ==
/// `msg.sender`.
/// @param _deedId The deed you are granting ownership of
function approve(address _to, uint256 _deedId) external;
/// @notice Become owner of a deed for which you are currently approved
/// @dev Throws if `msg.sender` is not approved to become the owner of
/// `deedId` or if `msg.sender` currently owns `_deedId`.
/// @param _deedId The deed that is being transferred
function takeOwnership(uint256 _deedId) external;
// SPEC EXTENSIONS /////////////////////////////////////////////////////////
/// @notice Transfer a deed to a new owner.
/// @dev Throws if `msg.sender` does not own deed `_deedId` or if
/// `_to` == 0x0.
/// @param _to The address of the new owner.
/// @param _deedId The deed you are transferring.
function transfer(address _to, uint256 _deedId) external;
}
/// @title Metadata extension to ERC-721 interface
/// @author William Entriken (https://phor.net)
/// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT)
interface ERC721Metadata {
/// @dev ERC-165 (draft) interface signature for ERC721
// bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11
// bytes4(keccak256('name()')) ^
// bytes4(keccak256('symbol()')) ^
// bytes4(keccak256('deedUri(uint256)'));
/// @notice A descriptive name for a collection of deeds managed by this
/// contract
/// @dev Wallets and exchanges MAY display this to the end user.
function name() public pure returns (string _deedName);
/// @notice An abbreviated name for deeds managed by this contract
/// @dev Wallets and exchanges MAY display this to the end user.
function symbol() public pure returns (string _deedSymbol);
/// @notice A distinct URI (RFC 3986) for a given token.
/// @dev If:
/// * The URI is a URL
/// * The URL is accessible
/// * The URL points to a valid JSON file format (ECMA-404 2nd ed.)
/// * The JSON base element is an object
/// then these names of the base element SHALL have special meaning:
/// * "name": A string identifying the item to which `_deedId` grants
/// ownership
/// * "description": A string detailing the item to which `_deedId` grants
/// ownership
/// * "image": A URI pointing to a file of image/* mime type representing
/// the item to which `_deedId` grants ownership
/// Wallets and exchanges MAY display this to the end user.
/// Consider making any images at a width between 320 and 1080 pixels and
/// aspect ratio between 1.91:1 and 4:5 inclusive.
function deedUri(uint256 _deedId) external pure returns (string _uri);
}
/// @dev Implements access control to the DWorld contract.
contract DWorldAccessControl is Claimable, Pausable, CanReclaimToken {
address public cfoAddress;
function DWorldAccessControl() public {
// The creator of the contract is the initial CFO.
cfoAddress = msg.sender;
}
/// @dev Access modifier for CFO-only functionality.
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current contract owner.
/// @param _newCFO The address of the new CFO.
function setCFO(address _newCFO) external onlyOwner {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
}
/// @dev Defines base data structures for DWorld.
contract DWorldBase is DWorldAccessControl {
using SafeMath for uint256;
/// @dev All minted plots (array of plot identifiers). There are
/// 2^16 * 2^16 possible plots (covering the entire world), thus
/// 32 bits are required. This fits in a uint32. Storing
/// the identifiers as uint32 instead of uint256 makes storage
/// cheaper. (The impact of this in mappings is less noticeable,
/// and using uint32 in the mappings below actually *increases*
/// gas cost for minting).
uint32[] public plots;
mapping (uint256 => address) identifierToOwner;
mapping (uint256 => address) identifierToApproved;
mapping (address => uint256) ownershipDeedCount;
/// @dev Event fired when a plot's data are changed. The plot
/// data are not stored in the contract directly, instead the
/// data are logged to the block. This gives significant
/// reductions in gas requirements (~75k for minting with data
/// instead of ~180k). However, it also means plot data are
/// not available from *within* other contracts.
event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl);
/// @notice Get all minted plots.
function getAllPlots() external view returns(uint32[]) {
return plots;
}
/// @dev Represent a 2D coordinate as a single uint.
/// @param x The x-coordinate.
/// @param y The y-coordinate.
function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) {
require(validCoordinate(x, y));
return (y << 16) + x;
}
/// @dev Turn a single uint representation of a coordinate into its x and y parts.
/// @param identifier The uint representation of a coordinate.
function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) {
require(validIdentifier(identifier));
y = identifier >> 16;
x = identifier - (y << 16);
}
/// @dev Test whether the coordinate is valid.
/// @param x The x-part of the coordinate to test.
/// @param y The y-part of the coordinate to test.
function validCoordinate(uint256 x, uint256 y) public pure returns(bool) {
return x < 65536 && y < 65536; // 2^16
}
/// @dev Test whether an identifier is valid.
/// @param identifier The identifier to test.
function validIdentifier(uint256 identifier) public pure returns(bool) {
return identifier < 4294967296; // 2^16 * 2^16
}
/// @dev Set a plot's data.
/// @param identifier The identifier of the plot to set data for.
function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal {
SetData(identifier, name, description, imageUrl, infoUrl);
}
}
/// @dev Holds deed functionality such as approving and transferring. Implements ERC721.
contract DWorldDeed is DWorldBase, ERC721, ERC721Metadata {
/// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata.
function name() public pure returns (string _deedName) {
_deedName = "DWorld Plots";
}
/// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata.
function symbol() public pure returns (string _deedSymbol) {
_deedSymbol = "DWP";
}
/// @dev ERC-165 (draft) interface signature for itself
bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7
bytes4(keccak256('supportsInterface(bytes4)'));
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('countOfDeeds()')) ^
bytes4(keccak256('countOfDeedsByOwner(address)')) ^
bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('takeOwnership(uint256)'));
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('deedUri(uint256)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract.
/// (ERC-165 and ERC-721.)
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return (
(_interfaceID == INTERFACE_SIGNATURE_ERC165)
|| (_interfaceID == INTERFACE_SIGNATURE_ERC721)
|| (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata)
);
}
/// @dev Checks if a given address owns a particular plot.
/// @param _owner The address of the owner to check for.
/// @param _deedId The plot identifier to check for.
function _owns(address _owner, uint256 _deedId) internal view returns (bool) {
return identifierToOwner[_deedId] == _owner;
}
/// @dev Approve a given address to take ownership of a deed.
/// @param _from The address approving taking ownership.
/// @param _to The address to approve taking ownership.
/// @param _deedId The identifier of the deed to give approval for.
function _approve(address _from, address _to, uint256 _deedId) internal {
identifierToApproved[_deedId] = _to;
// Emit event.
Approval(_from, _to, _deedId);
}
/// @dev Checks if a given address has approval to take ownership of a deed.
/// @param _claimant The address of the claimant to check for.
/// @param _deedId The identifier of the deed to check for.
function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) {
return identifierToApproved[_deedId] == _claimant;
}
/// @dev Assigns ownership of a specific deed to an address.
/// @param _from The address to transfer the deed from.
/// @param _to The address to transfer the deed to.
/// @param _deedId The identifier of the deed to transfer.
function _transfer(address _from, address _to, uint256 _deedId) internal {
// The number of plots is capped at 2^16 * 2^16, so this cannot
// be overflowed.
ownershipDeedCount[_to]++;
// Transfer ownership.
identifierToOwner[_deedId] = _to;
// When a new deed is minted, the _from address is 0x0, but we
// do not track deed ownership of 0x0.
if (_from != address(0)) {
ownershipDeedCount[_from]--;
// Clear taking ownership approval.
delete identifierToApproved[_deedId];
}
// Emit the transfer event.
Transfer(_from, _to, _deedId);
}
// ERC 721 implementation
/// @notice Returns the total number of deeds currently in existence.
/// @dev Required for ERC-721 compliance.
function countOfDeeds() public view returns (uint256) {
return plots.length;
}
/// @notice Returns the number of deeds owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function countOfDeedsByOwner(address _owner) public view returns (uint256) {
return ownershipDeedCount[_owner];
}
/// @notice Returns the address currently assigned ownership of a given deed.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _deedId) external view returns (address _owner) {
_owner = identifierToOwner[_deedId];
require(_owner != address(0));
}
/// @notice Approve a given address to take ownership of a deed.
/// @param _to The address to approve taking owernship.
/// @param _deedId The identifier of the deed to give approval for.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
approveMultiple(_to, _deedIds);
}
/// @notice Approve a given address to take ownership of multiple deeds.
/// @param _to The address to approve taking ownership.
/// @param _deedIds The identifiers of the deeds to give approval for.
function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Ensure the sender is not approving themselves.
require(msg.sender != _to);
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
// Require the sender is the owner of the deed.
require(_owns(msg.sender, _deedId));
// Perform the approval.
_approve(msg.sender, _to, _deedId);
}
}
/// @notice Transfer a deed to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your
/// deed may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _deedId The identifier of the deed to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
transferMultiple(_to, _deedIds);
}
/// @notice Transfers multiple deeds to another address. If transferring to
/// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721,
/// or your deeds may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _deedIds The identifiers of the deeds to transfer.
function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
// One can only transfer their own plots.
require(_owns(msg.sender, _deedId));
// Transfer ownership
_transfer(msg.sender, _to, _deedId);
}
}
/// @notice Transfer a deed owned by another address, for which the calling
/// address has previously been granted transfer approval by the owner.
/// @param _deedId The identifier of the deed to be transferred.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
takeOwnershipMultiple(_deedIds);
}
/// @notice Transfer multiple deeds owned by another address, for which the
/// calling address has previously been granted transfer approval by the owner.
/// @param _deedIds The identifier of the deed to be transferred.
function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused {
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
address _from = identifierToOwner[_deedId];
// Check for transfer approval
require(_approvedFor(msg.sender, _deedId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, msg.sender, _deedId);
}
}
/// @notice Returns a list of all deed identifiers assigned to an address.
/// @param _owner The owner whose deeds we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. It's very
/// expensive and is not supported in contract-to-contract calls as it returns
/// a dynamic array (only supported for web3 calls).
function deedsOfOwner(address _owner) external view returns(uint256[]) {
uint256 deedCount = countOfDeedsByOwner(_owner);
if (deedCount == 0) {
// Return an empty array.
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](deedCount);
uint256 totalDeeds = countOfDeeds();
uint256 resultIndex = 0;
for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {
uint256 identifier = plots[deedNumber];
if (identifierToOwner[identifier] == _owner) {
result[resultIndex] = identifier;
resultIndex++;
}
}
return result;
}
}
/// @notice Returns a deed identifier of the owner at the given index.
/// @param _owner The address of the owner we want to get a deed for.
/// @param _index The index of the deed we want.
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
// The index should be valid.
require(_index < countOfDeedsByOwner(_owner));
// Loop through all plots, accounting the number of plots of the owner we've seen.
uint256 seen = 0;
uint256 totalDeeds = countOfDeeds();
for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {
uint256 identifier = plots[deedNumber];
if (identifierToOwner[identifier] == _owner) {
if (seen == _index) {
return identifier;
}
seen++;
}
}
}
/// @notice Returns an (off-chain) metadata url for the given deed.
/// @param _deedId The identifier of the deed to get the metadata
/// url for.
/// @dev Implementation of optional ERC-721 functionality.
function deedUri(uint256 _deedId) external pure returns (string uri) {
require(validIdentifier(_deedId));
var (x, y) = identifierToCoordinate(_deedId);
// Maximum coordinate length in decimals is 5 (65535)
uri = "https://dworld.io/plot/xxxxx/xxxxx";
bytes memory _uri = bytes(uri);
for (uint256 i = 0; i < 5; i++) {
_uri[27 - i] = byte(48 + (x / 10 ** i) % 10);
_uri[33 - i] = byte(48 + (y / 10 ** i) % 10);
}
}
}
/// @dev Implements renting functionality.
contract DWorldRenting is DWorldDeed {
event Rent(address indexed renter, uint256 indexed deedId, uint256 rentPeriodEndTimestamp, uint256 rentPeriod);
mapping (uint256 => address) identifierToRenter;
mapping (uint256 => uint256) identifierToRentPeriodEndTimestamp;
/// @dev Checks if a given address rents a particular plot.
/// @param _renter The address of the renter to check for.
/// @param _deedId The plot identifier to check for.
function _rents(address _renter, uint256 _deedId) internal view returns (bool) {
return identifierToRenter[_deedId] == _renter && identifierToRentPeriodEndTimestamp[_deedId] >= now;
}
/// @dev Rent out a deed to an address.
/// @param _to The address to rent the deed out to.
/// @param _rentPeriod The rent period in seconds.
/// @param _deedId The identifier of the deed to rent out.
function _rentOut(address _to, uint256 _rentPeriod, uint256 _deedId) internal {
// Set the renter and rent period end timestamp
uint256 rentPeriodEndTimestamp = now.add(_rentPeriod);
identifierToRenter[_deedId] = _to;
identifierToRentPeriodEndTimestamp[_deedId] = rentPeriodEndTimestamp;
Rent(_to, _deedId, rentPeriodEndTimestamp, _rentPeriod);
}
/// @notice Rents a plot out to another address.
/// @param _to The address of the renter, can be a user or contract.
/// @param _rentPeriod The rent time period in seconds.
/// @param _deedId The identifier of the plot to rent out.
function rentOut(address _to, uint256 _rentPeriod, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
rentOutMultiple(_to, _rentPeriod, _deedIds);
}
/// @notice Rents multiple plots out to another address.
/// @param _to The address of the renter, can be a user or contract.
/// @param _rentPeriod The rent time period in seconds.
/// @param _deedIds The identifiers of the plots to rent out.
function rentOutMultiple(address _to, uint256 _rentPeriod, uint256[] _deedIds) public whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
require(validIdentifier(_deedId));
// There should not be an active renter.
require(identifierToRentPeriodEndTimestamp[_deedId] < now);
// One can only rent out their own plots.
require(_owns(msg.sender, _deedId));
_rentOut(_to, _rentPeriod, _deedId);
}
}
/// @notice Returns the address of the currently assigned renter and
/// end time of the rent period of a given plot.
/// @param _deedId The identifier of the deed to get the renter and
/// rent period for.
function renterOf(uint256 _deedId) external view returns (address _renter, uint256 _rentPeriodEndTimestamp) {
require(validIdentifier(_deedId));
if (identifierToRentPeriodEndTimestamp[_deedId] < now) {
// There is no active renter
_renter = address(0);
_rentPeriodEndTimestamp = 0;
} else {
_renter = identifierToRenter[_deedId];
_rentPeriodEndTimestamp = identifierToRentPeriodEndTimestamp[_deedId];
}
}
}
/// @title The internal clock auction functionality.
/// Inspired by CryptoKitties' clock auction
contract ClockAuctionBase {
// Address of the ERC721 contract this auction is linked to.
ERC721 public deedContract;
// Fee per successful auction in 1/1000th of a percentage.
uint256 public fee;
// Total amount of ether yet to be paid to auction beneficiaries.
uint256 public outstandingEther = 0 ether;
// Amount of ether yet to be paid per beneficiary.
mapping (address => uint256) public addressToEtherOwed;
/// @dev Represents a deed auction.
/// Care has been taken to ensure the auction fits in
/// two 256-bit words.
struct Auction {
address seller;
uint128 startPrice;
uint128 endPrice;
uint64 duration;
uint64 startedAt;
}
mapping (uint256 => Auction) identifierToAuction;
// Events
event AuctionCreated(address indexed seller, uint256 indexed deedId, uint256 startPrice, uint256 endPrice, uint256 duration);
event AuctionSuccessful(address indexed buyer, uint256 indexed deedId, uint256 totalPrice);
event AuctionCancelled(uint256 indexed deedId);
/// @dev Modifier to check whether the value can be stored in a 64 bit uint.
modifier fitsIn64Bits(uint256 _value) {
require (_value == uint256(uint64(_value)));
_;
}
/// @dev Modifier to check whether the value can be stored in a 128 bit uint.
modifier fitsIn128Bits(uint256 _value) {
require (_value == uint256(uint128(_value)));
_;
}
function ClockAuctionBase(address _deedContractAddress, uint256 _fee) public {
deedContract = ERC721(_deedContractAddress);
// Contract must indicate support for ERC721 through its interface signature.
require(deedContract.supportsInterface(0xda671b9b));
// Fee must be between 0 and 100%.
require(0 <= _fee && _fee <= 100000);
fee = _fee;
}
/// @dev Checks whether the given auction is active.
/// @param auction The auction to check for activity.
function _activeAuction(Auction storage auction) internal view returns (bool) {
return auction.startedAt > 0;
}
/// @dev Put the deed into escrow, thereby taking ownership of it.
/// @param _deedId The identifier of the deed to place into escrow.
function _escrow(uint256 _deedId) internal {
// Throws if the transfer fails
deedContract.takeOwnership(_deedId);
}
/// @dev Create the auction.
/// @param _deedId The identifier of the deed to create the auction for.
/// @param auction The auction to create.
function _createAuction(uint256 _deedId, Auction auction) internal {
// Add the auction to the auction mapping.
identifierToAuction[_deedId] = auction;
// Trigger auction created event.
AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration);
}
/// @dev Bid on an auction.
/// @param _buyer The address of the buyer.
/// @param _value The value sent by the sender (in ether).
/// @param _deedId The identifier of the deed to bid on.
function _bid(address _buyer, uint256 _value, uint256 _deedId) internal {
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active.
require(_activeAuction(auction));
// Calculate the auction's current price.
uint256 price = _currentPrice(auction);
// Make sure enough funds were sent.
require(_value >= price);
address seller = auction.seller;
if (price > 0) {
uint256 totalFee = _calculateFee(price);
uint256 proceeds = price - totalFee;
// Assign the proceeds to the seller.
// We do not send the proceeds directly, as to prevent
// malicious sellers from denying auctions (and burning
// the buyer's gas).
_assignProceeds(seller, proceeds);
}
AuctionSuccessful(_buyer, _deedId, price);
// The bid was won!
_winBid(seller, _buyer, _deedId, price);
// Remove the auction (we do this at the end, as
// winBid might require some additional information
// that will be removed when _removeAuction is
// called. As we do not transfer funds here, we do
// not have to worry about re-entry attacks.
_removeAuction(_deedId);
}
/// @dev Perform the bid win logic (in this case: transfer the deed).
/// @param _seller The address of the seller.
/// @param _winner The address of the winner.
/// @param _deedId The identifier of the deed.
/// @param _price The price the auction was bought at.
function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal {
_transfer(_winner, _deedId);
}
/// @dev Cancel an auction.
/// @param _deedId The identifier of the deed for which the auction should be cancelled.
/// @param auction The auction to cancel.
function _cancelAuction(uint256 _deedId, Auction auction) internal {
// Remove the auction
_removeAuction(_deedId);
// Transfer the deed back to the seller
_transfer(auction.seller, _deedId);
// Trigger auction cancelled event.
AuctionCancelled(_deedId);
}
/// @dev Remove an auction.
/// @param _deedId The identifier of the deed for which the auction should be removed.
function _removeAuction(uint256 _deedId) internal {
delete identifierToAuction[_deedId];
}
/// @dev Transfer a deed owned by this contract to another address.
/// @param _to The address to transfer the deed to.
/// @param _deedId The identifier of the deed.
function _transfer(address _to, uint256 _deedId) internal {
// Throws if the transfer fails
deedContract.transfer(_to, _deedId);
}
/// @dev Assign proceeds to an address.
/// @param _to The address to assign proceeds to.
/// @param _value The proceeds to assign.
function _assignProceeds(address _to, uint256 _value) internal {
outstandingEther += _value;
addressToEtherOwed[_to] += _value;
}
/// @dev Calculate the current price of an auction.
function _currentPrice(Auction storage _auction) internal view returns (uint256) {
require(now >= _auction.startedAt);
uint256 secondsPassed = now - _auction.startedAt;
if (secondsPassed >= _auction.duration) {
return _auction.endPrice;
} else {
// Negative if the end price is higher than the start price!
int256 totalPriceChange = int256(_auction.endPrice) - int256(_auction.startPrice);
// Calculate the current price based on the total change over the entire
// auction duration, and the amount of time passed since the start of the
// auction.
int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration);
// Calculate the final price. Note this once again
// is representable by a uint256, as the price can
// never be negative.
int256 price = int256(_auction.startPrice) + currentPriceChange;
// This never throws.
assert(price >= 0);
return uint256(price);
}
}
/// @dev Calculate the fee for a given price.
/// @param _price The price to calculate the fee for.
function _calculateFee(uint256 _price) internal view returns (uint256) {
// _price is guaranteed to fit in a uint128 due to the createAuction entry
// modifiers, so this cannot overflow.
return _price * fee / 100000;
}
}
contract ClockAuction is ClockAuctionBase, Pausable {
function ClockAuction(address _deedContractAddress, uint256 _fee)
ClockAuctionBase(_deedContractAddress, _fee)
public
{}
/// @notice Update the auction fee.
/// @param _fee The new fee.
function setFee(uint256 _fee) external onlyOwner {
require(0 <= _fee && _fee <= 100000);
fee = _fee;
}
/// @notice Get the auction for the given deed.
/// @param _deedId The identifier of the deed to get the auction for.
/// @dev Throws if there is no auction for the given deed.
function getAuction(uint256 _deedId) external view returns (
address seller,
uint256 startPrice,
uint256 endPrice,
uint256 duration,
uint256 startedAt
)
{
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active
require(_activeAuction(auction));
return (
auction.seller,
auction.startPrice,
auction.endPrice,
auction.duration,
auction.startedAt
);
}
/// @notice Create an auction for a given deed.
/// Must previously have been given approval to take ownership of the deed.
/// @param _deedId The identifier of the deed to create an auction for.
/// @param _startPrice The starting price of the auction.
/// @param _endPrice The ending price of the auction.
/// @param _duration The duration in seconds of the dynamic pricing part of the auction.
function createAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration)
public
fitsIn128Bits(_startPrice)
fitsIn128Bits(_endPrice)
fitsIn64Bits(_duration)
whenNotPaused
{
// Get the owner of the deed to be auctioned
address deedOwner = deedContract.ownerOf(_deedId);
// Caller must either be the deed contract or the owner of the deed
// to prevent abuse.
require(
msg.sender == address(deedContract) ||
msg.sender == deedOwner
);
// The duration of the auction must be at least 60 seconds.
require(_duration >= 60);
// Throws if placing the deed in escrow fails (the contract requires
// transfer approval prior to creating the auction).
_escrow(_deedId);
// Auction struct
Auction memory auction = Auction(
deedOwner,
uint128(_startPrice),
uint128(_endPrice),
uint64(_duration),
uint64(now)
);
_createAuction(_deedId, auction);
}
/// @notice Cancel an auction
/// @param _deedId The identifier of the deed to cancel the auction for.
function cancelAuction(uint256 _deedId) external whenNotPaused {
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active.
require(_activeAuction(auction));
// The auction can only be cancelled by the seller
require(msg.sender == auction.seller);
_cancelAuction(_deedId, auction);
}
/// @notice Bid on an auction.
/// @param _deedId The identifier of the deed to bid on.
function bid(uint256 _deedId) external payable whenNotPaused {
// Throws if the bid does not succeed.
_bid(msg.sender, msg.value, _deedId);
}
/// @dev Returns the current price of an auction.
/// @param _deedId The identifier of the deed to get the currency price for.
function getCurrentPrice(uint256 _deedId) external view returns (uint256) {
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active.
require(_activeAuction(auction));
return _currentPrice(auction);
}
/// @notice Withdraw ether owed to a beneficiary.
/// @param beneficiary The address to withdraw the auction balance for.
function withdrawAuctionBalance(address beneficiary) external {
// The sender must either be the beneficiary or the core deed contract.
require(
msg.sender == beneficiary ||
msg.sender == address(deedContract)
);
uint256 etherOwed = addressToEtherOwed[beneficiary];
// Ensure ether is owed to the beneficiary.
require(etherOwed > 0);
// Set ether owed to 0
delete addressToEtherOwed[beneficiary];
// Subtract from total outstanding balance. etherOwed is guaranteed
// to be less than or equal to outstandingEther, so this cannot
// underflow.
outstandingEther -= etherOwed;
// Transfer ether owed to the beneficiary (not susceptible to re-entry
// attack, as the ether owed is set to 0 before the transfer takes place).
beneficiary.transfer(etherOwed);
}
/// @notice Withdraw (unowed) contract balance.
function withdrawFreeBalance() external {
// Calculate the free (unowed) balance. This never underflows, as
// outstandingEther is guaranteed to be less than or equal to the
// contract balance.
uint256 freeBalance = this.balance - outstandingEther;
address deedContractAddress = address(deedContract);
require(
msg.sender == owner ||
msg.sender == deedContractAddress
);
deedContractAddress.transfer(freeBalance);
}
}
contract RentAuction is ClockAuction {
function RentAuction(address _deedContractAddress, uint256 _fee) ClockAuction(_deedContractAddress, _fee) public {}
/// @dev Allows other contracts to check whether this is the expected contract.
bool public isRentAuction = true;
mapping (uint256 => uint256) public identifierToRentPeriod;
/// @notice Create an auction for a given deed. Be careful when calling
/// createAuction for a RentAuction, that this overloaded function (including
/// the _rentPeriod parameter) is used. Otherwise the rent period defaults to
/// a week.
/// Must previously have been given approval to take ownership of the deed.
/// @param _deedId The identifier of the deed to create an auction for.
/// @param _startPrice The starting price of the auction.
/// @param _endPrice The ending price of the auction.
/// @param _duration The duration in seconds of the dynamic pricing part of the auction.
/// @param _rentPeriod The rent period in seconds being auctioned.
function createAuction(
uint256 _deedId,
uint256 _startPrice,
uint256 _endPrice,
uint256 _duration,
uint256 _rentPeriod
)
external
{
// Require the rent period to be at least one hour.
require(_rentPeriod >= 3600);
// Require there to be no active renter.
DWorldRenting dWorldRentingContract = DWorldRenting(deedContract);
var (renter,) = dWorldRentingContract.renterOf(_deedId);
require(renter == address(0));
// Set the rent period.
identifierToRentPeriod[_deedId] = _rentPeriod;
// Throws (reverts) if creating the auction fails.
createAuction(_deedId, _startPrice, _endPrice, _duration);
}
/// @dev Perform the bid win logic (in this case: give renter status to the winner).
/// @param _seller The address of the seller.
/// @param _winner The address of the winner.
/// @param _deedId The identifier of the deed.
/// @param _price The price the auction was bought at.
function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal {
DWorldRenting dWorldRentingContract = DWorldRenting(deedContract);
uint256 rentPeriod = identifierToRentPeriod[_deedId];
if (rentPeriod == 0) {
rentPeriod = 604800; // 1 week by default
}
// Rent the deed out to the winner.
dWorldRentingContract.rentOut(_winner, identifierToRentPeriod[_deedId], _deedId);
// Transfer the deed back to the seller.
_transfer(_seller, _deedId);
}
/// @dev Remove an auction.
/// @param _deedId The identifier of the deed for which the auction should be removed.
function _removeAuction(uint256 _deedId) internal {
delete identifierToAuction[_deedId];
delete identifierToRentPeriod[_deedId];
}
}
| The creator of the contract is the initial CFO. | function DWorldAccessControl() public {
cfoAddress = msg.sender;
}
| 12,995,679 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../utils/timelock/QuadraticTokenTimelock.sol";
interface IVotingToken is IERC20 {
function delegate(address delegatee) external;
}
/// @title a timelock for tokens allowing for bulk delegation
/// @author Fei Protocol
/// @notice allows the timelocked tokens to be delegated by the beneficiary while locked
contract QuadraticTimelockedDelegator is QuadraticTokenTimelock {
/// @notice QuadraticTimelockedDelegator constructor
/// @param _token the token address
/// @param _beneficiary admin, and timelock beneficiary
/// @param _duration duration of the token timelock window
/// @param _cliff the seconds before first claim is allowed
/// @param _clawbackAdmin the address which can trigger a clawback
/// @param _startTime the unix epoch for starting timelock. Use 0 to start at deployment
constructor(
address _token,
address _beneficiary,
uint256 _duration,
uint256 _cliff,
address _clawbackAdmin,
uint256 _startTime
) QuadraticTokenTimelock(_beneficiary, _duration, _token, _cliff, _clawbackAdmin, _startTime) {}
/// @notice accept beneficiary role over timelocked TRIBE
function acceptBeneficiary() public override {
_setBeneficiary(msg.sender);
}
/// @notice delegate all held TRIBE to the `to` address
function delegate(address to) public onlyBeneficiary {
IVotingToken(address(lockedToken)).delegate(to);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./TokenTimelock.sol";
contract QuadraticTokenTimelock is TokenTimelock {
constructor (
address _beneficiary,
uint256 _duration,
address _lockedToken,
uint256 _cliffDuration,
address _clawbackAdmin,
uint256 _startTime
) TokenTimelock(
_beneficiary,
_duration,
_cliffDuration,
_lockedToken,
_clawbackAdmin
) {
if (_startTime != 0) {
startTime = _startTime;
}
}
function _proportionAvailable(
uint256 initialBalance,
uint256 elapsed,
uint256 duration
) internal pure override returns (uint256) {
return initialBalance * elapsed * elapsed / duration / duration;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
// Inspired by OpenZeppelin TokenTimelock contract
// Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/TokenTimelock.sol
import "../Timed.sol";
import "./ITokenTimelock.sol";
abstract contract TokenTimelock is ITokenTimelock, Timed {
/// @notice ERC20 basic token contract being held in timelock
IERC20 public override lockedToken;
/// @notice beneficiary of tokens after they are released
address public override beneficiary;
/// @notice pending beneficiary appointed by current beneficiary
address public override pendingBeneficiary;
/// @notice initial balance of lockedToken
uint256 public override initialBalance;
uint256 internal lastBalance;
/// @notice number of seconds before releasing is allowed
uint256 public immutable cliffSeconds;
address public immutable clawbackAdmin;
constructor(
address _beneficiary,
uint256 _duration,
uint256 _cliffSeconds,
address _lockedToken,
address _clawbackAdmin
) Timed(_duration) {
require(_duration != 0, "TokenTimelock: duration is 0");
require(
_beneficiary != address(0),
"TokenTimelock: Beneficiary must not be 0 address"
);
beneficiary = _beneficiary;
_initTimed();
_setLockedToken(_lockedToken);
cliffSeconds = _cliffSeconds;
clawbackAdmin = _clawbackAdmin;
}
// Prevents incoming LP tokens from messing up calculations
modifier balanceCheck() {
if (totalToken() > lastBalance) {
uint256 delta = totalToken() - lastBalance;
initialBalance = initialBalance + delta;
}
_;
lastBalance = totalToken();
}
modifier onlyBeneficiary() {
require(
msg.sender == beneficiary,
"TokenTimelock: Caller is not a beneficiary"
);
_;
}
/// @notice releases `amount` unlocked tokens to address `to`
function release(address to, uint256 amount) external override onlyBeneficiary balanceCheck {
require(amount != 0, "TokenTimelock: no amount desired");
require(passedCliff(), "TokenTimelock: Cliff not passed");
uint256 available = availableForRelease();
require(amount <= available, "TokenTimelock: not enough released tokens");
_release(to, amount);
}
/// @notice releases maximum unlocked tokens to address `to`
function releaseMax(address to) external override onlyBeneficiary balanceCheck {
require(passedCliff(), "TokenTimelock: Cliff not passed");
_release(to, availableForRelease());
}
/// @notice the total amount of tokens held by timelock
function totalToken() public view override virtual returns (uint256) {
return lockedToken.balanceOf(address(this));
}
/// @notice amount of tokens released to beneficiary
function alreadyReleasedAmount() public view override returns (uint256) {
return initialBalance - totalToken();
}
/// @notice amount of held tokens unlocked and available for release
function availableForRelease() public view override returns (uint256) {
uint256 elapsed = timeSinceStart();
uint256 totalAvailable = _proportionAvailable(initialBalance, elapsed, duration);
uint256 netAvailable = totalAvailable - alreadyReleasedAmount();
return netAvailable;
}
/// @notice current beneficiary can appoint new beneficiary, which must be accepted
function setPendingBeneficiary(address _pendingBeneficiary)
public
override
onlyBeneficiary
{
pendingBeneficiary = _pendingBeneficiary;
emit PendingBeneficiaryUpdate(_pendingBeneficiary);
}
/// @notice pending beneficiary accepts new beneficiary
function acceptBeneficiary() public override virtual {
_setBeneficiary(msg.sender);
}
function clawback() public balanceCheck {
require(msg.sender == clawbackAdmin, "TokenTimelock: Only clawbackAdmin");
if (passedCliff()) {
_release(beneficiary, availableForRelease());
}
_release(clawbackAdmin, totalToken());
}
function passedCliff() public view returns (bool) {
return timeSinceStart() >= cliffSeconds;
}
function _proportionAvailable(uint256 initialBalance, uint256 elapsed, uint256 duration) internal pure virtual returns (uint256);
function _setBeneficiary(address newBeneficiary) internal {
require(
newBeneficiary == pendingBeneficiary,
"TokenTimelock: Caller is not pending beneficiary"
);
beneficiary = newBeneficiary;
emit BeneficiaryUpdate(newBeneficiary);
pendingBeneficiary = address(0);
}
function _setLockedToken(address tokenAddress) internal {
lockedToken = IERC20(tokenAddress);
}
function _release(address to, uint256 amount) internal {
lockedToken.transfer(to, amount);
emit Release(beneficiary, to, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title an abstract contract for timed events
/// @author Fei Protocol
abstract contract Timed {
/// @notice the start timestamp of the timed period
uint256 public startTime;
/// @notice the duration of the timed period
uint256 public duration;
event DurationUpdate(uint256 oldDuration, uint256 newDuration);
event TimerReset(uint256 startTime);
constructor(uint256 _duration) {
_setDuration(_duration);
}
modifier duringTime() {
require(isTimeStarted(), "Timed: time not started");
require(!isTimeEnded(), "Timed: time ended");
_;
}
modifier afterTime() {
require(isTimeEnded(), "Timed: time not ended");
_;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint256) {
return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d]
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timeSinceStart() public view returns (uint256) {
if (!isTimeStarted()) {
return 0; // uninitialized
}
uint256 _duration = duration;
uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime
return timePassed > _duration ? _duration : timePassed;
}
function isTimeStarted() public view returns (bool) {
return startTime != 0;
}
function _initTimed() internal {
startTime = block.timestamp;
emit TimerReset(block.timestamp);
}
function _setDuration(uint256 newDuration) internal {
require(newDuration != 0, "Timed: zero duration");
uint256 oldDuration = duration;
duration = newDuration;
emit DurationUpdate(oldDuration, newDuration);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title TokenTimelock interface
/// @author Fei Protocol
interface ITokenTimelock {
// ----------- Events -----------
event Release(address indexed _beneficiary, address indexed _recipient, uint256 _amount);
event BeneficiaryUpdate(address indexed _beneficiary);
event PendingBeneficiaryUpdate(address indexed _pendingBeneficiary);
// ----------- State changing api -----------
function release(address to, uint256 amount) external;
function releaseMax(address to) external;
function setPendingBeneficiary(address _pendingBeneficiary) external;
function acceptBeneficiary() external;
// ----------- Getters -----------
function lockedToken() external view returns (IERC20);
function beneficiary() external view returns (address);
function pendingBeneficiary() external view returns (address);
function initialBalance() external view returns (uint256);
function availableForRelease() external view returns (uint256);
function totalToken() external view returns(uint256);
function alreadyReleasedAmount() external view returns (uint256);
}
// 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);
} | amount of held tokens unlocked and available for release | function availableForRelease() public view override returns (uint256) {
uint256 elapsed = timeSinceStart();
uint256 totalAvailable = _proportionAvailable(initialBalance, elapsed, duration);
uint256 netAvailable = totalAvailable - alreadyReleasedAmount();
return netAvailable;
}
| 1,245,655 |
pragma solidity ^0.4.21;
import "zeppelin-solidity/contracts/access/rbac/RBAC.sol";
interface ITeamNFT {
function _createTeam(
uint256 _id,
string memory _TeamUrl,
string memory _name,
address _teamOwner
) public returns (uint256);
function mintTeamToken(
address teamOwner,
string name,
string metadata //isTeamOwner(teamOwner)
) public returns (uint256);
function evaluateTeam(uint256 teamId, address projectAddress) public;
function getTeamCount() public view returns (uint256 teamCount);
function transferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
);
function getTeamById(uint256 teamId)
public
view
returns (
uint256 id,
address teamOwner,
string name,
string TeamUrl,
bool exists
);
}
interface IWeekNFT {
/// wrapper on minting new 721
function mint721(
address _teamContract,
uint256 _teamTokenId,
address userAddress
) public returns (uint256);
function assignNFTToTeam(
address _teamContract,
uint256 _teamTokenId,
uint256 _weekTokenId,
address userAddress
) public;
function placeBid(
uint256 weekTokenId,
address bidder,
uint256 price
) public;
function transferWeekNFTOnBid(
uint256 weekTokenId,
address from,
address to
);
function getWeekById(uint256 weekId)
public
view
returns (
uint256 id,
uint256 teamId,
address weekOwner,
bool exists,
string WeekUrl,
uint256 price,
uint256 WeekNo,
uint256 Year
);
}
contract BundleBond is RBAC {
ITeamNFT TEAM;
IWeekNFT WEEK;
address TeamContractAddress;
address weekContractAddress;
mapping(address => Admin) AdminList;
mapping(address => TeamOwner) TeamOwnerList;
mapping(uint256 => Project) projectList;
mapping(uint256 => Offer) offerList;
uint256 lastProjectId;
uint256 lastOfferId;
struct Project {
string name;
address projectAddress;
address projectOwner;
}
struct Offer {
uint256 WeekId;
address fromAddress;
address ownerAddress;
bool accepted;
}
modifier onlyAdmin() {
hasRole(msg.sender, "Admin");
_;
}
modifier onlyTeamOwner() {
hasRole(msg.sender, "TEAM_OWNER");
_;
}
constructor(address _team, address _week) public {
TEAM = ITeamNFT(_team);
WEEK = IWeekNFT(_week);
TeamContractAddress = _team;
weekContractAddress = _team;
lastProjectId = 0;
lastOfferId=0;
addRole(msg.sender, "Admin");
}
struct Admin {
string name;
bool exists;
}
struct TeamOwner {
string name;
bool exists;
}
function isAdmin()
public
returns (bool)
{
return hasRole(msg.sender, "Admin");
}
function addAdmin(string _adminName, address _adminAddress)
{
Admin storage t = AdminList[_adminAddress];
if (!t.exists) {
AdminList[_adminAddress] = Admin({
exists: true,
name: _adminName
});
addRole(_adminAddress, "Admin");
}
}
function editAdminName(string _adminName, address _adminAddress)
{
Admin storage t = AdminList[_adminAddress];
if (t.exists) {
AdminList[_adminAddress].name = _adminName;
}
}
function getAdminName(address _adminAddress)
view
returns (string){
Admin storage admin = AdminList[_adminAddress];
if (admin.exists) {
return AdminList[_adminAddress].name;
}
return "";
}
function isTeamOwner()
public
returns(bool)
{
return hasRole(msg.sender, "TEAM_OWNER");
}
function addTeamOwner(string _teamOwnerName, address _teamOwnerAddress)
{
TeamOwner storage t = TeamOwnerList[_teamOwnerAddress];
if (!t.exists) {
TeamOwnerList[_teamOwnerAddress] = TeamOwner({
exists: true,
name: _teamOwnerName
});
addRole(_teamOwnerAddress, "TEAM_OWNER");
}
}
function editTeamOwnerName(string _teamOwnerName, address _teamOwnerAddress)
{
TeamOwner storage t = TeamOwnerList[_teamOwnerAddress];
if (t.exists) {
TeamOwnerList[_teamOwnerAddress].name = _teamOwnerName;
}
}
function getTeamOwnerName(address _teamOwnerAddress)
view
returns (string){
TeamOwner storage t = TeamOwnerList[_teamOwnerAddress];
if (t.exists) {
return TeamOwnerList[_teamOwnerAddress].name;
}
return "";
}
function addTeam(
address teamOwner,
string teamName,
string metadata)
returns(uint256)
{
return TEAM.mintTeamToken(teamOwner, teamName, metadata);
}
function getTeamCount()
public
view
returns (uint256 teamCount)
{
return TEAM.getTeamCount();
}
function getTeamById(uint256 teamId)
public
view
returns (
uint256 id,
address teamOwner,
string name,
string TeamUrl,
bool exists
)
{
return TEAM.getTeamById(teamId);
}
function addWeek(uint256 _teamTokenId, address teamOwnerAddress) {
WEEK.mint721(TeamContractAddress, _teamTokenId, teamOwnerAddress);
}
function getWeekById(uint256 weekId)
public
view
returns (
uint256 id,
uint256 teamId,
address weekOwner,
bool exists,
string WeekUrl,
uint256 price,
uint256 WeekNo,
uint256 Year
)
{
return WEEK.getWeekById(weekId);
}
function purchaseWeekOfTeam(
uint256 teamTokenId,
uint256 weekTokenId)
public
payable
{
//price to team
//NFT update (set owner)
var ( teamId,teamOwner, name, TeamUrl, teamExists)=getTeamById(teamTokenId);
var ( weekId, weekTeamId, weekOwner, weekExists, WeekUrl, price,WeekNo,Year)=getWeekById(teamTokenId);
require(msg.value >= (price), "The value is " );
uint256 amountToRefund = msg.value - price;
msg.sender.transfer(amountToRefund);
weekOwner.transfer(price);
sellWeekNFT(teamTokenId, weekTokenId,msg.sender );
}
function sellWeekNFT(
uint256 teamTokenId,
uint256 weekTokenId,
address to
)
{
TEAM.transferChild(teamTokenId, to, weekContractAddress, weekTokenId);
}
function makeAnOffer(
uint256 weekTokenId)
public
payable
{
//price to contract
//offer map update
var ( weekId, teamId, weekOwner, exists, WeekUrl, price,WeekNo,Year)=getWeekById(weekTokenId);
require(msg.value >= (price), "The value is " );
uint256 amountToRefund = msg.value - price;
msg.sender.transfer(amountToRefund);
Offer storage o = offerList[lastOfferId];
offerList[lastOfferId] = Offer({
WeekId:weekTokenId,
fromAddress:msg.sender,
ownerAddress:weekOwner,
accepted:false
});
lastOfferId=lastOfferId+1;
}
function acceptAnOffer(uint256 offerID)
public
payable
{
//price to prev owner
//change offer status
//call transferWeekNFTOnBid
var ( weekId, teamId, weekOwner, exists, WeekUrl, price,WeekNo,Year)=getWeekById(offerList[offerID].WeekId);
offerList[offerID].ownerAddress.transfer(price);
offerList[offerID].accepted = true;
transferWeekNFTOnBid( offerList[offerID].WeekId,offerList[offerID].fromAddress, offerList[offerID].ownerAddress );
}
function rejectAnOffer(uint256 offerID)
public
payable
{
var ( weekId, teamId, weekOwner, exists, WeekUrl, price,WeekNo,Year)=getWeekById(offerList[offerID].WeekId);
offerList[offerID].fromTransfer.transfer(price);
}
function transferWeekNFTOnBid(
uint256 weekTokenId,
address from,
address to
) {
WEEK.transferWeekNFTOnBid(weekTokenId,from,to);
}
function placeBidOnWeekNFT(
uint256 weekTokenId,
address bidder,
uint256 price
) public {
WEEK.placeBid(weekTokenId, bidder, price);
}
function AddProjectToResume(string _name, address _projectAddress)
public
{
projectList[lastProjectId] = Project({
name: _name,
projectAddress:_projectAddress,
projectOwner:msg.sender
});
lastProjectId=lastProjectId+1;
}
}
| price to prev ownerchange offer statuscall transferWeekNFTOnBid | function acceptAnOffer(uint256 offerID)
public
payable
{
var ( weekId, teamId, weekOwner, exists, WeekUrl, price,WeekNo,Year)=getWeekById(offerList[offerID].WeekId);
offerList[offerID].ownerAddress.transfer(price);
offerList[offerID].accepted = true;
transferWeekNFTOnBid( offerList[offerID].WeekId,offerList[offerID].fromAddress, offerList[offerID].ownerAddress );
}
| 6,460,584 |
/*
Copyright 2019 RigoBlock, Rigo Investment Sagl.
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.4;
pragma experimental ABIEncoderV2;
// https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function approve(address _spender, uint _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
interface WETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
interface Oracle {
function getExpectedRate(
ERC20 src,
ERC20 dest,
uint srcQty,
bool usePermissionless)
external
view
returns (uint expectedRate, uint slippageRate);
}
contract TotlePrimary {
address public tokenTransferProxy;
}
/// @title Totle Primary adapter - A helper contract for the Totle exchange aggregator.
/// @author Gabriele Rigo - <[email protected]>
// solhint-disable-next-line
contract ATotlePrimary {
WETH weth;
struct Trade {
bool isSell;
address tokenAddress;
uint256 tokenAmount;
bool optionalTrade;
uint256 minimumExchangeRate;
uint256 minimumAcceptableTokenAmount;
Order[] orders;
}
struct Order {
address exchangeHandler;
bytes genericPayload;
}
struct TradeFlag {
bool ignoreTrade;
bool[] ignoreOrder;
}
constructor(
address _weth
)
public
{
weth = WETH(_weth);
}
/// @dev Sends transactions to the Totle contract.
/// @param trades Array of Structs of parameters and orders.
/// @param id Number of the trasactions id.
function performRebalance(
address totlePrimaryAddress,
Trade memory trades,
bytes32 id
)
public
{
//Trade[] memory checkedTrades = new Trade[](trades.length);
//for (uint256 i = 1; i <= trades.length; i++) {
//address ETH_TOKEN_ADDRESS = address(0);
//address targetTokenAddress = trades[i].tokenAddress;
address targetTokenAddress = trades.tokenAddress;
/*
address oracleAddress = address(0);
Oracle oracle = Oracle(oracleAddress);
(uint expectedRate, ) = (oracle.getExpectedRate(
ERC20(ETH_TOKEN_ADDRESS),
ERC20(targetTokenAddress),
uint256(0),
false
)
);
if (expectedRate < trades[i].minimumExchangeRate * 95 / 100)
continue;
if (expectedRate > trades[i].minimumExchangeRate * 105 / 100)
continue;
*/
//checkedTrades[i] = trades[i];
Trade memory checkedTrades = trades;
// set allowances
address tokenTransferProxy = TotlePrimary(totlePrimaryAddress)
.tokenTransferProxy();
require(
setAllowances(
tokenTransferProxy,
targetTokenAddress,
2**256 -1
),
"ALLOWANCE_NOT_SET"
);
// TODO: differentiate between buy and sell order
weth.deposit.value(trades.tokenAmount)(); // TODO: check exact amount
//}
address totleAddress = totlePrimaryAddress;
(bool success, ) = totleAddress.call(
abi.encodeWithSignature(
"performRebalance(Trade[] calldata, bytes32)",
checkedTrades,
id
)
);
// set allowances back to 0
//for (uint256 i = 1; i <= trades.length; i++) {
//address targetTokenAddress = trades[i].tokenAddress;
//addreess tokenTransferProxy = ... // already defined
require(
setAllowances(
tokenTransferProxy,
targetTokenAddress,
0
),
"ALLOWANCE_NOT_REVOKED"
);
//}
require(
success,
"CALL_FAILED"
);
}
// TODO: add withdraw residual WETH function
/*
* INTERNAL FUNCTIONS
*/
/// @dev Allows owner to set an infinite allowance to an approved exchange.
/// @param tokenTransferProxy Address of the proxy to be approved.
/// @param token Address of the token to receive allowance for.
/// @param amount Amount to be approved.
function setAllowances(
address tokenTransferProxy,
address token,
uint256 amount)
internal
returns (bool success)
{
success = false;
require(
ERC20(token)
.approve(
tokenTransferProxy,
amount
),
"ALLOWANCE_SET_UNSUCCESSFUL"
);
return (success = true);
}
}
| INTERNAL FUNCTIONS/ Allows owner to set an infinite allowance to an approved exchange. tokenTransferProxy Address of the proxy to be approved. token Address of the token to receive allowance for. amount Amount to be approved. | function setAllowances(
address tokenTransferProxy,
address token,
uint256 amount)
internal
returns (bool success)
{
success = false;
require(
ERC20(token)
.approve(
tokenTransferProxy,
amount
),
"ALLOWANCE_SET_UNSUCCESSFUL"
);
return (success = true);
}
| 943,270 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
// (Uni|Pancake)Swap libs are interchangeable
import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Factory.sol";
import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol";
import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol";
import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";
/*
For lines that are marked ERC20 Token Standard, learn more at https://eips.ethereum.org/EIPS/eip-20.
*/
contract ERC20Deflationary is Context, IERC20, Ownable {
// Keeps track of balances for address that are included in receiving reward.
mapping (address => uint256) private _reflectionBalances;
// Keeps track of balances for address that are excluded from receiving reward.
mapping (address => uint256) private _tokenBalances;
// Keeps track of which address are excluded from fee.
mapping (address => bool) private _isExcludedFromFee;
// Keeps track of which address are excluded from reward.
mapping (address => bool) private _isExcludedFromReward;
// An array of addresses that are excluded from reward.
address[] private _excludedFromReward;
// ERC20 Token Standard
mapping (address => mapping (address => uint256)) private _allowances;
// Liquidity pool provider router
IUniswapV2Router02 internal _uniswapV2Router;
// This Token and WETH pair contract address.
address internal _uniswapV2Pair;
// Where burnt tokens are sent to. This is an address that no one can have accesses to.
address private constant burnAccount = 0x000000000000000000000000000000000000dEaD;
/*
Tax rate = (_taxXXX / 10**_tax_XXXDecimals) percent.
For example: if _taxBurn is 1 and _taxBurnDecimals is 2.
Tax rate = 0.01%
If you want tax rate for burn to be 5% for example,
set _taxBurn to 5 and _taxBurnDecimals to 0.
5 * (10 ** 0) = 5
*/
// Decimals of taxBurn. Used for have tax less than 1%.
uint8 private _taxBurnDecimals;
// Decimals of taxReward. Used for have tax less than 1%.
uint8 private _taxRewardDecimals;
// Decimals of taxLiquify. Used for have tax less than 1%.
uint8 private _taxLiquifyDecimals;
// This percent of a transaction will be burnt.
uint8 private _taxBurn;
// This percent of a transaction will be redistribute to all holders.
uint8 private _taxReward;
// This percent of a transaction will be added to the liquidity pool. More details at https://github.com/Sheldenshi/ERC20Deflationary.
uint8 private _taxLiquify;
// ERC20 Token Standard
uint8 private _decimals;
// ERC20 Token Standard
uint256 private _totalSupply;
// Current supply:= total supply - burnt tokens
uint256 private _currentSupply;
// A number that helps distributing fees to all holders respectively.
uint256 private _reflectionTotal;
// Total amount of tokens rewarded / distributing.
uint256 private _totalRewarded;
// Total amount of tokens burnt.
uint256 private _totalBurnt;
// Total amount of tokens locked in the LP (this token and WETH pair).
uint256 private _totalTokensLockedInLiquidity;
// Total amount of ETH locked in the LP (this token and WETH pair).
uint256 private _totalETHLockedInLiquidity;
// A threshold for swap and liquify.
uint256 private _minTokensBeforeSwap;
// ERC20 Token Standard
string private _name;
// ERC20 Token Standard
string private _symbol;
// Whether a previous call of SwapAndLiquify process is still in process.
bool private _inSwapAndLiquify;
bool private _autoSwapAndLiquifyEnabled;
bool private _autoBurnEnabled;
bool private _rewardEnabled;
// Prevent reentrancy.
modifier lockTheSwap {
require(!_inSwapAndLiquify, "Currently in swap and liquify.");
_inSwapAndLiquify = true;
_;
_inSwapAndLiquify = false;
}
// Return values of _getValues function.
struct ValuesFromAmount {
// Amount of tokens for to transfer.
uint256 amount;
// Amount tokens charged for burning.
uint256 tBurnFee;
// Amount tokens charged to reward.
uint256 tRewardFee;
// Amount tokens charged to add to liquidity.
uint256 tLiquifyFee;
// Amount tokens after fees.
uint256 tTransferAmount;
// Reflection of amount.
uint256 rAmount;
// Reflection of burn fee.
uint256 rBurnFee;
// Reflection of reward fee.
uint256 rRewardFee;
// Reflection of liquify fee.
uint256 rLiquifyFee;
// Reflection of transfer amount.
uint256 rTransferAmount;
}
/*
Events
*/
event Burn(address from, uint256 amount);
event TaxBurnUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal);
event TaxRewardUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal);
event TaxLiquifyUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal);
event MinTokensBeforeSwapUpdated(uint256 previous, uint256 current);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensAddedToLiquidity
);
event ExcludeAccountFromReward(address account);
event IncludeAccountInReward(address account);
event ExcludeAccountFromFee(address account);
event IncludeAccountInFee(address account);
event EnabledAutoBurn();
event EnabledReward();
event EnabledAutoSwapAndLiquify();
event DisabledAutoBurn();
event DisabledReward();
event DisabledAutoSwapAndLiquify();
event Airdrop(uint256 amount);
constructor (string memory name_, string memory symbol_, uint8 decimals_, uint256 tokenSupply_) {
// Sets the values for `name`, `symbol`, `totalSupply`, `currentSupply`, and `rTotal`.
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
_totalSupply = tokenSupply_ * (10 ** decimals_);
_currentSupply = _totalSupply;
_reflectionTotal = (~uint256(0) - (~uint256(0) % _totalSupply));
// Mint
_reflectionBalances[_msgSender()] = _reflectionTotal;
// exclude owner and this contract from fee.
excludeAccountFromFee(owner());
excludeAccountFromFee(address(this));
// exclude owner, burnAccount, and this contract from receiving rewards.
_excludeAccountFromReward(owner());
_excludeAccountFromReward(burnAccount);
_excludeAccountFromReward(address(this));
emit Transfer(address(0), _msgSender(), _totalSupply);
}
// allow the contract to receive ETH
receive() external payable {}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev Returns the address of this token and WETH pair.
*/
function uniswapV2Pair() public view virtual returns (address) {
return _uniswapV2Pair;
}
/**
* @dev Returns the current burn tax.
*/
function taxBurn() public view virtual returns (uint8) {
return _taxBurn;
}
/**
* @dev Returns the current reward tax.
*/
function taxReward() public view virtual returns (uint8) {
return _taxReward;
}
/**
* @dev Returns the current liquify tax.
*/
function taxLiquify() public view virtual returns (uint8) {
return _taxLiquify;
}
/**
* @dev Returns the current burn tax decimals.
*/
function taxBurnDecimals() public view virtual returns (uint8) {
return _taxBurnDecimals;
}
/**
* @dev Returns the current reward tax decimals.
*/
function taxRewardDecimals() public view virtual returns (uint8) {
return _taxRewardDecimals;
}
/**
* @dev Returns the current liquify tax decimals.
*/
function taxLiquifyDecimals() public view virtual returns (uint8) {
return _taxLiquifyDecimals;
}
/**
* @dev Returns true if auto burn feature is enabled.
*/
function autoBurnEnabled() public view virtual returns (bool) {
return _autoBurnEnabled;
}
/**
* @dev Returns true if reward feature is enabled.
*/
function rewardEnabled() public view virtual returns (bool) {
return _rewardEnabled;
}
/**
* @dev Returns true if auto swap and liquify feature is enabled.
*/
function autoSwapAndLiquifyEnabled() public view virtual returns (bool) {
return _autoSwapAndLiquifyEnabled;
}
/**
* @dev Returns the threshold before swap and liquify.
*/
function minTokensBeforeSwap() external view virtual returns (uint256) {
return _minTokensBeforeSwap;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() external view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns current supply of the token.
* (currentSupply := totalSupply - totalBurnt)
*/
function currentSupply() external view virtual returns (uint256) {
return _currentSupply;
}
/**
* @dev Returns the total number of tokens burnt.
*/
function totalBurnt() external view virtual returns (uint256) {
return _totalBurnt;
}
/**
* @dev Returns the total number of tokens locked in the LP.
*/
function totalTokensLockedInLiquidity() external view virtual returns (uint256) {
return _totalTokensLockedInLiquidity;
}
/**
* @dev Returns the total number of ETH locked in the LP.
*/
function totalETHLockedInLiquidity() external view virtual returns (uint256) {
return _totalETHLockedInLiquidity;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
if (_isExcludedFromReward[account]) return _tokenBalances[account];
return tokenFromReflection(_reflectionBalances[account]);
}
/**
* @dev Returns whether an account is excluded from reward.
*/
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcludedFromReward[account];
}
/**
* @dev Returns whether an account is excluded from fee.
*/
function isExcludedFromFee(address account) external view returns (bool) {
return _isExcludedFromFee[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);
require(_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), _allowances[sender][_msgSender()] - 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 Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Burn} event indicating the amount burnt.
* Emits a {Transfer} event with `to` set to the burn 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 != burnAccount, "ERC20: burn from the burn address");
uint256 accountBalance = balanceOf(account);
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
uint256 rAmount = _getRAmount(amount);
// Transfer from account to the burnAccount
if (_isExcludedFromReward[account]) {
_tokenBalances[account] -= amount;
}
_reflectionBalances[account] -= rAmount;
_tokenBalances[burnAccount] += amount;
_reflectionBalances[burnAccount] += rAmount;
_currentSupply -= amount;
_totalBurnt += amount;
emit Burn(account, amount);
emit Transfer(account, burnAccount, 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 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");
ValuesFromAmount memory values = _getValues(amount, _isExcludedFromFee[sender]);
if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferFromExcluded(sender, recipient, values);
} else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferToExcluded(sender, recipient, values);
} else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferStandard(sender, recipient, values);
} else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferBothExcluded(sender, recipient, values);
} else {
_transferStandard(sender, recipient, values);
}
emit Transfer(sender, recipient, values.tTransferAmount);
if (!_isExcludedFromFee[sender]) {
_afterTokenTransfer(values);
}
}
/**
* @dev Performs all the functionalities that are enabled.
*/
function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual {
// Burn
if (_autoBurnEnabled) {
_tokenBalances[address(this)] += values.tBurnFee;
_reflectionBalances[address(this)] += values.rBurnFee;
_approve(address(this), _msgSender(), values.tBurnFee);
burnFrom(address(this), values.tBurnFee);
}
// Reflect
if (_rewardEnabled) {
_distributeFee(values.rRewardFee, values.tRewardFee);
}
// Add to liquidity pool
if (_autoSwapAndLiquifyEnabled) {
// add liquidity fee to this contract.
_tokenBalances[address(this)] += values.tLiquifyFee;
_reflectionBalances[address(this)] += values.rLiquifyFee;
uint256 contractBalance = _tokenBalances[address(this)];
// whether the current contract balances makes the threshold to swap and liquify.
bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap;
if (overMinTokensBeforeSwap &&
!_inSwapAndLiquify &&
_msgSender() != _uniswapV2Pair &&
_autoSwapAndLiquifyEnabled
)
{
swapAndLiquify(contractBalance);
}
}
}
/**
* @dev Performs transfer between two accounts that are both included in receiving reward.
*/
function _transferStandard(address sender, address recipient, ValuesFromAmount memory values) private {
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
/**
* @dev Performs transfer from an included account to an excluded account.
* (included and excluded from receiving reward.)
*/
function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private {
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
/**
* @dev Performs transfer from an excluded account to an included account.
* (included and excluded from receiving reward.)
*/
function _transferFromExcluded(address sender, address recipient, ValuesFromAmount memory values) private {
_tokenBalances[sender] = _tokenBalances[sender] - values.amount;
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
/**
* @dev Performs transfer between two accounts that are both excluded in receiving reward.
*/
function _transferBothExcluded(address sender, address recipient, ValuesFromAmount memory values) private {
_tokenBalances[sender] = _tokenBalances[sender] - values.amount;
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
*/
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");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
/**
* @dev Excludes an account from receiving reward.
*
* Emits a {ExcludeAccountFromReward} event.
*
* Requirements:
*
* - `account` is included in receiving reward.
*/
function _excludeAccountFromReward(address account) internal {
require(!_isExcludedFromReward[account], "Account is already excluded.");
if(_reflectionBalances[account] > 0) {
_tokenBalances[account] = tokenFromReflection(_reflectionBalances[account]);
}
_isExcludedFromReward[account] = true;
_excludedFromReward.push(account);
emit ExcludeAccountFromReward(account);
}
/**
* @dev Includes an account from receiving reward.
*
* Emits a {IncludeAccountInReward} event.
*
* Requirements:
*
* - `account` is excluded in receiving reward.
*/
function _includeAccountInReward(address account) internal {
require(_isExcludedFromReward[account], "Account is already included.");
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_excludedFromReward[i] == account) {
_excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];
_tokenBalances[account] = 0;
_isExcludedFromReward[account] = false;
_excludedFromReward.pop();
break;
}
}
emit IncludeAccountInReward(account);
}
/**
* @dev Excludes an account from fee.
*
* Emits a {ExcludeAccountFromFee} event.
*
* Requirements:
*
* - `account` is included in fee.
*/
function excludeAccountFromFee(address account) internal {
require(!_isExcludedFromFee[account], "Account is already excluded.");
_isExcludedFromFee[account] = true;
emit ExcludeAccountFromFee(account);
}
/**
* @dev Includes an account from fee.
*
* Emits a {IncludeAccountFromFee} event.
*
* Requirements:
*
* - `account` is excluded in fee.
*/
function includeAccountInFee(address account) internal {
require(_isExcludedFromFee[account], "Account is already included.");
_isExcludedFromFee[account] = false;
emit IncludeAccountInFee(account);
}
/**
* @dev Airdrop tokens to all holders that are included from reward.
* Requirements:
* - the caller must have a balance of at least `amount`.
*/
function airdrop(uint256 amount) public {
address sender = _msgSender();
//require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function");
require(balanceOf(sender) >= amount, "The caller must have balance >= amount.");
ValuesFromAmount memory values = _getValues(amount, false);
if (_isExcludedFromReward[sender]) {
_tokenBalances[sender] -= values.amount;
}
_reflectionBalances[sender] -= values.rAmount;
_reflectionTotal = _reflectionTotal - values.rAmount;
_totalRewarded += amount ;
emit Airdrop(amount);
}
/**
* @dev Returns the reflected amount of a token.
* Requirements:
* - `amount` must be less than total supply.
*/
function reflectionFromToken(uint256 amount, bool deductTransferFee) internal view returns(uint256) {
require(amount <= _totalSupply, "Amount must be less than supply");
ValuesFromAmount memory values = _getValues(amount, deductTransferFee);
return values.rTransferAmount;
}
/**
* @dev Used to figure out the balance after reflection.
* Requirements:
* - `rAmount` must be less than reflectTotal.
*/
function tokenFromReflection(uint256 rAmount) internal view returns(uint256) {
require(rAmount <= _reflectionTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
/**
* @dev Swap half of contract's token balance for ETH,
* and pair it up with the other half to add to the
* liquidity pool.
*
* Emits {SwapAndLiquify} event indicating the amount of tokens swapped to eth,
* the amount of ETH added to the LP, and the amount of tokens added to the LP.
*/
function swapAndLiquify(uint256 contractBalance) private lockTheSwap {
// Split the contract balance into two halves.
uint256 tokensToSwap = contractBalance / 2;
uint256 tokensAddToLiquidity = contractBalance - tokensToSwap;
// Contract's current ETH balance.
uint256 initialBalance = address(this).balance;
// Swap half of the tokens to ETH.
swapTokensForEth(tokensToSwap);
// Figure out the exact amount of tokens received from swapping.
uint256 ethAddToLiquify = address(this).balance - initialBalance;
// Add to the LP of this token and WETH pair (half ETH and half this token).
addLiquidity(ethAddToLiquify, tokensAddToLiquidity);
_totalETHLockedInLiquidity += address(this).balance - initialBalance;
_totalTokensLockedInLiquidity += contractBalance - balanceOf(address(this));
emit SwapAndLiquify(tokensToSwap, ethAddToLiquify, tokensAddToLiquidity);
}
/**
* @dev Swap `amount` tokens for ETH.
*
* Emits {Transfer} event. From this contract to the token and WETH Pair.
*/
function swapTokensForEth(uint256 amount) 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), amount);
// Swap tokens to ETH
_uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0,
path,
address(this), // this contract will receive the eth that were swapped from the token
block.timestamp + 60 * 1000
);
}
/**
* @dev Add `ethAmount` of ETH and `tokenAmount` of tokens to the LP.
* Depends on the current rate for the pair between this token and WETH,
* `ethAmount` and `tokenAmount` might not match perfectly.
* Dust(leftover) ETH or token will be refunded to this contract
* (usually very small quantity).
*
* Emits {Transfer} event. From this contract to the token and WETH Pai.
*/
function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private {
_approve(address(this), address(_uniswapV2Router), tokenAmount);
// Add the ETH and token to LP.
// The LP tokens will be sent to burnAccount.
// No one will have access to them, so the liquidity will be locked forever.
_uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
burnAccount, // the LP is sent to burnAccount.
block.timestamp + 60 * 1000
);
}
/**
* @dev Distribute the `tRewardFee` tokens to all holders that are included in receiving reward.
* amount received is based on how many token one owns.
*/
function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private {
// This would decrease rate, thus increase amount reward receive based on one's balance.
_reflectionTotal = _reflectionTotal - rRewardFee;
_totalRewarded += tRewardFee;
}
/**
* @dev Returns fees and transfer amount in both tokens and reflections.
* tXXXX stands for tokenXXXX
* rXXXX stands for reflectionXXXX
* More details can be found at comments for ValuesForAmount Struct.
*/
function _getValues(uint256 amount, bool deductTransferFee) private view returns (ValuesFromAmount memory) {
ValuesFromAmount memory values;
values.amount = amount;
_getTValues(values, deductTransferFee);
_getRValues(values, deductTransferFee);
return values;
}
/**
* @dev Adds fees and transfer amount in tokens to `values`.
* tXXXX stands for tokenXXXX
* More details can be found at comments for ValuesForAmount Struct.
*/
function _getTValues(ValuesFromAmount memory values, bool deductTransferFee) view private {
if (deductTransferFee) {
values.tTransferAmount = values.amount;
} else {
// calculate fee
values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals);
values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals);
values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals);
// amount after fee
values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee;
}
}
/**
* @dev Adds fees and transfer amount in reflection to `values`.
* rXXXX stands for reflectionXXXX
* More details can be found at comments for ValuesForAmount Struct.
*/
function _getRValues(ValuesFromAmount memory values, bool deductTransferFee) view private {
uint256 currentRate = _getRate();
values.rAmount = values.amount * currentRate;
if (deductTransferFee) {
values.rTransferAmount = values.rAmount;
} else {
values.rAmount = values.amount * currentRate;
values.rBurnFee = values.tBurnFee * currentRate;
values.rRewardFee = values.tRewardFee * currentRate;
values.rLiquifyFee = values.tLiquifyFee * currentRate;
values.rTransferAmount = values.rAmount - values.rBurnFee - values.rRewardFee - values.rLiquifyFee;
}
}
/**
* @dev Returns `amount` in reflection.
*/
function _getRAmount(uint256 amount) private view returns (uint256) {
uint256 currentRate = _getRate();
return amount * currentRate;
}
/**
* @dev Returns the current reflection rate.
*/
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply / tSupply;
}
/**
* @dev Returns the current reflection supply and token supply.
*/
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _reflectionTotal;
uint256 tSupply = _totalSupply;
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply);
rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]];
tSupply = tSupply - _tokenBalances[_excludedFromReward[i]];
}
if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply);
return (rSupply, tSupply);
}
/**
* @dev Returns fee based on `amount` and `taxRate`
*/
function _calculateTax(uint256 amount, uint8 tax, uint8 taxDecimals_) private pure returns (uint256) {
return amount * tax / (10 ** taxDecimals_) / (10 ** 2);
}
/*
Owner functions
*/
/**
* @dev Enables the auto burn feature.
* Burn transaction amount * `taxBurn_` amount of tokens each transaction when enabled.
*
* Emits a {EnabledAutoBurn} event.
*
* Requirements:
*
* - auto burn feature mush be disabled.
* - tax must be greater than 0.
* - tax decimals + 2 must be less than token decimals.
* (because tax rate is in percentage)
*/
function enableAutoBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner {
require(!_autoBurnEnabled, "Auto burn feature is already enabled.");
require(taxBurn_ > 0, "Tax must be greater than 0.");
require(taxBurnDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2");
_autoBurnEnabled = true;
setTaxBurn(taxBurn_, taxBurnDecimals_);
emit EnabledAutoBurn();
}
/**
* @dev Enables the reward feature.
* Distribute transaction amount * `taxReward_` amount of tokens each transaction when enabled.
*
* Emits a {EnabledReward} event.
*
* Requirements:
*
* - reward feature mush be disabled.
* - tax must be greater than 0.
* - tax decimals + 2 must be less than token decimals.
* (because tax rate is in percentage)
*/
function enableReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner {
require(!_rewardEnabled, "Reward feature is already enabled.");
require(taxReward_ > 0, "Tax must be greater than 0.");
require(taxRewardDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2");
_rewardEnabled = true;
setTaxReward(taxReward_, taxRewardDecimals_);
emit EnabledReward();
}
/**
* @dev Enables the auto swap and liquify feature.
* Swaps half of transaction amount * `taxLiquify_` amount of tokens
* to ETH and pair with the other half of tokens to the LP each transaction when enabled.
*
* Emits a {EnabledAutoSwapAndLiquify} event.
*
* Requirements:
*
* - auto swap and liquify feature mush be disabled.
* - tax must be greater than 0.
* - tax decimals + 2 must be less than token decimals.
* (because tax rate is in percentage)
*/
function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner {
require(!_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already enabled.");
require(taxLiquify_ > 0, "Tax must be greater than 0.");
require(taxLiquifyDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2");
_minTokensBeforeSwap = minTokensBeforeSwap_;
// init Router
IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(routerAddress);
_uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).getPair(address(this), uniswapV2Router.WETH());
if (_uniswapV2Pair == address(0)) {
_uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
}
_uniswapV2Router = uniswapV2Router;
// exclude uniswapV2Router from receiving reward.
_excludeAccountFromReward(address(uniswapV2Router));
// exclude WETH and this Token Pair from receiving reward.
_excludeAccountFromReward(_uniswapV2Pair);
// exclude uniswapV2Router from paying fees.
excludeAccountFromFee(address(uniswapV2Router));
// exclude WETH and this Token Pair from paying fees.
excludeAccountFromFee(_uniswapV2Pair);
// enable
_autoSwapAndLiquifyEnabled = true;
setTaxLiquify(taxLiquify_, taxLiquifyDecimals_);
emit EnabledAutoSwapAndLiquify();
}
/**
* @dev Disables the auto burn feature.
*
* Emits a {DisabledAutoBurn} event.
*
* Requirements:
*
* - auto burn feature mush be enabled.
*/
function disableAutoBurn() public onlyOwner {
require(_autoBurnEnabled, "Auto burn feature is already disabled.");
setTaxBurn(0, 0);
_autoBurnEnabled = false;
emit DisabledAutoBurn();
}
/**
* @dev Disables the reward feature.
*
* Emits a {DisabledReward} event.
*
* Requirements:
*
* - reward feature mush be enabled.
*/
function disableReward() public onlyOwner {
require(_rewardEnabled, "Reward feature is already disabled.");
setTaxReward(0, 0);
_rewardEnabled = false;
emit DisabledReward();
}
/**
* @dev Disables the auto swap and liquify feature.
*
* Emits a {DisabledAutoSwapAndLiquify} event.
*
* Requirements:
*
* - auto swap and liquify feature mush be enabled.
*/
function disableAutoSwapAndLiquify() public onlyOwner {
require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already disabled.");
setTaxLiquify(0, 0);
_autoSwapAndLiquifyEnabled = false;
emit DisabledAutoSwapAndLiquify();
}
/**
* @dev Updates `_minTokensBeforeSwap`
*
* Emits a {MinTokensBeforeSwap} event.
*
* Requirements:
*
* - `minTokensBeforeSwap_` must be less than _currentSupply.
*/
function setMinTokensBeforeSwap(uint256 minTokensBeforeSwap_) public onlyOwner {
require(minTokensBeforeSwap_ < _currentSupply, "minTokensBeforeSwap must be higher than current supply.");
uint256 previous = _minTokensBeforeSwap;
_minTokensBeforeSwap = minTokensBeforeSwap_;
emit MinTokensBeforeSwapUpdated(previous, _minTokensBeforeSwap);
}
/**
* @dev Updates taxBurn
*
* Emits a {TaxBurnUpdate} event.
*
* Requirements:
*
* - auto burn feature must be enabled.
* - total tax rate must be less than 100%.
*/
function setTaxBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner {
require(_autoBurnEnabled, "Auto burn feature must be enabled. Try the EnableAutoBurn function.");
require(taxBurn_ + _taxReward + _taxLiquify < 100, "Tax fee too high.");
uint8 previousTax = _taxBurn;
uint8 previousDecimals = _taxBurnDecimals;
_taxBurn = taxBurn_;
_taxBurnDecimals = taxBurnDecimals_;
emit TaxBurnUpdate(previousTax, previousDecimals, taxBurn_, taxBurnDecimals_);
}
/**
* @dev Updates taxReward
*
* Emits a {TaxRewardUpdate} event.
*
* Requirements:
*
* - reward feature must be enabled.
* - total tax rate must be less than 100%.
*/
function setTaxReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner {
require(_rewardEnabled, "Reward feature must be enabled. Try the EnableReward function.");
require(_taxBurn + taxReward_ + _taxLiquify < 100, "Tax fee too high.");
uint8 previousTax = _taxReward;
uint8 previousDecimals = _taxRewardDecimals;
_taxReward = taxReward_;
_taxBurnDecimals = taxRewardDecimals_;
emit TaxRewardUpdate(previousTax, previousDecimals, taxReward_, taxRewardDecimals_);
}
/**
* @dev Updates taxLiquify
*
* Emits a {TaxLiquifyUpdate} event.
*
* Requirements:
*
* - auto swap and liquify feature must be enabled.
* - total tax rate must be less than 100%.
*/
function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner {
require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function.");
require(_taxBurn + _taxReward + taxLiquify_ < 100, "Tax fee too high.");
uint8 previousTax = _taxLiquify;
uint8 previousDecimals = _taxLiquifyDecimals;
_taxLiquify = taxLiquify_;
_taxLiquifyDecimals = taxLiquifyDecimals_;
emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_);
}
}
| Returns whether an account is excluded from reward./ | function isExcludedFromReward(address account) external view returns (bool) {
return _isExcludedFromReward[account];
}
| 916,781 |
pragma solidity 0.5.17;
import "./MToken.sol";
import "./ErrorReporter.sol";
import "./PriceOracle.sol";
import "./MomaMasterInterface.sol";
import "./MomaMasterStorage.sol";
import "./MomaPool.sol";
/**
* @title Moma's MomaMaster Contract
* @author Moma
*/
contract MomaMaster is MomaMasterInterface, MomaMasterV1Storage, MomaMasterErrorReporter, ExponentialNoError {
/// @notice Emitted when an admin supports a market
event MarketListed(MToken mToken);
/// @notice Emitted when an account enters a market
event MarketEntered(MToken mToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(MToken mToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(MToken mToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a mToken is changed
event NewBorrowCap(MToken indexed mToken, uint newBorrowCap);
/// @notice Emitted when a new token speed is updated for a market
event TokenSpeedUpdated(address indexed token, MToken indexed mToken, uint oldSpeed, uint newSpeed);
/// @notice Emitted when token is distributed to a supplier
event DistributedSupplierToken(address indexed token, MToken indexed mToken, address indexed supplier, uint tokenDelta, uint tokenSupplyIndex);
/// @notice Emitted when token is distributed to a borrower
event DistributedBorrowerToken(address indexed token, MToken indexed mToken, address indexed borrower, uint tokenDelta, uint tokenBorrowIndex);
/// @notice Emitted when token is claimed by user
event TokenClaimed(address indexed token, address indexed user, uint accrued, uint claimed, uint notClaimed);
/// @notice Emitted when token farm is updated by admin
event TokenFarmUpdated(EIP20Interface token, uint oldStart, uint oldEnd, uint newStart, uint newEnd);
/// @notice Emitted when a new token market is added to momaMarkets
event NewTokenMarket(address indexed token, MToken indexed mToken);
/// @notice Emitted when token is granted by admin
event TokenGranted(address token, address recipient, uint amount);
/// @notice Indicator that this is a MomaMaster contract (for inspection)
bool public constant isMomaMaster = true;
/// @notice The initial moma index for a market
uint224 public constant momaInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (MToken[] memory) {
MToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param mToken The mToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, MToken mToken) external view returns (bool) {
return markets[address(mToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param mTokens The list of addresses of the mToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory mTokens) public returns (uint[] memory) {
uint len = mTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
MToken mToken = MToken(mTokens[i]);
results[i] = uint(addToMarketInternal(mToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param mToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(mToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (oracle.getUnderlyingPrice(mToken) == 0) {
// not have price
return Error.PRICE_ERROR;
}
if (marketToJoin.accountMembership[borrower]) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(mToken);
emit MarketEntered(mToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param mTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address mTokenAddress) external returns (uint) {
MToken mToken = MToken(mTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the mToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(mToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set mToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete mToken from the account’s list of assets */
// load into memory for faster iteration
MToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == mToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
MToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(mToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param mToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[mToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateFarmSupplyIndex(mToken);
distributeSupplierFarm(mToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param mToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address mToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
mToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param mToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateFarmSupplyIndex(mToken);
distributeSupplierFarm(mToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[mToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param mToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
mToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param mToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint) {
require(isLendingPool, "this is not lending pool");
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[mToken], "borrow is paused");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[mToken].accountMembership[borrower]) {
// only mTokens may call borrowAllowed if borrower not in market
require(msg.sender == mToken, "sender must be mToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(MToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[mToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[mToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = MToken(mToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
uint borrowIndex = MToken(mToken).borrowIndex();
updateFarmBorrowIndex(mToken, borrowIndex);
distributeBorrowerFarm(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param mToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address mToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
mToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param mToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
require(isLendingPool, "this is not lending pool");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
uint borrowIndex = MToken(mToken).borrowIndex();
updateFarmBorrowIndex(mToken, borrowIndex);
distributeBorrowerFarm(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param mToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address mToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
mToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
require(isLendingPool, "this is not lending pool");
if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
mTokenBorrowed;
mTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
require(isLendingPool, "this is not lending pool");
// Shh - currently unused
seizeTokens;
if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (MToken(mTokenCollateral).momaMaster() != MToken(mTokenBorrowed).momaMaster()) {
return uint(Error.MOMAMASTER_MISMATCH);
}
// Keep the flywheel moving
updateFarmSupplyIndex(mTokenCollateral);
distributeSupplierFarm(mTokenCollateral, borrower);
distributeSupplierFarm(mTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
mTokenCollateral;
mTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param mToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(mToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateFarmSupplyIndex(mToken);
distributeSupplierFarm(mToken, src);
distributeSupplierFarm(mToken, dst);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param mToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
*/
function transferVerify(address mToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
mToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `mTokenBalance` is the number of mTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint mTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address mTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
MToken mTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
MToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
MToken asset = assets[i];
// Read the balances and exchange rate from the mToken
(oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * mTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with mTokenModify
if (asset == mTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in mToken.liquidateBorrowFresh)
* @param mTokenBorrowed The address of the borrowed mToken
* @param mTokenCollateral The address of the collateral mToken
* @param actualRepayAmount The amount of mTokenBorrowed underlying to convert into mTokenCollateral tokens
* @return (errorCode, number of mTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(MToken(mTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(MToken(mTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = MToken(mTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the MomaMaster
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _updatePriceOracle() public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Read the new oracle from factory
address newOracle = MomaFactoryInterface(factory).oracle();
// Check newOracle
require(newOracle != address(0), "factory not set oracle");
// Track the old oracle for the MomaMaster
PriceOracle oldOracle = oracle;
// Set MomaMaster's oracle to newOracle
oracle = PriceOracle(newOracle);
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, PriceOracle(newOracle));
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
require(newCloseFactorMantissa >= closeFactorMinMantissa, "close factor too small");
require(newCloseFactorMantissa <= closeFactorMaxMantissa, "close factor too large");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param mToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(mToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
require(newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa, "liquidation incentive too small");
require(newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "liquidation incentive too large");
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param mToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(MToken mToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (isLendingPool) {
require(address(mToken.interestRateModel()) != address(0), "mToken not set interestRateModel");
}
// Check is mToken
require(MomaFactoryInterface(factory).isMToken(address(mToken)), 'not mToken');
if (markets[address(mToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
require(mToken.isMToken(), 'not mToken contract'); // Sanity check to make sure its really a MToken
// Note that isMomaed is not in active use anymore
// markets[address(mToken)] = Market({isListed: true, isMomaed: false, collateralFactorMantissa: 0});
markets[address(mToken)] = Market({isListed: true, collateralFactorMantissa: 0});
_addMarketInternal(address(mToken));
emit MarketListed(mToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address mToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != MToken(mToken), "market already added");
}
allMarkets.push(MToken(mToken));
}
/**
* @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or pauseGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param mTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == pauseGuardian, "only admin or pauseGuardian can set borrow caps");
uint numMarkets = mTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(mTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(mTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _upgradeLendingPool() external returns (bool) {
require(msg.sender == admin, "only admin can upgrade");
// must update oracle first, it succuss or revert, so no need to check again
_updatePriceOracle();
// all markets must set interestRateModel
for (uint i = 0; i < allMarkets.length; i++) {
MToken mToken = allMarkets[i];
require(address(mToken.interestRateModel()) != address(0), "support market not set interestRateModel");
// require(oracle.getUnderlyingPrice(mToken) != 0, "support market not set price"); // let functions check
}
bool state = MomaFactoryInterface(factory).upgradeLendingPool();
if (state) {
require(updateBorrowBlock() == 0, "update borrow block error");
isLendingPool = true;
}
return state;
}
function _setMintPaused(MToken mToken, bool state) external returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state, "only admin can unpause");
mintGuardianPaused[address(mToken)] = state;
emit ActionPaused(mToken, "Mint", state);
return state;
}
function _setBorrowPaused(MToken mToken, bool state) external returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state, "only admin can unpause");
borrowGuardianPaused[address(mToken)] = state;
emit ActionPaused(mToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) external returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) external returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(MomaPool momaPool) external {
require(msg.sender == momaPool.admin(), "only momaPool admin can change brains");
require(momaPool._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == momaMasterImplementation;
}
/*** Farming ***/
/**
* @notice Update all markets' borrow block for all tokens when pool upgrade to lending pool
* @return uint 0=success, otherwise a failure
*/
function updateBorrowBlock() internal returns (uint) {
uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits");
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
uint32 nextBlock = blockNumber;
TokenFarmState storage state = farmStates[token];
if (state.startBlock > blockNumber) nextBlock = state.startBlock;
// if (state.endBlock < blockNumber) blockNumber = state.endBlock;
MToken[] memory mTokens = state.tokenMarkets;
for (uint j = 0; j < mTokens.length; j++) {
MToken mToken = mTokens[j];
state.borrowState[address(mToken)].block = nextBlock; // if state.speeds[address(mToken)] > 0 ?
}
}
return uint(Error.NO_ERROR);
}
/**
* @notice Accrue tokens and MOMA to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateFarmSupplyIndex(address mToken) internal {
updateMomaSupplyIndex(mToken);
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
updateTokenSupplyIndex(token, mToken);
}
}
/**
* @notice Accrue tokens and MOMA to the market by updating the supply index
* @param mToken The market whose supply index to update
* @param marketBorrowIndex The market borrow index
*/
function updateFarmBorrowIndex(address mToken, uint marketBorrowIndex) internal {
updateMomaBorrowIndex(mToken, marketBorrowIndex);
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
updateTokenBorrowIndex(token, mToken, marketBorrowIndex);
}
}
/**
* @notice Calculate tokens and MOMA accrued by a supplier
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute tokens and MOMA to
*/
function distributeSupplierFarm(address mToken, address supplier) internal {
distributeSupplierMoma(mToken, supplier);
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
distributeSupplierToken(token, mToken, supplier);
}
}
/**
* @notice Calculate tokens and MOMA accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute tokens and MOMA to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerFarm(address mToken, address borrower, uint marketBorrowIndex) internal {
distributeBorrowerMoma(mToken, borrower, marketBorrowIndex);
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
distributeBorrowerToken(token, mToken, borrower, marketBorrowIndex);
}
}
/*** Tokens Farming ***/
/**
* @notice Accrue token to the market by updating the supply index
* @param token The token whose supply index to update
* @param mToken The market whose supply index to update
*/
function updateTokenSupplyIndex(address token, address mToken) internal {
delegateToFarming(abi.encodeWithSignature("updateTokenSupplyIndex(address,address)", token, mToken));
}
/**
* @notice Accrue token to the market by updating the borrow index
* @param token The token whose borrow index to update
* @param mToken The market whose borrow index to update
* @param marketBorrowIndex The market borrow index
*/
function updateTokenBorrowIndex(address token, address mToken, uint marketBorrowIndex) internal {
delegateToFarming(abi.encodeWithSignature("updateTokenBorrowIndex(address,address,uint256)", token, mToken, marketBorrowIndex));
}
/**
* @notice Calculate token accrued by a supplier
* @param token The token in which the supplier is interacting
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute token to
*/
function distributeSupplierToken(address token, address mToken, address supplier) internal {
delegateToFarming(abi.encodeWithSignature("distributeSupplierToken(address,address,address)", token, mToken, supplier));
}
/**
* @notice Calculate token accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute token to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerToken(address token, address mToken, address borrower, uint marketBorrowIndex) internal {
delegateToFarming(abi.encodeWithSignature("distributeBorrowerToken(address,address,address,uint256)", token, mToken, borrower, marketBorrowIndex));
}
/*** Reward Public Functions ***/
/**
* @notice Distribute all the token accrued to user in specified markets of specified token and claim
* @param token The token to distribute
* @param mTokens The list of markets to distribute token in
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(address token, MToken[] memory mTokens, bool suppliers, bool borrowers) public {
delegateToFarming(abi.encodeWithSignature("dclaim(address,address[],bool,bool)", token, mTokens, suppliers, borrowers));
}
/**
* @notice Distribute all the token accrued to user in all markets of specified token and claim
* @param token The token to distribute
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(address token, bool suppliers, bool borrowers) external {
delegateToFarming(abi.encodeWithSignature("dclaim(address,bool,bool)", token, suppliers, borrowers));
}
/**
* @notice Distribute all the token accrued to user in all markets of specified tokens and claim
* @param tokens The list of tokens to distribute and claim
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(address[] memory tokens, bool suppliers, bool borrowers) public {
delegateToFarming(abi.encodeWithSignature("dclaim(address[],bool,bool)", tokens, suppliers, borrowers));
}
/**
* @notice Distribute all the token accrued to user in all markets of all tokens and claim
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(bool suppliers, bool borrowers) external {
delegateToFarming(abi.encodeWithSignature("dclaim(bool,bool)", suppliers, borrowers));
}
/**
* @notice Claim all the token have been distributed to user of specified token
* @param token The token to claim
*/
function claim(address token) external {
delegateToFarming(abi.encodeWithSignature("claim(address)", token));
}
/**
* @notice Claim all the token have been distributed to user of all tokens
*/
function claim() external {
delegateToFarming(abi.encodeWithSignature("claim()"));
}
/**
* @notice Calculate undistributed token accrued by the user in specified market of specified token
* @param user The address to calculate token for
* @param token The token to calculate
* @param mToken The market to calculate token
* @param suppliers Whether or not to calculate token earned by supplying
* @param borrowers Whether or not to calculate token earned by borrowing
* @return The amount of undistributed token of this user
*/
function undistributed(address user, address token, address mToken, bool suppliers, bool borrowers) public view returns (uint) {
bytes memory data = delegateToFarmingView(abi.encodeWithSignature("undistributed(address,address,address,bool,bool)", user, token, mToken, suppliers, borrowers));
return abi.decode(data, (uint));
}
/**
* @notice Calculate undistributed tokens accrued by the user in all markets of specified token
* @param user The address to calculate token for
* @param token The token to calculate
* @param suppliers Whether or not to calculate token earned by supplying
* @param borrowers Whether or not to calculate token earned by borrowing
* @return The amount of undistributed token of this user in each market
*/
function undistributed(address user, address token, bool suppliers, bool borrowers) public view returns (uint[] memory) {
bytes memory data = delegateToFarmingView(abi.encodeWithSignature("undistributed(address,address,bool,bool)", user, token, suppliers, borrowers));
return abi.decode(data, (uint[]));
}
/*** Token Distribution Admin ***/
/**
* @notice Transfer token to the recipient
* @dev Note: If there is not enough token, we do not perform the transfer all.
* @param token The token to transfer
* @param recipient The address of the recipient to transfer token to
* @param amount The amount of token to (possibly) transfer
*/
function _grantToken(address token, address recipient, uint amount) external {
delegateToFarming(abi.encodeWithSignature("_grantToken(address,address,uint256)", token, recipient, amount));
}
/**
* @notice Admin function to add/update erc20 token farming
* @dev Can only add token or restart this token farm again after endBlock
* @param token Token to add/update for farming
* @param start Block heiht to start to farm this token
* @param end Block heiht to stop farming
* @return uint 0=success, otherwise a failure
*/
function _setTokenFarm(EIP20Interface token, uint start, uint end) external returns (uint) {
bytes memory data = delegateToFarming(abi.encodeWithSignature("_setTokenFarm(address,uint256,uint256)", token, start, end));
return abi.decode(data, (uint));
}
/**
* @notice Set token speed for multi markets
* @dev Note that token speed could be set to 0 to halt liquidity rewards for a market
* @param token The token to update speed
* @param mTokens The markets whose token speed to update
* @param newSpeeds New token speeds for markets
*/
function _setTokensSpeed(address token, MToken[] memory mTokens, uint[] memory newSpeeds) public {
delegateToFarming(abi.encodeWithSignature("_setTokensSpeed(address,address[],uint256[])", token, mTokens, newSpeeds));
}
/*** MOMA Farming ***/
/**
* @notice Accrue MOMA to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateMomaSupplyIndex(address mToken) internal {
IMomaFarming(currentMomaFarming()).updateMarketSupplyState(mToken);
}
/**
* @notice Accrue MOMA to the market by updating the borrow index
* @param mToken The market whose borrow index to update
* @param marketBorrowIndex The market borrow index
*/
function updateMomaBorrowIndex(address mToken, uint marketBorrowIndex) internal {
IMomaFarming(currentMomaFarming()).updateMarketBorrowState(mToken, marketBorrowIndex);
}
/**
* @notice Calculate MOMA accrued by a supplier
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOMA to
*/
function distributeSupplierMoma(address mToken, address supplier) internal {
IMomaFarming(currentMomaFarming()).distributeSupplierMoma(mToken, supplier);
}
/**
* @notice Calculate MOMA accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOMA to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) internal {
IMomaFarming(currentMomaFarming()).distributeBorrowerMoma(mToken, borrower, marketBorrowIndex);
}
/*** View functions ***/
/**
* @notice Return all of the support tokens
* @dev The automatic getter may be used to access an individual token.
* @return The list of market addresses
*/
function getAllTokens() external view returns (address[] memory) {
return allTokens;
}
/**
* @notice Weather a token is farming
* @param token The token address to ask for
* @param market Which market
* @return Wether this market farm the token currently
*/
function isFarming(address token, address market) external view returns (bool) {
uint blockNumber = getBlockNumber();
TokenFarmState storage state = farmStates[token];
return state.speeds[market] > 0 && blockNumber > uint(state.startBlock) && blockNumber <= uint(state.endBlock);
}
/**
* @notice Get the market speed for a token
* @param token The token address to ask for
* @param market Which market
* @return The market farm speed of this token currently
*/
function getTokenMarketSpeed(address token, address market) external view returns (uint) {
return farmStates[token].speeds[market];
}
/**
* @notice Get the accrued amount of this token farming for a user
* @param token The token address to ask for
* @param user The user address to ask for
* @return The accrued amount of this token farming for a user
*/
function getTokenUserAccrued(address token, address user) external view returns (uint) {
return farmStates[token].accrued[user];
}
/**
* @notice Weather a market is this token market
* @param token The token address to ask for
* @param market The market address to ask for
* @return true of false
*/
function isTokenMarket(address token, address market) external view returns (bool) {
return farmStates[token].isTokenMarket[market];
}
/**
* @notice Return all the farming support markets of a token
* @param token The token address to ask for
* @return The list of market addresses
*/
function getTokenMarkets(address token) external view returns (MToken[] memory) {
return farmStates[token].tokenMarkets;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() external view returns (MToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/*** Delegate ***/
/**
* @notice Get current moma farming contract
* @return The contract address
*/
function currentMomaFarming() public view returns (address) {
return MomaFactoryInterface(factory).momaFarming();
}
/**
* @notice Get current farming contract
* @return The contract address
*/
function currentFarmingDelegate() public view returns (address) {
return MomaFactoryInterface(factory).farmingDelegate();
}
/**
* @notice Internal method to delegate execution to farming contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToFarming(bytes memory data) internal returns (bytes memory) {
address callee = currentFarmingDelegate();
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Public method to delegate view execution to farming contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToFarmingSelf(bytes memory data) public returns (bytes memory) {
require(msg.sender == address(this), "can only called by self");
return delegateToFarming(data);
}
/**
* @notice Internal method to delegate view execution to farming contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToFarmingView(bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToFarmingSelf(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
}
interface IMomaFarming {
function updateMarketSupplyState(address mToken) external;
function updateMarketBorrowState(address mToken, uint marketBorrowIndex) external;
function distributeSupplierMoma(address mToken, address supplier) external;
function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) external;
function upgradeLendingPool(address pool) external;
function isMomaFarming() external view returns (bool);
}
| Calculate token accrued by a borrower Borrowers will not begin to accrue until after the first interaction with the protocol. mToken The market in which the borrower is interacting borrower The address of the borrower to distribute token to marketBorrowIndex The market borrow index/ | function distributeBorrowerToken(address token, address mToken, address borrower, uint marketBorrowIndex) internal {
delegateToFarming(abi.encodeWithSignature("distributeBorrowerToken(address,address,address,uint256)", token, mToken, borrower, marketBorrowIndex));
}
| 12,663,229 |
./partial_match/42/0xe74EFb19BBC46DbE28b7BaB1F14af6eB7158B4BE/sources/L1_Bridge.sol | Bond covers _amount plus a bounty to pay a potential challenger | function getChallengeAmountForTransferAmount(uint256 _amount) public view returns (uint256) {
return _amount.mul(challengeAmountMultiplier).div(challengeAmountDivisor);
}
| 3,427,465 |
./partial_match/1/0xF2170fC7C95f2745FfE12366b29a003Ce2Da8820/sources/RefundEscrow.sol | Withdraws the beneficiary's funds./ | function beneficiaryWithdraw() public virtual {
require(_state == State.Closed, "RefundEscrow: beneficiary can only withdraw while closed");
_beneficiary.transfer(address(this).balance);
}
| 15,935,661 |
./full_match/43114/0xfA6289aE61588DC08a9E0CD31B6f64135a24412A/sources/DoubleMint.sol | Unstake and send to active | function sendToActive(address payable _active) public
{
_unstake();
uint256 amount = IERC20(time).balanceOf(address(this));
_active.transfer(amount);
}
| 4,521,688 |
pragma solidity 0.5.10;
// This is a staking token ERC677 contract
// (a copy of the token contract from https://github.com/poanetwork/tokenbridge-contracts repo).
// Since the source `ERC677BridgeTokenRewardable` requires solc v0.4.24 but truffle
// doesn't allow using different versions of compiler at the same time, this flat
// source file for `ERC677BridgeTokenRewardable` was taken from
// https://github.com/poanetwork/tokenbridge-contracts/tree/a7ce4441ab77e1c3e4d01017d862c53516933645
// cleared of excess functions and adapted for solc v0.5.10.
/* solhint-disable */
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/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: 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.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: 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 OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
/**
* @title DetailedERC20 token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string memory _name, string memory _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/interfaces/ERC677.sol
contract ERC677 is ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(address, uint256, bytes calldata) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) public returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool);
}
// File: contracts/interfaces/IBurnableMintableERC677Token.sol
contract IBurnableMintableERC677Token is ERC677 {
function mint(address _to, uint256 _amount) public returns (bool);
function burn(uint256 _value) public;
function claimTokens(address _token, address payable _to) public;
}
// File: contracts/upgradeable_contracts/Sacrifice.sol
contract Sacrifice {
constructor(address payable _recipient) public payable {
selfdestruct(_recipient);
}
}
// File: contracts/upgradeable_contracts/Claimable.sol
contract Claimable {
bytes4 internal constant TRANSFER = 0xa9059cbb; // transfer(address,uint256)
modifier validAddress(address _to) {
require(_to != address(0));
/* solcov ignore next */
_;
}
function claimValues(address _token, address payable _to) internal {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
function claimNativeCoins(address payable _to) internal {
uint256 value = address(this).balance;
if (!_to.send(value)) {
(new Sacrifice).value(value)(_to);
}
}
function claimErc20Tokens(address _token, address _to) internal {
ERC20Basic token = ERC20Basic(_token);
uint256 balance = token.balanceOf(address(this));
safeTransfer(_token, _to, balance);
}
function safeTransfer(address _token, address _to, uint256 _value) internal {
bytes memory returnData;
bool returnDataResult;
bytes memory callData = abi.encodeWithSelector(TRANSFER, _to, _value);
assembly {
let result := call(gas, _token, 0x0, add(callData, 0x20), mload(callData), 0, 32)
returnData := mload(0)
returnDataResult := mload(0)
switch result
case 0 {
revert(0, 0)
}
}
// Return data is optional
if (returnData.length > 0) {
require(returnDataResult);
}
}
}
// File: contracts/ERC677BridgeToken.sol
/**
* @title ERC677BridgeToken
* @dev The basic implementation of a bridgeable ERC677-compatible token
*/
contract ERC677BridgeToken is IBurnableMintableERC677Token, DetailedERC20, BurnableToken, MintableToken, Claimable {
bytes4 internal constant ON_TOKEN_TRANSFER = 0xa4c0ed36; // onTokenTransfer(address,uint256,bytes)
event ContractFallbackCallFailed(address from, address to, uint256 value);
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) DetailedERC20(_name, _symbol, _decimals) public {
// solhint-disable-previous-line no-empty-blocks
}
modifier validRecipient(address _recipient) {
require(_recipient != address(0) && _recipient != address(this));
/* solcov ignore next */
_;
}
function transferAndCall(address _to, uint256 _value, bytes calldata _data) external validRecipient(_to) returns (bool) {
require(superTransfer(_to, _value));
emit Transfer(msg.sender, _to, _value, _data);
if (AddressUtils.isContract(_to)) {
require(contractFallback(msg.sender, _to, _value, _data));
}
return true;
}
function getTokenInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
return (2, 2, 0);
}
function superTransfer(address _to, uint256 _value) internal returns (bool) {
return super.transfer(_to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(superTransfer(_to, _value));
callAfterTransfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(super.transferFrom(_from, _to, _value));
callAfterTransfer(_from, _to, _value);
return true;
}
function callAfterTransfer(address _from, address _to, uint256 _value) internal {
if (AddressUtils.isContract(_to) && !contractFallback(_from, _to, _value, new bytes(0))) {
require(!isBridge(_to));
emit ContractFallbackCallFailed(_from, _to, _value);
}
}
function isBridge(address) public view returns (bool);
/**
* @dev call onTokenTransfer fallback on the token recipient contract
* @param _from tokens sender
* @param _to tokens recipient
* @param _value amount of tokens that was sent
* @param _data set of extra bytes that can be passed to the recipient
*/
function contractFallback(address _from, address _to, uint256 _value, bytes memory _data) private returns (bool) {
(bool success,) = _to.call(abi.encodeWithSelector(ON_TOKEN_TRANSFER, _from, _value, _data));
return success;
}
function claimTokens(address _token, address payable _to) public onlyOwner validAddress(_to) {
claimValues(_token, _to);
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
return super.increaseApproval(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
return super.decreaseApproval(spender, subtractedValue);
}
}
// File: contracts/PermittableToken.sol
contract PermittableToken is ERC677BridgeToken {
string public constant version = "1";
// EIP712 niceties
bytes32 public DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
mapping(address => uint256) public nonces;
mapping(address => mapping(address => uint256)) public expirations;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _chainId
) ERC677BridgeToken(_name, _symbol, _decimals) public {
require(_chainId != 0);
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(_name)),
keccak256(bytes(version)),
_chainId,
address(this)
));
}
/// @dev transferFrom in this contract works in a slightly different form than the generic
/// transferFrom function. This contract allows for "unlimited approval".
/// Should the user approve an address for the maximum uint256 value,
/// then that address will have unlimited approval until told otherwise.
/// @param _sender The address of the sender.
/// @param _recipient The address of the recipient.
/// @param _amount The value to transfer.
/// @return Success status.
function transferFrom(address _sender, address _recipient, uint256 _amount) public returns (bool) {
require(_sender != address(0));
require(_recipient != address(0));
balances[_sender] = balances[_sender].sub(_amount);
balances[_recipient] = balances[_recipient].add(_amount);
emit Transfer(_sender, _recipient, _amount);
if (_sender != msg.sender) {
uint256 allowedAmount = allowance(_sender, msg.sender);
if (allowedAmount != uint256(-1)) {
// If allowance is limited, adjust it.
// In this case `transferFrom` works like the generic
allowed[_sender][msg.sender] = allowedAmount.sub(_amount);
emit Approval(_sender, msg.sender, allowed[_sender][msg.sender]);
} else {
// If allowance is unlimited by `permit`, `approve`, or `increaseAllowance`
// function, don't adjust it. But the expiration date must be empty or in the future
require(
expirations[_sender][msg.sender] == 0 || expirations[_sender][msg.sender] >= _now()
);
}
} else {
// If `_sender` is `msg.sender`,
// the function works just like `transfer()`
}
callAfterTransfer(_sender, _recipient, _amount);
return true;
}
/// @dev An alias for `transfer` function.
/// @param _to The address of the recipient.
/// @param _amount The value to transfer.
function push(address _to, uint256 _amount) public {
transferFrom(msg.sender, _to, _amount);
}
/// @dev Makes a request to transfer the specified amount
/// from the specified address to the caller's address.
/// @param _from The address of the holder.
/// @param _amount The value to transfer.
function pull(address _from, uint256 _amount) public {
transferFrom(_from, msg.sender, _amount);
}
/// @dev An alias for `transferFrom` function.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _amount The value to transfer.
function move(address _from, address _to, uint256 _amount) public {
transferFrom(_from, _to, _amount);
}
/// @dev Allows to spend holder's unlimited amount by the specified spender.
/// The function can be called by anyone, but requires having allowance parameters
/// signed by the holder according to EIP712.
/// @param _holder The holder's address.
/// @param _spender The spender's address.
/// @param _nonce The nonce taken from `nonces(_holder)` public getter.
/// @param _expiry The allowance expiration date (unix timestamp in UTC).
/// Can be zero for no expiration. Forced to zero if `_allowed` is `false`.
/// @param _allowed True to enable unlimited allowance for the spender by the holder. False to disable.
/// @param _v A final byte of signature (ECDSA component).
/// @param _r The first 32 bytes of signature (ECDSA component).
/// @param _s The second 32 bytes of signature (ECDSA component).
function permit(
address _holder,
address _spender,
uint256 _nonce,
uint256 _expiry,
bool _allowed,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
require(_holder != address(0));
require(_spender != address(0));
require(_expiry == 0 || _now() <= _expiry);
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(
PERMIT_TYPEHASH,
_holder,
_spender,
_nonce,
_expiry,
_allowed
))
));
require(_holder == ecrecover(digest, _v, _r, _s));
require(_nonce == nonces[_holder]++);
uint256 amount = _allowed ? uint256(-1) : 0;
allowed[_holder][_spender] = amount;
expirations[_holder][_spender] = _allowed ? _expiry : 0;
emit Approval(_holder, _spender, amount);
}
function _now() internal view returns(uint256) {
return now;
}
}
// File: contracts/ERC677MultiBridgeToken.sol
/**
* @title ERC677MultiBridgeToken
* @dev This contract extends ERC677BridgeToken to support several bridge simulteniously
*/
contract ERC677MultiBridgeToken is PermittableToken {
address public constant F_ADDR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
uint256 internal constant MAX_BRIDGES = 50;
mapping(address => address) public bridgePointers;
uint256 public bridgeCount;
event BridgeAdded(address indexed bridge);
event BridgeRemoved(address indexed bridge);
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _chainId
) PermittableToken(_name, _symbol, _decimals, _chainId) public {
bridgePointers[F_ADDR] = F_ADDR; // empty bridge contracts list
}
/**
* @dev Adds one more bridge contract into the list
* @param _bridge bridge contract address
*/
function addBridge(address _bridge) external onlyOwner {
require(bridgeCount < MAX_BRIDGES);
require(AddressUtils.isContract(_bridge));
require(!isBridge(_bridge));
address firstBridge = bridgePointers[F_ADDR];
require(firstBridge != address(0));
bridgePointers[F_ADDR] = _bridge;
bridgePointers[_bridge] = firstBridge;
bridgeCount = bridgeCount.add(1);
emit BridgeAdded(_bridge);
}
/**
* @dev Removes one existing bridge contract from the list
* @param _bridge bridge contract address
*/
function removeBridge(address _bridge) external onlyOwner {
require(isBridge(_bridge));
address nextBridge = bridgePointers[_bridge];
address index = F_ADDR;
address next = bridgePointers[index];
require(next != address(0));
while (next != _bridge) {
index = next;
next = bridgePointers[index];
require(next != F_ADDR && next != address(0));
}
bridgePointers[index] = nextBridge;
delete bridgePointers[_bridge];
bridgeCount = bridgeCount.sub(1);
emit BridgeRemoved(_bridge);
}
/**
* @dev Returns all recorded bridge contract addresses
* @return address[] bridge contract addresses
*/
function bridgeList() external view returns (address[] memory) {
address[] memory list = new address[](bridgeCount);
uint256 counter = 0;
address nextBridge = bridgePointers[F_ADDR];
require(nextBridge != address(0));
while (nextBridge != F_ADDR) {
list[counter] = nextBridge;
nextBridge = bridgePointers[nextBridge];
counter++;
require(nextBridge != address(0));
}
return list;
}
/**
* @dev Checks if given address is included into bridge contracts list
* @param _address bridge contract address
* @return bool true, if given address is a known bridge contract
*/
function isBridge(address _address) public view returns (bool) {
return _address != F_ADDR && bridgePointers[_address] != address(0);
}
}
// File: contracts/ERC677BridgeTokenRewardable.sol
contract ERC677BridgeTokenRewardable is ERC677MultiBridgeToken {
address public blockRewardContract;
address public stakingContract;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _chainId
) ERC677MultiBridgeToken(_name, _symbol, _decimals, _chainId) public {
// solhint-disable-previous-line no-empty-blocks
}
function setBlockRewardContract(address _blockRewardContract) external onlyOwner {
require(AddressUtils.isContract(_blockRewardContract));
blockRewardContract = _blockRewardContract;
}
function setStakingContract(address _stakingContract) external onlyOwner {
require(AddressUtils.isContract(_stakingContract));
require(balanceOf(_stakingContract) == 0);
stakingContract = _stakingContract;
}
modifier onlyBlockRewardContract() {
require(msg.sender == blockRewardContract);
/* solcov ignore next */
_;
}
modifier onlyStakingContract() {
require(msg.sender == stakingContract);
/* solcov ignore next */
_;
}
function mintReward(uint256 _amount) external onlyBlockRewardContract {
if (_amount == 0) return;
// Mint `_amount` for the BlockReward contract
address to = blockRewardContract;
totalSupply_ = totalSupply_.add(_amount);
balances[to] = balances[to].add(_amount);
emit Mint(to, _amount);
emit Transfer(address(0), to, _amount);
}
function stake(address _staker, uint256 _amount) external onlyStakingContract {
// Transfer `_amount` from `_staker` to `stakingContract`
balances[_staker] = balances[_staker].sub(_amount);
balances[stakingContract] = balances[stakingContract].add(_amount);
emit Transfer(_staker, stakingContract, _amount);
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != blockRewardContract);
require(_to != stakingContract);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != blockRewardContract);
require(_to != stakingContract);
return super.transferFrom(_from, _to, _value);
}
}
/* solhint-enable */
| Returns all recorded bridge contract addresses return address[] bridge contract addresses/ | function bridgeList() external view returns (address[] memory) {
address[] memory list = new address[](bridgeCount);
uint256 counter = 0;
address nextBridge = bridgePointers[F_ADDR];
require(nextBridge != address(0));
while (nextBridge != F_ADDR) {
list[counter] = nextBridge;
nextBridge = bridgePointers[nextBridge];
counter++;
require(nextBridge != address(0));
}
return list;
}
| 6,346,681 |
./partial_match/1/0xD2dF60073C0A9c0b607ca6AC809ACecc0D9250bD/sources/contracts/core/SmardexPair.sol | @inheritdoc ISmardexPair | function swap(
address _to,
bool _zeroForOne,
int256 _amountSpecified,
bytes calldata _data
) external override lock returns (int256 amount0_, int256 amount1_) {
require(_amountSpecified != 0, "SmarDex: ZERO_AMOUNT");
SwapParams memory _params = SwapParams({
amountCalculated: 0,
fictiveReserveIn: 0,
fictiveReserveOut: 0,
priceAverageIn: 0,
priceAverageOut: 0,
token0: token0,
token1: token1,
balanceIn: 0,
balanceOut: 0
});
(
_params.balanceIn,
_params.balanceOut,
_params.fictiveReserveIn,
_params.fictiveReserveOut,
_params.priceAverageIn,
_params.priceAverageOut
) = _zeroForOne
? (
IERC20(_params.token0).balanceOf(address(this)) - feeToAmount0,
IERC20(_params.token1).balanceOf(address(this)) - feeToAmount1,
fictiveReserve0,
fictiveReserve1,
priceAverage0,
priceAverage1
)
: (
IERC20(_params.token1).balanceOf(address(this)) - feeToAmount1,
IERC20(_params.token0).balanceOf(address(this)) - feeToAmount0,
fictiveReserve1,
fictiveReserve0,
priceAverage1,
priceAverage0
);
_params.fictiveReserveIn,
_params.fictiveReserveOut,
priceAverageLastTimestamp,
_params.priceAverageIn,
_params.priceAverageOut,
block.timestamp
);
? (_params.priceAverageIn.toUint128(), _params.priceAverageOut.toUint128(), uint40(block.timestamp))
: (_params.priceAverageOut.toUint128(), _params.priceAverageIn.toUint128(), uint40(block.timestamp));
if (_amountSpecified > 0) {
uint256 _temp;
(_temp, , , _params.fictiveReserveIn, _params.fictiveReserveOut) = SmardexLibrary.getAmountOut(
_amountSpecified.toUint256(),
_params.balanceIn,
_params.balanceOut,
_params.fictiveReserveIn,
_params.fictiveReserveOut,
_params.priceAverageIn,
_params.priceAverageOut
);
_params.amountCalculated = _temp.toInt256();
uint256 _temp;
(_temp, , , _params.fictiveReserveIn, _params.fictiveReserveOut) = SmardexLibrary.getAmountIn(
(-_amountSpecified).toUint256(),
_params.balanceIn,
_params.balanceOut,
_params.fictiveReserveIn,
_params.fictiveReserveOut,
_params.priceAverageIn,
_params.priceAverageOut
);
_params.amountCalculated = _temp.toInt256();
}
(amount0_, amount1_) = _zeroForOne
? (
_amountSpecified > 0
? (_amountSpecified, -_params.amountCalculated)
: (_params.amountCalculated, _amountSpecified)
)
: (
_amountSpecified > 0
? (-_params.amountCalculated, _amountSpecified)
: (_amountSpecified, _params.amountCalculated)
);
require(_to != _params.token0 && _to != _params.token1, "SmarDex: INVALID_TO");
if (_zeroForOne) {
if (amount1_ < 0) {
TransferHelper.safeTransfer(_params.token1, _to, uint256(-amount1_));
}
ISmardexSwapCallback(msg.sender).smardexSwapCallback(amount0_, amount1_, _data);
uint256 _balanceInBefore = _params.balanceIn;
_params.balanceIn = IERC20(token0).balanceOf(address(this));
require(
_balanceInBefore + feeToAmount0 + (amount0_).toUint256() <= _params.balanceIn,
"SmarDex: INSUFFICIENT_TOKEN0_INPUT_AMOUNT"
);
_params.balanceOut = IERC20(token1).balanceOf(address(this));
if (amount0_ < 0) {
TransferHelper.safeTransfer(_params.token0, _to, uint256(-amount0_));
}
ISmardexSwapCallback(msg.sender).smardexSwapCallback(amount0_, amount1_, _data);
uint256 _balanceInBefore = _params.balanceIn;
_params.balanceIn = IERC20(token1).balanceOf(address(this));
require(
_balanceInBefore + feeToAmount1 + (amount1_).toUint256() <= _params.balanceIn,
"SmarDex: INSUFFICIENT_TOKEN1_INPUT_AMOUNT"
);
_params.balanceOut = IERC20(token0).balanceOf(address(this));
}
if (_zeroForOne) {
if (_feeOn) {
feeToAmount0 += ((uint256(amount0_) * SmardexLibrary.FEES_POOL) / SmardexLibrary.FEES_BASE).toUint104();
}
_update(
_params.balanceIn,
_params.balanceOut,
_params.fictiveReserveIn,
_params.fictiveReserveOut,
_params.priceAverageIn,
_params.priceAverageOut
);
if (_feeOn) {
feeToAmount1 += ((uint256(amount1_) * SmardexLibrary.FEES_POOL) / SmardexLibrary.FEES_BASE).toUint104();
}
_update(
_params.balanceOut,
_params.balanceIn,
_params.fictiveReserveOut,
_params.fictiveReserveIn,
_params.priceAverageOut,
_params.priceAverageIn
);
}
emit Swap(msg.sender, _to, amount0_, amount1_);
}
| 3,646,215 |
pragma solidity ^0.4.0;
import "6_safe.sol";
// I need no ether to attack,
contract GiveMeEverything {
TokensGate public tg;
uint64 public theif_counter;
constructor() payable {
}
function startAttack(address _addr) public {
tg = TokensGate(_addr);
theif_counter = 0;
theif_counter++;
tg.transferEth(address(this), 500000000000000000 wei);
}
function() public payable {
// tries to steal a limited times to that the attack is successful (does not drain the resources)
//tg.transferEth(address(this), 500000000000000000 wei);
if (theif_counter < 8) {
theif_counter++;
tg.transferEth(address(this), 800000000000000000 wei);
}
}
} | tries to steal a limited times to that the attack is successful (does not drain the resources)tg.transferEth(address(this), 500000000000000000 wei); | function() public payable {
if (theif_counter < 8) {
theif_counter++;
tg.transferEth(address(this), 800000000000000000 wei);
}
}
| 15,816,527 |
./partial_match/1/0x7D70447241Be7442Ae08e96d7EF1d0c13d727f29/sources/InvestmentPool.sol | apply funds from investor. _beneficiary investor./ | function invest(address _beneficiary) public payable {
uint amount = msg.value;
_preValidateInvest(_beneficiary, amount);
weiRaised = weiRaised.add(amount);
investments[_beneficiary] = investments[_beneficiary].add(amount);
emit Invest(_beneficiary, amount);
}
| 2,804,649 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { Initializable } from "@openzeppelin/contracts/proxy/Initializable.sol";
import { EnsResolve } from "torn-token/contracts/ENS.sol";
import { ITornadoGovernance } from "../interfaces/ITornadoGovernance.sol";
/**
* @notice This is the staking contract of the governance staking upgrade.
* This contract should hold the staked funds which are received upon relayer registration,
* and properly attribute rewards to addresses without security issues.
* @dev CONTRACT RISKS:
* - Relayer staked TORN at risk if contract is compromised.
* */
contract TornadoStakingRewards is Initializable, EnsResolve {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice 1e25
uint256 public immutable ratioConstant;
ITornadoGovernance public immutable Governance;
IERC20 public immutable torn;
address public immutable relayerRegistry;
/// @notice the sum torn_burned_i/locked_amount_i*coefficient where i is incremented at each burn
uint256 public accumulatedRewardPerTorn;
/// @notice notes down accumulatedRewardPerTorn for an address on a lock/unlock/claim
mapping(address => uint256) public accumulatedRewardRateOnLastUpdate;
/// @notice notes down how much an account may claim
mapping(address => uint256) public accumulatedRewards;
event RewardsUpdated(address indexed account, uint256 rewards);
event RewardsClaimed(address indexed account, uint256 rewardsClaimed);
modifier onlyGovernance() {
require(msg.sender == address(Governance), "only governance");
_;
}
constructor(
address governanceAddress,
address tornAddress,
bytes32 _relayerRegistry
) public {
Governance = ITornadoGovernance(governanceAddress);
torn = IERC20(tornAddress);
relayerRegistry = resolve(_relayerRegistry);
ratioConstant = IERC20(tornAddress).totalSupply();
}
/**
* @notice This function should safely send a user his rewards.
* @dev IMPORTANT FUNCTION:
* We know that rewards are going to be updated every time someone locks or unlocks
* so we know that this function can't be used to falsely increase the amount of
* lockedTorn by locking in governance and subsequently calling it.
* - set rewards to 0 greedily
*/
function getReward() external {
uint256 rewards = _updateReward(msg.sender, Governance.lockedBalance(msg.sender));
rewards = rewards.add(accumulatedRewards[msg.sender]);
accumulatedRewards[msg.sender] = 0;
torn.safeTransfer(msg.sender, rewards);
emit RewardsClaimed(msg.sender, rewards);
}
/**
* @notice This function should increment the proper amount of rewards per torn for the contract
* @dev IMPORTANT FUNCTION:
* - calculation must not overflow with extreme values
* (amount <= 1e25) * 1e25 / (balance of vault <= 1e25) -> (extreme values)
* @param amount amount to add to the rewards
*/
function addBurnRewards(uint256 amount) external {
require(msg.sender == address(Governance) || msg.sender == relayerRegistry, "unauthorized");
accumulatedRewardPerTorn = accumulatedRewardPerTorn.add(
amount.mul(ratioConstant).div(torn.balanceOf(address(Governance.userVault())))
);
}
/**
* @notice This function should allow governance to properly update the accumulated rewards rate for an account
* @param account address of account to update data for
* @param amountLockedBeforehand the balance locked beforehand in the governance contract
* */
function updateRewardsOnLockedBalanceChange(address account, uint256 amountLockedBeforehand) external onlyGovernance {
uint256 claimed = _updateReward(account, amountLockedBeforehand);
accumulatedRewards[account] = accumulatedRewards[account].add(claimed);
}
/**
* @notice This function should allow governance rescue tokens from the staking rewards contract
* */
function withdrawTorn(uint256 amount) external onlyGovernance {
if (amount == type(uint256).max) amount = torn.balanceOf(address(this));
torn.safeTransfer(address(Governance), amount);
}
/**
* @notice This function should calculated the proper amount of rewards attributed to user since the last update
* @dev IMPORTANT FUNCTION:
* - calculation must not overflow with extreme values
* (accumulatedReward <= 1e25) * (lockedBeforehand <= 1e25) / 1e25
* - result may go to 0, since this implies on 1 TORN locked => accumulatedReward <= 1e7, meaning a very small reward
* @param account address of account to calculate rewards for
* @param amountLockedBeforehand the balance locked beforehand in the governance contract
* @return claimed the rewards attributed to user since the last update
*/
function _updateReward(address account, uint256 amountLockedBeforehand) private returns (uint256 claimed) {
if (amountLockedBeforehand != 0)
claimed = (accumulatedRewardPerTorn.sub(accumulatedRewardRateOnLastUpdate[account])).mul(amountLockedBeforehand).div(
ratioConstant
);
accumulatedRewardRateOnLastUpdate[account] = accumulatedRewardPerTorn;
emit RewardsUpdated(account, claimed);
}
/**
* @notice This function should show a user his rewards.
* @param account address of account to calculate rewards for
*/
function checkReward(address account) external view returns (uint256 rewards) {
uint256 amountLocked = Governance.lockedBalance(account);
if (amountLocked != 0)
rewards = (accumulatedRewardPerTorn.sub(accumulatedRewardRateOnLastUpdate[account])).mul(amountLocked).div(ratioConstant);
rewards = rewards.add(accumulatedRewards[account]);
}
}
| This function should allow governance rescue tokens from the staking rewards contract / | function withdrawTorn(uint256 amount) external onlyGovernance {
if (amount == type(uint256).max) amount = torn.balanceOf(address(this));
torn.safeTransfer(address(Governance), amount);
}
| 12,600,006 |
./full_match/11155111/0x1e7eE10b72628db353DeDDfd3A6EC8a2543BDF78/sources/src/SimpleStorage.sol | memory , calldata, storage -- with memory the information only exists for a short period of time same with calldata calldata once defined in a function cant be modified again after its being defined string are a special data type so they work with memory,calldata or storage creating a variable outside of a function automatically defaults to a storage variable | function addPeople(
string memory _name,
uint256 _number,
bool _isAdded
) public {
listOfPeopleAdded.push(Person(_number, _name, _isAdded));
nameToNumber[_name] = _number;
}
| 3,792,698 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
interface ISqwidMigrator {
function positionClosed(
uint256 positionId,
address receiver,
bool saleCreated
) external;
}
interface ISqwidERC1155 {
function mint(
address to,
uint256 amount,
string memory tokenURI,
string calldata mimeType_,
address royaltyRecipient,
uint256 royaltyValue
) external returns (uint256);
function mintBatch(
address to,
uint256[] memory amounts,
string[] memory tokenURIs,
string[] calldata mimeTypes,
address[] memory royaltyRecipients,
uint256[] memory royaltyValues
) external returns (uint256[] memory);
function burn(
address account,
uint256 id,
uint256 amount
) external;
function wrapERC721(
address extNftContract,
uint256 extTokenId,
string calldata mimeType_
) external returns (uint256);
function wrapERC1155(
address extNftContract,
uint256 extTokenId,
string calldata mimeType_,
uint256 amount
) external returns (uint256);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) external;
function balanceOf(address account, uint256 id) external view returns (uint256);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator) external view returns (bool);
function mimeType(uint256 tokenId) external view returns (string memory);
}
interface ISqwidMarketplace {
enum PositionState {
Available,
RegularSale,
Auction,
Raffle,
Loan
}
struct Item {
uint256 itemId;
address nftContract;
uint256 tokenId;
address creator;
uint256 positionCount;
ItemSale[] sales;
}
struct Position {
uint256 positionId;
uint256 itemId;
address payable owner;
uint256 amount;
uint256 price;
uint256 marketFee;
PositionState state;
}
struct ItemSale {
address seller;
address buyer;
uint256 price;
uint256 amount;
}
struct AuctionData {
uint256 deadline;
uint256 minBid;
address highestBidder;
uint256 highestBid;
mapping(address => uint256) addressToAmount;
mapping(uint256 => address) indexToAddress;
uint256 totalAddresses;
}
struct RaffleData {
uint256 deadline;
uint256 totalValue;
mapping(address => uint256) addressToAmount;
mapping(uint256 => address) indexToAddress;
uint256 totalAddresses;
}
struct LoanData {
uint256 loanAmount;
uint256 feeAmount;
uint256 numMinutes;
uint256 deadline;
address lender;
}
struct AuctionDataResponse {
uint256 deadline;
uint256 minBid;
address highestBidder;
uint256 highestBid;
uint256 totalAddresses;
}
struct RaffleDataResponse {
uint256 deadline;
uint256 totalValue;
uint256 totalAddresses;
}
function transferOwnership(address newOwner) external;
function setMarketFee(uint16 marketFee_, PositionState typeFee) external;
function setMimeTypeFee(uint256 mimeTypeFee_) external;
function setNftContractAddress(ISqwidERC1155 sqwidERC1155_) external;
function setMigratorAddress(ISqwidMigrator sqwidMigrator_) external;
function withdraw() external;
function currentItemId() external view returns (uint256);
function currentPositionId() external view returns (uint256);
function fetchItem(uint256 itemId) external view returns (Item memory);
function fetchPosition(uint256 positionId) external view returns (Position memory);
function fetchStateCount(PositionState state) external view returns (uint256);
function fetchAuctionData(uint256 positionId)
external
view
returns (AuctionDataResponse memory);
function fetchBid(uint256 positionId, uint256 bidIndex)
external
view
returns (address, uint256);
function fetchRaffleData(uint256 positionId) external view returns (RaffleDataResponse memory);
function fetchRaffleEntry(uint256 positionId, uint256 entryIndex)
external
view
returns (address, uint256);
function fetchLoanData(uint256 positionId) external view returns (LoanData memory);
}
contract SqwidMarketplaceUtil is Ownable {
struct ItemResponse {
uint256 itemId;
address nftContract;
uint256 tokenId;
address creator;
ISqwidMarketplace.ItemSale[] sales;
ISqwidMarketplace.Position[] positions;
}
struct PositionResponse {
uint256 positionId;
ISqwidMarketplace.Item item;
address payable owner;
uint256 amount;
uint256 price;
uint256 marketFee;
ISqwidMarketplace.PositionState state;
ISqwidMarketplace.AuctionDataResponse auctionData;
ISqwidMarketplace.RaffleDataResponse raffleData;
ISqwidMarketplace.LoanData loanData;
}
struct AuctionBidded {
PositionResponse auction;
uint256 bidAmount;
}
struct RaffleEntered {
PositionResponse raffle;
uint256 enteredAmount;
}
ISqwidMarketplace public marketplace;
modifier pagination(uint256 pageNumber, uint256 pageSize) {
require(pageNumber > 0, "SqwidMarketUtil: Page number cannot be 0");
require(pageSize <= 100 && pageSize > 0, "SqwidMarketUtil: Invalid page size");
_;
}
modifier idsSize(uint256 size) {
require(size <= 100 && size > 0, "SqwidMarketUtil: Invalid number of ids");
_;
}
constructor(ISqwidMarketplace marketplace_) {
marketplace = marketplace_;
}
/**
* Sets new market contract address.
*/
function setMarketContractAddress(ISqwidMarketplace marketplace_) external onlyOwner {
marketplace = marketplace_;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// ITEMS ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns item and all its item positions.
*/
function fetchItem(uint256 itemId) public view returns (ItemResponse memory) {
ISqwidMarketplace.Item memory item = marketplace.fetchItem(itemId);
require(item.itemId > 0, "SqwidMarketUtil: Item not found");
return
ItemResponse(
itemId,
item.nftContract,
item.tokenId,
item.creator,
item.sales,
_fetchPositionsByItemId(itemId)
);
}
/**
* Returns <limit> valid items for a given state starting at <startIndex> (where the itemIds
* are part of approvedIds)
*/
function fetchItems(
uint256 startIndex,
uint256 limit,
bytes memory approvedIds
) external view returns (ISqwidMarketplace.Item[] memory items) {
require(limit >= 1 && limit <= 100, "SqwidMarketUtil: Invalid limit");
uint256 totalItems = marketplace.currentItemId();
if (startIndex == 0) {
startIndex = totalItems;
}
require(
startIndex >= 1 && startIndex <= totalItems,
"SqwidMarketUtil: Invalid start index"
);
require(approvedIds.length > 0, "SqwidMarketUtil: Invalid approvedIds");
if (startIndex < limit) {
limit = startIndex;
}
items = new ISqwidMarketplace.Item[](limit);
uint256 count;
for (uint256 i = startIndex; i > 0; i--) {
if (_checkExistsBytes(i, approvedIds)) {
items[count] = marketplace.fetchItem(i);
count++;
if (count == limit) break;
}
}
}
/**
* Returns items paginated.
*/
function fetchItemsPage(uint256 pageSize, uint256 pageNumber)
external
view
pagination(pageSize, pageNumber)
returns (ISqwidMarketplace.Item[] memory items, uint256 totalPages)
{
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalItemCount = marketplace.currentItemId();
if (totalItemCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (items, 0);
}
if (startIndex > totalItemCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > totalItemCount) {
endIndex = totalItemCount;
}
// Fill array
items = new ISqwidMarketplace.Item[](endIndex - startIndex + 1);
uint256 count;
for (uint256 i = startIndex; i <= endIndex; i++) {
items[count] = marketplace.fetchItem(i);
count++;
}
// Set total number pages
totalPages = (totalItemCount + pageSize - 1) / pageSize;
}
/**
* Returns total number of items.
*/
function fetchNumberItems() public view returns (uint256) {
return marketplace.currentItemId();
}
/**
* Returns number of items created by an address.
*/
function fetchAddressNumberItemsCreated(address targetAddress) public view returns (uint256) {
uint256 createdItemCount = 0;
uint256 totalItemCount = marketplace.currentItemId();
for (uint256 i; i < totalItemCount; i++) {
if (marketplace.fetchItem(i + 1).creator == targetAddress) {
createdItemCount++;
}
}
return createdItemCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// POSITIONS ////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns item position.
*/
function fetchPosition(uint256 positionId) public view returns (PositionResponse memory) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(positionId);
require(position.positionId > 0, "SqwidMarketUtil: Position not found");
ISqwidMarketplace.AuctionDataResponse memory auctionData;
ISqwidMarketplace.RaffleDataResponse memory raffleData;
ISqwidMarketplace.LoanData memory loanData;
ISqwidMarketplace.Item memory item = marketplace.fetchItem(position.itemId);
uint256 amount = position.amount;
if (position.state == ISqwidMarketplace.PositionState.Available) {
amount = ISqwidERC1155(item.nftContract).balanceOf(position.owner, item.tokenId);
} else if (position.state == ISqwidMarketplace.PositionState.Auction) {
auctionData = marketplace.fetchAuctionData(positionId);
} else if (position.state == ISqwidMarketplace.PositionState.Raffle) {
raffleData = marketplace.fetchRaffleData(positionId);
} else if (position.state == ISqwidMarketplace.PositionState.Loan) {
loanData = marketplace.fetchLoanData(positionId);
}
return
PositionResponse(
positionId,
item,
position.owner,
amount,
position.price,
position.marketFee,
position.state,
auctionData,
raffleData,
loanData
);
}
/**
* Returns <limit> valid positions for a given state starting at <startIndex> (where the itemIds
* are part of approvedIds) of owner != address (0) it also filters by owner
*/
function fetchPositions(
ISqwidMarketplace.PositionState state,
address owner,
uint256 startIndex,
uint256 limit,
bytes memory approvedIds
) external view returns (PositionResponse[] memory positions) {
require(limit >= 1 && limit <= 100, "SqwidMarketUtil: Invalid limit");
uint256 totalPositions = marketplace.currentPositionId();
if (startIndex == 0) {
startIndex = totalPositions;
}
require(
startIndex >= 1 && startIndex <= totalPositions,
"SqwidMarketUtil: Invalid start index"
);
require(approvedIds.length > 0, "SqwidMarketUtil: Invalid approvedIds");
if (startIndex < limit) {
limit = startIndex;
}
positions = new PositionResponse[](limit);
uint256 count;
for (uint256 i = startIndex; i > 0; i--) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i);
if (
(owner != address(0) ? position.owner == owner : true) &&
position.state == state &&
position.amount > 0 &&
_checkExistsBytes(position.itemId, approvedIds)
) {
positions[count] = fetchPosition(i);
if (positions[count].amount > 0) {
count++;
if (count == limit) break;
} else {
delete positions[count];
}
}
}
}
/**
* Returns items positions from an address paginated.
*/
function fetchAddressPositionsPage(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
)
external
view
pagination(pageSize, pageNumber)
returns (PositionResponse[] memory positions, uint256 totalPages)
{
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressPositionCount;
uint256 firstMatch;
for (uint256 i; i < totalPositionCount; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i + 1);
if (position.owner == targetAddress) {
addressPositionCount++;
if (addressPositionCount == startIndex) {
firstMatch = i + 1;
}
}
}
if (addressPositionCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (positions, 0);
}
if (startIndex > addressPositionCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > addressPositionCount) {
endIndex = addressPositionCount;
}
uint256 size = endIndex - startIndex + 1;
// Fill array
positions = new PositionResponse[](size);
uint256 count;
for (uint256 i = firstMatch; count < size; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i);
if (position.owner == targetAddress) {
positions[count] = fetchPosition(i);
count++;
}
}
// Set total number of pages
totalPages = (addressPositionCount + pageSize - 1) / pageSize;
}
/**
* Returns item positions for a given state paginated.
*/
function fetchPositionsByStatePage(
ISqwidMarketplace.PositionState state,
uint256 pageSize,
uint256 pageNumber
)
external
view
pagination(pageSize, pageNumber)
returns (PositionResponse[] memory positions, uint256 totalPages)
{
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalStatePositions = marketplace.fetchStateCount(state);
if (totalStatePositions == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (positions, 0);
}
if (startIndex > totalStatePositions) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > totalStatePositions) {
endIndex = totalStatePositions;
}
uint256 size = endIndex - startIndex + 1;
// Fill array
positions = new PositionResponse[](size);
uint256 count;
uint256 statePositionCount;
for (uint256 i = 1; count < size; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i);
if (position.positionId > 0 && position.state == state) {
statePositionCount++;
if (statePositionCount >= startIndex) {
positions[count] = fetchPosition(i);
count++;
}
}
}
// Set total number pages
totalPages = (totalStatePositions + pageSize - 1) / pageSize;
}
/**
* Returns number of items positions from an address.
*/
function fetchAddressNumberPositions(address targetAddress) external view returns (uint256) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 positionCount = 0;
for (uint256 i; i < totalPositionCount; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i + 1);
if (position.owner == targetAddress) {
positionCount++;
}
}
return positionCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// AUCTIONS /////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns addresses and bids of an active auction.
*/
function fetchAuctionBids(uint256 positionId)
public
view
returns (address[] memory, uint256[] memory)
{
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(positionId);
require(
position.state == ISqwidMarketplace.PositionState.Auction,
"SqwidMarketUtil: Position on wrong state"
);
uint256 totalAddresses = marketplace.fetchAuctionData(positionId).totalAddresses;
// Initialize array
address[] memory addresses = new address[](totalAddresses);
uint256[] memory amounts = new uint256[](totalAddresses);
// Fill arrays
for (uint256 i; i < totalAddresses; i++) {
(address addr, uint256 amount) = marketplace.fetchBid(positionId, i);
addresses[i] = addr;
amounts[i] = amount;
}
return (addresses, amounts);
}
/**
* Returns bids by an address paginated.
*/
function fetchAddressBidsPage(
address targetAddress,
uint256 pageSize,
uint256 pageNumber,
bool newestToOldest
)
external
view
pagination(pageSize, pageNumber)
returns (AuctionBidded[] memory bids, uint256 totalPages)
{
if (newestToOldest) {
return _fetchAddressBidsReverse(targetAddress, pageSize, pageNumber);
} else {
return _fetchAddressBids(targetAddress, pageSize, pageNumber);
}
}
/**
* Returns number of bids by an address.
*/
function fetchAddressNumberBids(address targetAddress) external view returns (uint256) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressBidCount;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, ) = fetchAuctionBids(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressBidCount++;
}
}
}
}
return addressBidCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// RAFFLES //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns addresses and amounts of an active raffle.
*/
function fetchRaffleEntries(uint256 positionId)
public
view
returns (address[] memory, uint256[] memory)
{
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(positionId);
require(
position.state == ISqwidMarketplace.PositionState.Raffle,
"SqwidMarketUtil: Position on wrong state"
);
uint256 totalAddresses = marketplace.fetchRaffleData(positionId).totalAddresses;
// Initialize array
address[] memory addresses = new address[](totalAddresses);
uint256[] memory amounts = new uint256[](totalAddresses);
// Fill arrays
for (uint256 i; i < totalAddresses; i++) {
(address addr, uint256 amount) = marketplace.fetchRaffleEntry(positionId, i);
addresses[i] = addr;
amounts[i] = amount;
}
return (addresses, amounts);
}
/**
* Returns active raffles entered by an address paginated.
*/
function fetchAddressRafflesPage(
address targetAddress,
uint256 pageSize,
uint256 pageNumber,
bool newestToOldest
)
external
view
pagination(pageSize, pageNumber)
returns (RaffleEntered[] memory raffles, uint256 totalPages)
{
if (newestToOldest) {
return _fetchAddressRafflesReverse(targetAddress, pageSize, pageNumber);
} else {
return _fetchAddressRaffles(targetAddress, pageSize, pageNumber);
}
}
/**
* Returns number active raffles entered by an address.
*/
function fetchAddressNumberRaffles(address targetAddress) external view returns (uint256) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressRaffleCount;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, ) = fetchRaffleEntries(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressRaffleCount++;
}
}
}
}
return addressRaffleCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// LOANS ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns active loans funded by an address paginated.
*/
function fetchAddressLoansPage(
address targetAddress,
uint256 pageSize,
uint256 pageNumber,
bool newestToOldest
)
external
view
pagination(pageSize, pageNumber)
returns (PositionResponse[] memory loans, uint256 totalPages)
{
if (newestToOldest) {
return _fetchAddressLoansReverse(targetAddress, pageSize, pageNumber);
} else {
return _fetchAddressLoans(targetAddress, pageSize, pageNumber);
}
}
/**
* Returns number active loans funded by an address paginated.
*/
function fetchAddressNumberLoans(address targetAddress) external view returns (uint256) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressLoanCount;
for (uint256 i; i < totalPositionCount; i++) {
if (
marketplace.fetchLoanData(i + 1).lender == targetAddress &&
marketplace.fetchPosition(i + 1).positionId > 0
) {
addressLoanCount++;
}
}
return addressLoanCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// PRIVATE //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
function _fetchPositionsByItemId(uint256 itemId)
private
view
returns (ISqwidMarketplace.Position[] memory)
{
// Initialize array
ISqwidMarketplace.Position[] memory items = new ISqwidMarketplace.Position[](
marketplace.fetchItem(itemId).positionCount
);
// Fill array
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 currentIndex = 0;
for (uint256 i; i < totalPositionCount; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i + 1);
if (position.itemId == itemId) {
items[currentIndex] = position;
currentIndex++;
}
}
return items;
}
/**
* Returns bids by an address paginated (starting from first element).
*/
function _fetchAddressBids(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (AuctionBidded[] memory bids, uint256 totalPages) {
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressBidCount;
uint256 firstMatch;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, ) = fetchAuctionBids(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressBidCount++;
if (addressBidCount == startIndex) {
firstMatch = i + 1;
}
break;
}
}
}
}
if (addressBidCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (bids, 0);
}
if (startIndex > addressBidCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > addressBidCount) {
endIndex = addressBidCount;
}
// Fill array
bids = new AuctionBidded[](endIndex - startIndex + 1);
uint256 count;
for (uint256 i = firstMatch; count < endIndex - startIndex + 1; i++) {
if (marketplace.fetchPosition(i).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, uint256[] memory amounts) = fetchAuctionBids(i);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
bids[count] = AuctionBidded(fetchPosition(i), amounts[j]);
count++;
break;
}
}
}
}
// Set total number of pages
totalPages = (addressBidCount + pageSize - 1) / pageSize;
}
/**
* Returns bids by an address paginated in reverse order
* (starting from last element).
*/
function _fetchAddressBidsReverse(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (AuctionBidded[] memory bids, uint256 totalPages) {
// Get start and end index
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressBidCount;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, ) = fetchAuctionBids(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressBidCount++;
break;
}
}
}
}
if (addressBidCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (bids, 0);
}
if ((pageSize * (pageNumber - 1)) >= addressBidCount) {
revert("SqwidMarketUtil: Invalid page number");
}
uint256 startIndex = addressBidCount - (pageSize * (pageNumber - 1));
uint256 endIndex = 1;
if (startIndex > pageSize) {
endIndex = startIndex - pageSize + 1;
}
uint256 size = startIndex - endIndex + 1;
// Fill array
bids = new AuctionBidded[](size);
uint256 count;
uint256 addressBidIndex = addressBidCount + 1;
for (uint256 i = totalPositionCount; count < size; i--) {
if (marketplace.fetchPosition(i).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, uint256[] memory amounts) = fetchAuctionBids(i);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressBidIndex--;
if (addressBidIndex <= startIndex) {
bids[count] = AuctionBidded(fetchPosition(i), amounts[j]);
count++;
}
break;
}
}
}
}
// Set total number of pages
totalPages = (addressBidCount + pageSize - 1) / pageSize;
}
/**
* Returns active raffles entered by an address paginated (starting from first element).
*/
function _fetchAddressRaffles(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (RaffleEntered[] memory raffles, uint256 totalPages) {
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressRaffleCount;
uint256 firstMatch;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, ) = fetchRaffleEntries(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressRaffleCount++;
if (addressRaffleCount == startIndex) {
firstMatch = i + 1;
}
break;
}
}
}
}
if (addressRaffleCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (raffles, 0);
}
if (startIndex > addressRaffleCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > addressRaffleCount) {
endIndex = addressRaffleCount;
}
// Fill array
raffles = new RaffleEntered[](endIndex - startIndex + 1);
uint256 count;
for (uint256 i = firstMatch; count < endIndex - startIndex + 1; i++) {
if (marketplace.fetchPosition(i).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, uint256[] memory amounts) = fetchRaffleEntries(i);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
raffles[count] = RaffleEntered(fetchPosition(i), amounts[j]);
count++;
break;
}
}
}
}
// Set total number of pages
totalPages = (addressRaffleCount + pageSize - 1) / pageSize;
}
/**
* Returns active raffles entered by an address paginated in reverse order
* (starting from last element).
*/
function _fetchAddressRafflesReverse(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (RaffleEntered[] memory raffles, uint256 totalPages) {
// Get start and end index
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressRaffleCount;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, ) = fetchRaffleEntries(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressRaffleCount++;
break;
}
}
}
}
if (addressRaffleCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (raffles, 0);
}
if ((pageSize * (pageNumber - 1)) >= addressRaffleCount) {
revert("SqwidMarketUtil: Invalid page number");
}
uint256 startIndex = addressRaffleCount - (pageSize * (pageNumber - 1));
uint256 endIndex = 1;
if (startIndex > pageSize) {
endIndex = startIndex - pageSize + 1;
}
uint256 size = startIndex - endIndex + 1;
// Fill array
raffles = new RaffleEntered[](size);
uint256 count;
uint256 addressRaffleIndex = addressRaffleCount + 1;
for (uint256 i = totalPositionCount; count < size; i--) {
if (marketplace.fetchPosition(i).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, uint256[] memory amounts) = fetchRaffleEntries(i);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressRaffleIndex--;
if (addressRaffleIndex <= startIndex) {
raffles[count] = RaffleEntered(fetchPosition(i), amounts[j]);
count++;
}
break;
}
}
}
}
// Set total number of pages
totalPages = (addressRaffleCount + pageSize - 1) / pageSize;
}
/**
* Returns active loans funded by an address paginated (starting from first element).
*/
function _fetchAddressLoans(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (PositionResponse[] memory loans, uint256 totalPages) {
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressLoanCount;
uint256 firstMatch;
for (uint256 i; i < totalPositionCount; i++) {
if (
marketplace.fetchLoanData(i + 1).lender == targetAddress &&
marketplace.fetchPosition(i + 1).positionId > 0
) {
addressLoanCount++;
if (addressLoanCount == startIndex) {
firstMatch = i + 1;
}
}
}
if (addressLoanCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (loans, 0);
}
if (startIndex > addressLoanCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > addressLoanCount) {
endIndex = addressLoanCount;
}
// Fill array
loans = new PositionResponse[](endIndex - startIndex + 1);
uint256 count;
for (uint256 i = firstMatch; count < endIndex - startIndex + 1; i++) {
if (
marketplace.fetchLoanData(i).lender == targetAddress &&
marketplace.fetchPosition(i).positionId > 0
) {
loans[count] = fetchPosition(i);
count++;
}
}
// Set total number of pages
totalPages = (addressLoanCount + pageSize - 1) / pageSize;
}
/**
* Returns active loans funded by an address paginated in reverse order
* (starting from last element).
*/
function _fetchAddressLoansReverse(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (PositionResponse[] memory loans, uint256 totalPages) {
// Get start and end index
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressLoanCount;
for (uint256 i; i < totalPositionCount; i++) {
if (
marketplace.fetchLoanData(i + 1).lender == targetAddress &&
marketplace.fetchPosition(i + 1).positionId > 0
) {
addressLoanCount++;
}
}
if (addressLoanCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (loans, 0);
}
if ((pageSize * (pageNumber - 1)) >= addressLoanCount) {
revert("SqwidMarketUtil: Invalid page number");
}
uint256 startIndex = addressLoanCount - (pageSize * (pageNumber - 1));
uint256 endIndex = 1;
if (startIndex > pageSize) {
endIndex = startIndex - pageSize + 1;
}
uint256 size = startIndex - endIndex + 1;
// Fill array
loans = new PositionResponse[](size);
uint256 count;
uint256 addressLoanIndex = addressLoanCount + 1;
for (uint256 i = totalPositionCount; count < size; i--) {
if (
marketplace.fetchLoanData(i).lender == targetAddress &&
marketplace.fetchPosition(i).positionId > 0
) {
addressLoanIndex--;
if (addressLoanIndex <= startIndex) {
loans[count] = fetchPosition(i);
count++;
}
}
}
// Set total number of pages
totalPages = (addressLoanCount + pageSize - 1) / pageSize;
}
/**
* Returns whether a certain id is set to true (exists) by checking the byte
* byte of its corresponding position inside the packedBooleans variable.
*/
function _checkExistsBytes(uint256 _id, bytes memory _packedBooleans)
private
pure
returns (bool)
{
if (_id >= _packedBooleans.length * 8) {
return false;
}
uint8 b = uint8(_packedBooleans[_id / 8]);
uint8 mask = uint8((1 << (_id % 8)));
uint8 flag = b & mask;
return (flag != 0);
}
}
| Returns active loans funded by an address paginated in reverse order (starting from last element)./ Get start and end index | function _fetchAddressLoansReverse(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (PositionResponse[] memory loans, uint256 totalPages) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressLoanCount;
for (uint256 i; i < totalPositionCount; i++) {
if (
marketplace.fetchLoanData(i + 1).lender == targetAddress &&
marketplace.fetchPosition(i + 1).positionId > 0
) {
addressLoanCount++;
}
}
if (addressLoanCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (loans, 0);
}
if ((pageSize * (pageNumber - 1)) >= addressLoanCount) {
revert("SqwidMarketUtil: Invalid page number");
}
uint256 startIndex = addressLoanCount - (pageSize * (pageNumber - 1));
uint256 endIndex = 1;
if (startIndex > pageSize) {
endIndex = startIndex - pageSize + 1;
}
uint256 size = startIndex - endIndex + 1;
uint256 count;
uint256 addressLoanIndex = addressLoanCount + 1;
for (uint256 i = totalPositionCount; count < size; i--) {
if (
marketplace.fetchLoanData(i).lender == targetAddress &&
marketplace.fetchPosition(i).positionId > 0
) {
addressLoanIndex--;
if (addressLoanIndex <= startIndex) {
loans[count] = fetchPosition(i);
count++;
}
}
}
}
| 979,053 |
pragma solidity ^0.4.24;
contract RSEvents {
// 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 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 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 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 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
}
contract modularRatScam is RSEvents {}
contract ChivesGarden is modularRatScam {
using SafeMath for *;
using NameFilter for string;
using RSKeysCalc for uint256;
// TODO: check address
BankInterfaceForForwarder constant private Bank = BankInterfaceForForwarder(0xfa1678C00299fB685794865eA5e20dB155a8C913);
ChivesBookInterface constant private ChivesBook = ChivesBookInterface(0xE7D91A421D816349Cf0CD9C4b7a10123C2B28125);
address private admin = msg.sender;
string constant public name = "Chives Garden";
string constant public symbol = "Chives";
// TODO: check time
uint256 private rndGap_ = 0;
uint256 private rndExtra_ = 0 minutes;
uint256 constant private rndInit_ = 24 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
//****************
// 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 => RSdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => RSdatasets.PlayerRounds) public plyrRnds_; // current round
mapping (uint256 => mapping (uint256 => RSdatasets.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
//****************
uint256 public rID_; // round id number / total rounds that have happened
RSdatasets.Round public round_; // round data
mapping (uint256 => RSdatasets.Round) public round; // current round
//****************
// TEAM FEE DATA
//****************
uint256 public fees_ = 60; // fee distribution
uint256 public potSplit_ = 45; // pot split distribution
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet");
_;
}
/**
* @dev prevents contracts from interacting with ratscam
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "non smart contract address only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "too little money");
require(_eth <= 100000000000000000000000, "too much money");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (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
RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
*/
function buyXid(uint256 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.EventReturns memory _eventData_ = determinePID(_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;
}
// buy core
buyCore(_pID, _affCode, _eventData_);
}
function buyXaddr(address _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.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
buyCore(_pID, _affID, _eventData_);
}
function buyXname(bytes32 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.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
buyCore(_pID, _affID, _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 _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
RSdatasets.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
reLoadCore(_pID, _affCode, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
RSdatasets.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
reLoadCore(_pID, _affID, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
RSdatasets.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
reLoadCore(_pID, _affID, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round[_rID].end && round[_rID].ended == false && round[_rID].plyr != 0)
{
// set up our tx event data
RSdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit RSEvents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _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 registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = ChivesBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = ChivesBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
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) = ChivesBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit RSEvents.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)
{
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0)))
return ( (round[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @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)
{
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)
{
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round[_rID].end && round[_rID].ended == false && round[_rID].plyr != 0)
{
// if player is winner
if (round[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
plyrRnds_[_pID] = plyrRnds[_pID][_rID];
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round[_rID].mask).add(((((round[_rID].pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round[_rID].keys))).mul(plyrRnds[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return total keys
* @return time ends
* @return time started
* @return current pot
* @return current player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256)
{
uint256 _rID = rID_;
return
(
round[_rID].keys, //0
round[_rID].end, //1
round[_rID].strt, //2
round[_rID].pot, //3
round[_rID].plyr, //4
plyr_[round[_rID].plyr].addr, //5
plyr_[round[_rID].plyr].name, //6
airDropTracker_ + (airDropPot_ * 1000) //7
);
}
/**
* @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)
{
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
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (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, RSdatasets.EventReturns memory _eventData_)
private
{
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, _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 RSEvents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @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, RSdatasets.EventReturns memory _eventData_)
private
{
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)))
{
// 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.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _eventData_);
// if round is not active and end round needs to be ran
} else 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 RSEvents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_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, RSdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round[_rID].eth < 100000000000000000000 && plyrRnds[_pID][_rID].eth.add(_eth) > 10000000000000000000)
{
uint256 _availableLimit = (10000000000000000000).sub(plyrRnds[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round[_rID].eth).keysRec(_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;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 1 prize was won
_eventData_.compressedData += 100000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// 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);
// distribute eth
_eventData_ = distributeExternal(_pID, _eth, _affID, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _eth, _keys, _eventData_);
}
plyrRnds_[_pID] = plyrRnds[_pID][_rID];
round_ = round[_rID];
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @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)
{
return((((round[_rIDlast].mask).mul(plyrRnds[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds[_pID][_rIDlast].mask));
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _eth)
public
view
returns(uint256)
{
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0)))
return ( (round[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @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)
{
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0)))
return ( (round[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(ChivesBook), "only ChivesBook can call this function");
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(ChivesBook), "only ChivesBook can call this function");
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(RSdatasets.EventReturns memory _eventData_)
private
returns (RSdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of ratscam
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = ChivesBook.getPlayerID(msg.sender);
bytes32 _name = ChivesBook.getPlayerName(_pID);
uint256 _laff = ChivesBook.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, RSdatasets.EventReturns memory _eventData_)
private
returns (RSdatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
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(RSdatasets.EventReturns memory _eventData_)
private
returns (RSdatasets.EventReturns)
{
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round[_rID].plyr;
// grab our pot amount
// add airdrop pot into the final pot
// uint256 _pot = round[_rID].pot + airDropPot_;
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(45)) / 100;
uint256 _com = (_pot / 10);
uint256 _gen = (_pot.mul(potSplit_)) / 100;
// 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);
_com = _com.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
// if (!address(Bank).call.value(_com)(bytes4(keccak256("deposit()"))))
// {
// _gen = _gen.add(_com);
// _com = 0;
// }
// 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);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.newPot = _com;
// start next round
rID_++;
_rID++;
round[_rID].strt = now + rndExtra_;
round[_rID].end = now + rndInit_ + rndExtra_;
round[_rID].pot = _com;
round_ = round[_rID];
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);
plyrRnds_[_pID] = plyrRnds[_pID][_rIDlast];
}
}
/**
* @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);
round_ = round[_rID];
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_)
private
returns(RSdatasets.EventReturns)
{
// pay 5% out to community rewards
uint256 _com = _eth * 5 / 100;
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now);
} else {
// no affiliates, add to community
_com += _aff;
}
if (!address(Bank).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
}
return(_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_)
private
returns(RSdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_)) / 100;
// toss 5% into airdrop pot
uint256 _air = (_eth / 20);
airDropPot_ = airDropPot_.add(_air);
// calculate pot (20%)
uint256 _pot = (_eth.mul(20) / 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(_dust).add(round[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
round_ = round[_rID];
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);
plyrRnds_[_pID] = plyrRnds[_pID][_rID];
round_ = round[_rID];
// calculate & return dust
return(_gen.sub((_ppt.mul(round[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit RSEvents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_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;
function activate()
public
{
// only owner can activate
// TODO: set owner
require(msg.sender == admin);
// can only be ran once
require(activated_ == false, "ratscam already activated");
// activate the contract
activated_ = true;
rID_ = 1;
round[1].strt = now + rndExtra_;
round[1].end = now + rndInit_ + rndExtra_;
round_ = round[1];
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library RSdatasets {
//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 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
}
struct Round {
uint256 plyr; // pID of player 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
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library RSKeysCalc {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @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 eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface BankInterfaceForForwarder {
function deposit() external payable returns(bool);
}
interface ChivesBookInterface {
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);
}
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
* - 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;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
} | distributes eth based on fees to com, aff, and p3d/ pay 5% out to community rewards distribute share to affiliate decide what to do with affiliate share of fees affiliate must not be self, and must have a name registered no affiliates, add to community This ensures Team Just cannot influence the outcome of FoMo3D with bank migrations by breaking outgoing transactions. Something we would never do. But that's not the point. We spent 2000$ in eth re-deploying just to patch this, we hold the highest belief that everything we create should be trustless. Team JUST, The name you shouldn't have to trust. | function distributeExternal(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_)
private
returns(RSdatasets.EventReturns)
{
uint256 _com = _eth * 5 / 100;
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now);
_com += _aff;
}
if (!address(Bank).call.value(_com)(bytes4(keccak256("deposit()"))))
{
}
return(_eventData_);
}
| 338,459 |
pragma solidity ^0.4.18;
import "./BaseAPI.sol";
import "../interfaces/EpochRegistry.sol";
import "../interfaces/ContractDirectory.sol";
import "../interfaces/NodeRegistry.sol";
contract EpochRegistryAPI is EpochRegistry, BaseAPI {
// Events
event EpochStarted(uint256 _nonce, uint256 _blockStart, uint256 _blockEnd);
event RelayAddedToEpoch(bytes32 _relayNonce, bytes8 _token, bytes32 _txHash, address _sender, bytes32 _nodeNonce, uint256 _epoch);
event RelayVerified(uint256 _epoch, bytes32 _relayNonce, bytes32 _nodeNonce, bool _verificationResult);
// Functions
/*
* @dev Adds a Relay to the current epoch indicated in the state of this contract.
* @param bytes8 _token - The token id of the transaction (BTC, ETH, LTC, etc).
* @param bytes32 _txHash - The tx hash of this relay
* @param address _sender - Sender of the relay
* @param bytes32 _nodeNonce - The nonce pertaining to the Node doing this relay
*/
function addRelayToCurrentEpoch(bytes8 _token, bytes32 _txHash, address _sender, bytes32 _nodeNonce) public returns(bytes32) {
require(_sender != address(0x0));
NodeRegistry nodeRegistry = NodeRegistry(ContractDirectory(contractDirectory).getContract("NodeRegistry"));
require(nodeRegistry.getNodeOwner(_nodeNonce) == msg.sender);
Models.Epoch storage currentEpochInstance = epochs[currentEpoch];
if(epochsIndex.length == 0 || block.number > currentEpochInstance.blockEnd) {
insertEpoch();
currentEpochInstance = epochs[currentEpoch];
}
Models.Relay memory relay = Models.Relay(_token, _txHash, _sender, _nodeNonce);
bytes32 relayNonce = keccak256(_token, _txHash, _sender);
currentEpochInstance.relays[relayNonce] = relay;
currentEpochInstance.relaysPerNode[_nodeNonce].push(relayNonce);
RelayAddedToEpoch(relayNonce, _token, _txHash, _sender, _nodeNonce, currentEpoch);
return relayNonce;
}
/*
* @dev Adds a verification of whether or not a given Relay was succesfully executed or not.
* The condition to be able to verify a Relay, is being a Node that executed another Relay
* in the same Epoch.
* @param uint256 _epoch - The epoch where the relay happened.
* @param bytes32 _relayNonce - The nonce of the relay being verified
* @param bytes32 _nodeNonce - The nonce of the node submitting the verification
* @param bool _verificationResult - The result of this verification
*/
function verifyRelayInEpoch(uint256 _epoch, bytes32 _relayNonce, bytes32 _nodeNonce, bool _verificationResult) public {
Models.Epoch storage epoch = epochs[_epoch];
require(epoch.relays[_relayNonce].txHash != bytes32(0));
NodeRegistry nodeRegistry = NodeRegistry(ContractDirectory(contractDirectory).getContract("NodeRegistry"));
require(nodeRegistry.getNodeOwner(_nodeNonce) == msg.sender);
uint256 verifierRelayCount = epoch.relaysPerNode[_nodeNonce].length;
require(verifierRelayCount > 0);
epoch.relays[_relayNonce].verifications[_nodeNonce] = _verificationResult;
RelayVerified(_epoch, _relayNonce, _nodeNonce, _verificationResult);
}
/*
* @dev Registers the next epoch
*/
function insertEpoch() internal {
epochs[epochsIndex.length] = Models.Epoch(epochsIndex.length, block.number, block.number + blocksPerEpoch);
epochsIndex.push(epochs[epochsIndex.length].nonce);
currentEpoch = epochs[epochsIndex.length - 1].nonce;
EpochStarted(epochs[currentEpoch].nonce, epochs[currentEpoch].blockStart, epochs[currentEpoch].blockEnd);
}
/*
* @dev Sets the blocksPerEpoch state variable
*/
function setBlocksPerEpoch(uint256 _blocksPerEpoch) public onlyOwner {
blocksPerEpoch = _blocksPerEpoch;
}
/*
* @dev Checks wheter or not a relay exists with the given nonce at the given Epoch
* @param bytes32 _relayNonce
* @param uint256 _epochNonce
*/
function isRelayAtEpoch(bytes32 _relayNonce, uint256 _epochNonce) public view returns(bool) {
Models.Epoch storage epochInstance = epochs[_epochNonce];
return epochInstance.relays[_relayNonce].txHash != 0;
}
}
| Sets the blocksPerEpoch state variable/ | function setBlocksPerEpoch(uint256 _blocksPerEpoch) public onlyOwner {
blocksPerEpoch = _blocksPerEpoch;
}
| 5,535,358 |
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2; // solhint-disable-line
/**
* @dev Constant values shared across mixins.
*/
abstract contract Constants {
uint256 internal constant BASIS_POINTS = 10000;
}
interface ICHIARTNFT721 {
function tokenCreator(uint256 tokenId) external view returns (address payable);
}
/**
* @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));
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* @notice A mixin that stores a reference to the Chiart treasury contract.
*/
abstract contract ChiartTreasuryNode is Initializable {
using AddressUpgradeable for address payable;
address payable private treasury;
/**
* @dev Called once after the initial deployment to set the Chiart treasury address.
*/
function _initializeChiartTreasuryNode(address payable _treasury) internal initializer {
require(_treasury.isContract(), "ChiartTreasuryNode: Address is not a contract");
treasury = _treasury;
}
/**
* @notice Returns the address of the Chiart treasury.
*/
function getChiartTreasury() public view returns (address payable) {
return treasury;
}
// `______gap` is added to each mixin to allow adding new data slots or additional mixins in an upgrade-safe way.
uint256[2000] private __gap;
}
/**
* @notice Allows a contract to leverage an admin role defined by the Chiart contract.
*/
abstract contract ChiartAdminRole is ChiartTreasuryNode {
// This file uses 0 data slots (other than what's included via ChiartTreasuryNode)
modifier onlyChiartAdmin() {
require(
IAdminRole(getChiartTreasury()).isAdmin(msg.sender),
"ChiartAdminRole: caller does not have the Admin role"
);
_;
}
}
/**
* @notice A place for common modifiers and functions used by various NFTMarket mixins, if any.
* @dev This also leaves a gap which can be used to add a new mixin to the top of the inheritance tree.
*/
abstract contract NFTMarketCore {
/**
* @dev If the auction did not have an escrowed seller to return, this falls back to return the current owner.
* This allows functions to calculate the correct fees before the NFT has been listed in auction.
*/
function _getSellerFor(address nftContract, uint256 tokenId) internal view virtual returns (address) {
return IERC721Upgradeable(nftContract).ownerOf(tokenId);
}
// 50 slots were consumed by adding ReentrancyGuardUpgradeable
uint256[950] private ______gap;
}
/**
* @notice Attempt to send ETH and if the transfer fails or runs out of gas, store the balance
* for future withdrawal instead.
*/
abstract contract SendValueWithFallbackWithdraw is ReentrancyGuardUpgradeable {
using AddressUpgradeable for address payable;
using SafeMathUpgradeable for uint256;
mapping(address => uint256) private pendingWithdrawals;
event WithdrawPending(address indexed user, uint256 amount);
event Withdrawal(address indexed user, uint256 amount);
/**
* @notice Returns how much funds are available for manual withdraw due to failed transfers.
*/
function getPendingWithdrawal(address user) public view returns (uint256) {
return pendingWithdrawals[user];
}
/**
* @notice Allows a user to manually withdraw funds which originally failed to transfer.
*/
function withdraw() public nonReentrant {
uint256 amount = pendingWithdrawals[msg.sender];
require(amount > 0, "No funds are pending withdrawal");
pendingWithdrawals[msg.sender] = 0;
msg.sender.sendValue(amount);
emit Withdrawal(msg.sender, amount);
}
function _sendValueWithFallbackWithdraw(address payable user, uint256 amount) internal {
if (amount == 0) {
return;
}
// Cap the gas to prevent consuming all available gas to block a tx from completing successfully
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = user.call{ value: amount, gas: 20000 }("");
if (!success) {
// Record failed sends for a withdrawal later
// Transfers could fail if sent to a multisig with non-trivial receiver logic
// solhint-disable-next-line reentrancy
pendingWithdrawals[user] = pendingWithdrawals[user].add(amount);
emit WithdrawPending(user, amount);
}
}
uint256[499] private ______gap;
}
/**
* @notice A mixin for associating creators to NFTs.
* @dev In the future this may store creators directly in order to support NFTs created on a different platform.
*/
abstract contract NFTMarketCreators is
ReentrancyGuardUpgradeable // Adding this unused mixin to help with linearization
{
/**
* @dev If the creator is not available then 0x0 is returned. Downstream this indicates that the creator
* fee should be sent to the current seller instead.
* This may apply when selling NFTs that were not minted on Chiart.
*/
function getCreator(address nftContract, uint256 tokenId) internal view returns (address payable) {
try ICHIARTNFT721(nftContract).tokenCreator(tokenId) returns (address payable creator) {
return creator;
} catch {
return address(0);
}
}
// 500 slots were added via the new SendValueWithFallbackWithdraw mixin
uint256[500] private ______gap;
}
/**
* @notice A mixin to distribute funds when an NFT is sold.
*/
abstract contract NFTMarketFees is
Constants,
Initializable,
ChiartTreasuryNode,
NFTMarketCore,
NFTMarketCreators,
SendValueWithFallbackWithdraw
{
using SafeMathUpgradeable for uint256;
event MarketFeesUpdated(
uint256 primaryChiartFeeBasisPoints,
uint256 secondaryChiartFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
);
uint256 private _primaryChiartFeeBasisPoints;
uint256 private _secondaryChiartFeeBasisPoints;
uint256 private _secondaryCreatorFeeBasisPoints;
mapping(address => mapping(uint256 => bool)) private nftContractToTokenIdToFirstSaleCompleted;
/**
* @notice Returns true if the given NFT has not been sold in this market previously and is being sold by the creator.
*/
function getIsPrimary(address nftContract, uint256 tokenId) public view returns (bool) {
return _getIsPrimary(nftContract, tokenId, _getSellerFor(nftContract, tokenId));
}
/**
* @dev A helper that determines if this is a primary sale given the current seller.
* This is a minor optimization to use the seller if already known instead of making a redundant lookup call.
*/
function _getIsPrimary(
address nftContract,
uint256 tokenId,
address seller
) private view returns (bool) {
// By checking if the first sale has been completed first we can short circuit getCreator which is an external call.
return
!nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] && getCreator(nftContract, tokenId) == seller;
}
/**
* @notice Returns the current fee configuration in basis points.
*/
function getFeeConfig()
public
view
returns (
uint256 primaryChiartFeeBasisPoints,
uint256 secondaryChiartFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
)
{
return (_primaryChiartFeeBasisPoints, _secondaryChiartFeeBasisPoints, _secondaryCreatorFeeBasisPoints);
}
/**
* @notice Returns how funds will be distributed for a sale at the given price point.
* @dev This could be used to present exact fee distributing on listing or before a bid is placed.
*/
function getFees(
address nftContract,
uint256 tokenId,
uint256 price
)
public
view
returns (
uint256 chiartFee,
uint256 creatorSecondaryFee,
uint256 ownerRev
)
{
return _getFees(nftContract, tokenId, _getSellerFor(nftContract, tokenId), price);
}
/**
* @dev Calculates how funds should be distributed for the given sale details.
* If this is a primary sale, the creator revenue will appear as `ownerRev`.
*/
function _getFees(
address nftContract,
uint256 tokenId,
address seller,
uint256 price
)
public
view
returns (
uint256 chiartFee,
uint256 creatorSecondaryFee,
uint256 ownerRev
)
{
uint256 chiartFeeBasisPoints;
if (_getIsPrimary(nftContract, tokenId, seller)) {
chiartFeeBasisPoints = _primaryChiartFeeBasisPoints;
// On a primary sale, the creator is paid the remainder via `ownerRev`.
} else {
chiartFeeBasisPoints = _secondaryChiartFeeBasisPoints;
// SafeMath is not required when dividing by a constant value > 0.
creatorSecondaryFee = price.mul(_secondaryCreatorFeeBasisPoints) / BASIS_POINTS;
}
// SafeMath is not required when dividing by a constant value > 0.
chiartFee = price.mul(chiartFeeBasisPoints) / BASIS_POINTS;
ownerRev = price.sub(chiartFee).sub(creatorSecondaryFee);
}
/**
* @dev Distributes funds to chiart, creator, and NFT owner after a sale.
*/
function _distributeFunds(
address nftContract,
uint256 tokenId,
address payable seller,
uint256 price
)
internal
returns (
uint256 chiartFee,
uint256 creatorFee,
uint256 ownerRev
)
{
(chiartFee, creatorFee, ownerRev) = _getFees(nftContract, tokenId, seller, price);
// Anytime fees are distributed that indicates the first sale is complete,
// which will not change state during a secondary sale.
// This must come after the `_getFees` call above as this state is considered in the function.
nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] = true;
_sendValueWithFallbackWithdraw(getChiartTreasury(), chiartFee);
if (creatorFee > 0) {
address payable creator = getCreator(nftContract, tokenId);
if (creator == address(0)) {
// If the creator is unknown, send all revenue to the current seller instead.
ownerRev = ownerRev.add(creatorFee);
creatorFee = 0;
} else {
_sendValueWithFallbackWithdraw(creator, creatorFee);
}
}
_sendValueWithFallbackWithdraw(seller, ownerRev);
}
/**
* @notice Allows Chiart to change the market fees.
*/
function _updateMarketFees(
uint256 primaryChiartFeeBasisPoints,
uint256 secondaryChiartFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
) internal {
require(primaryChiartFeeBasisPoints < BASIS_POINTS, "NFTMarketFees: Fees >= 100%");
require(
secondaryChiartFeeBasisPoints.add(secondaryCreatorFeeBasisPoints) < BASIS_POINTS,
"NFTMarketFees: Fees >= 100%"
);
_primaryChiartFeeBasisPoints = primaryChiartFeeBasisPoints;
_secondaryChiartFeeBasisPoints = secondaryChiartFeeBasisPoints;
_secondaryCreatorFeeBasisPoints = secondaryCreatorFeeBasisPoints;
emit MarketFeesUpdated(
primaryChiartFeeBasisPoints,
secondaryChiartFeeBasisPoints,
secondaryCreatorFeeBasisPoints
);
}
uint256[1000] private ______gap;
}
/**
* @notice An abstraction layer for auctions.
* @dev This contract can be expanded with reusable calls and data as more auction types are added.
*/
abstract contract NFTMarketAuction {
/**
* @dev A global id for auctions of any type.
*/
uint256 private nextAuctionId;
function _initializeNFTMarketAuction() internal {
nextAuctionId = 1;
}
function _getNextAndIncrementAuctionId() internal returns (uint256) {
return nextAuctionId++;
}
uint256[1000] private ______gap;
}
/**
* @notice Manages a reserve price auction for NFTs.
*/
abstract contract NFTMarketReserveAuction is
Constants,
NFTMarketCore,
ReentrancyGuardUpgradeable,
SendValueWithFallbackWithdraw,
NFTMarketFees,
NFTMarketAuction
{
using SafeMathUpgradeable for uint256;
struct ReserveAuction {
address nftContract;
uint256 tokenId;
address payable seller;
uint256 duration;
uint256 extensionDuration;
uint256 endTime;
address payable bidder;
uint256 amount;
}
mapping(address => mapping(uint256 => uint256)) private nftContractToTokenIdToAuctionId;
mapping(uint256 => ReserveAuction) private auctionIdToAuction;
uint256 private _minPercentIncrementInBasisPoints;
// This variable was used in an older version of the contract, left here as a gap to ensure upgrade compatibility
uint256 private ______gap_was_maxBidIncrementRequirement;
uint256 private _duration;
// These variables were used in an older version of the contract, left here as gaps to ensure upgrade compatibility
uint256 private ______gap_was_extensionDuration;
uint256 private ______gap_was_goLiveDate;
// Cap the max duration so that overflows will not occur
uint256 private constant MAX_MAX_DURATION = 1000 days;
uint256 private constant EXTENSION_DURATION = 15 minutes;
event ReserveAuctionConfigUpdated(
uint256 minPercentIncrementInBasisPoints,
uint256 maxBidIncrementRequirement,
uint256 duration,
uint256 extensionDuration,
uint256 goLiveDate
);
event ReserveAuctionCreated(
address indexed seller,
address indexed nftContract,
uint256 indexed tokenId,
uint256 duration,
uint256 extensionDuration,
uint256 reservePrice,
uint256 auctionId
);
event ReserveAuctionUpdated(uint256 indexed auctionId, uint256 reservePrice);
event ReserveAuctionCanceled(uint256 indexed auctionId);
event ReserveAuctionBidPlaced(uint256 indexed auctionId, address indexed bidder, uint256 amount, uint256 endTime);
event ReserveAuctionFinalized(
uint256 indexed auctionId,
address indexed seller,
address indexed bidder,
uint256 f8nFee,
uint256 creatorFee,
uint256 ownerRev
);
modifier onlyValidAuctionConfig(uint256 reservePrice) {
require(reservePrice > 0, "NFTMarketReserveAuction: Reserve price must be at least 1 wei");
_;
}
/**
* @notice Returns auction details for a given auctionId.
*/
function getReserveAuction(uint256 auctionId) public view returns (ReserveAuction memory) {
return auctionIdToAuction[auctionId];
}
/**
* @notice Returns the auctionId for a given NFT, or 0 if no auction is found.
* @dev If an auction is canceled, it will not be returned. However the auction may be over and pending finalization.
*/
function getReserveAuctionIdFor(address nftContract, uint256 tokenId) public view returns (uint256) {
return nftContractToTokenIdToAuctionId[nftContract][tokenId];
}
/**
* @dev Returns the seller that put a given NFT into escrow,
* or bubbles the call up to check the current owner if the NFT is not currently in escrow.
*/
function _getSellerFor(address nftContract, uint256 tokenId) internal view virtual override returns (address) {
address seller = auctionIdToAuction[nftContractToTokenIdToAuctionId[nftContract][tokenId]].seller;
if (seller == address(0)) {
return super._getSellerFor(nftContract, tokenId);
}
return seller;
}
/**
* @notice Returns the current configuration for reserve auctions.
*/
function getReserveAuctionConfig() public view returns (uint256 minPercentIncrementInBasisPoints, uint256 duration) {
minPercentIncrementInBasisPoints = _minPercentIncrementInBasisPoints;
duration = _duration;
}
function _initializeNFTMarketReserveAuction() internal {
_duration = 24 hours; // A sensible default value
}
function _updateReserveAuctionConfig(uint256 minPercentIncrementInBasisPoints, uint256 duration) internal {
require(minPercentIncrementInBasisPoints <= BASIS_POINTS, "NFTMarketReserveAuction: Min increment must be <= 100%");
// Cap the max duration so that overflows will not occur
require(duration <= MAX_MAX_DURATION, "NFTMarketReserveAuction: Duration must be <= 1000 days");
require(duration >= EXTENSION_DURATION, "NFTMarketReserveAuction: Duration must be >= EXTENSION_DURATION");
_minPercentIncrementInBasisPoints = minPercentIncrementInBasisPoints;
_duration = duration;
// We continue to emit unused configuration variables to simplify the subgraph integration.
emit ReserveAuctionConfigUpdated(minPercentIncrementInBasisPoints, 0, duration, EXTENSION_DURATION, 0);
}
/**
* @notice Creates an auction for the given NFT.
* The NFT is held in escrow until the auction is finalized or canceled.
*/
function createReserveAuction(
address nftContract,
uint256 tokenId,
uint256 reservePrice
) public onlyValidAuctionConfig(reservePrice) nonReentrant {
// If an auction is already in progress then the NFT would be in escrow and the modifier would have failed
uint256 auctionId = _getNextAndIncrementAuctionId();
nftContractToTokenIdToAuctionId[nftContract][tokenId] = auctionId;
auctionIdToAuction[auctionId] = ReserveAuction(
nftContract,
tokenId,
msg.sender,
_duration,
EXTENSION_DURATION,
0, // endTime is only known once the reserve price is met
address(0), // bidder is only known once a bid has been placed
reservePrice
);
IERC721Upgradeable(nftContract).transferFrom(msg.sender, address(this), tokenId);
emit ReserveAuctionCreated(
msg.sender,
nftContract,
tokenId,
_duration,
EXTENSION_DURATION,
reservePrice,
auctionId
);
}
/**
* @notice If an auction has been created but has not yet received bids, the configuration
* such as the reservePrice may be changed by the seller.
*/
function updateReserveAuction(uint256 auctionId, uint256 reservePrice) public onlyValidAuctionConfig(reservePrice) {
ReserveAuction storage auction = auctionIdToAuction[auctionId];
require(auction.seller == msg.sender, "NFTMarketReserveAuction: Not your auction");
require(auction.endTime == 0, "NFTMarketReserveAuction: Auction in progress");
auction.amount = reservePrice;
emit ReserveAuctionUpdated(auctionId, reservePrice);
}
/**
* @notice If an auction has been created but has not yet received bids, it may be canceled by the seller.
* The NFT is returned to the seller from escrow.
*/
function cancelReserveAuction(uint256 auctionId) public nonReentrant {
ReserveAuction memory auction = auctionIdToAuction[auctionId];
require(auction.seller == msg.sender, "NFTMarketReserveAuction: Not your auction");
require(auction.endTime == 0, "NFTMarketReserveAuction: Auction in progress");
delete nftContractToTokenIdToAuctionId[auction.nftContract][auction.tokenId];
delete auctionIdToAuction[auctionId];
IERC721Upgradeable(auction.nftContract).transferFrom(address(this), auction.seller, auction.tokenId);
emit ReserveAuctionCanceled(auctionId);
}
/**
* @notice A bidder may place a bid which is at least the value defined by `getMinBidAmount`.
* If this is the first bid on the auction, the countdown will begin.
* If there is already an outstanding bid, the previous bidder will be refunded at this time
* and if the bid is placed in the final moments of the auction, the countdown may be extended.
*/
function placeBid(uint256 auctionId) public payable nonReentrant {
ReserveAuction storage auction = auctionIdToAuction[auctionId];
require(auction.amount != 0, "NFTMarketReserveAuction: Auction not found");
if (auction.endTime == 0) {
// If this is the first bid, ensure it's >= the reserve price
require(auction.amount <= msg.value, "NFTMarketReserveAuction: Bid must be at least the reserve price");
} else {
// If this bid outbids another, confirm that the bid is at least x% greater than the last
require(auction.endTime >= block.timestamp, "NFTMarketReserveAuction: Auction is over");
require(auction.bidder != msg.sender, "NFTMarketReserveAuction: You already have an outstanding bid");
uint256 minAmount = _getMinBidAmountForReserveAuction(auction.amount);
require(msg.value >= minAmount, "NFTMarketReserveAuction: Bid amount too low");
}
if (auction.endTime == 0) {
auction.amount = msg.value;
auction.bidder = msg.sender;
// On the first bid, the endTime is now + duration
auction.endTime = block.timestamp + auction.duration;
} else {
// Cache and update bidder state before a possible reentrancy (via the value transfer)
uint256 originalAmount = auction.amount;
address payable originalBidder = auction.bidder;
auction.amount = msg.value;
auction.bidder = msg.sender;
// When a bid outbids another, check to see if a time extension should apply.
if (auction.endTime - block.timestamp < auction.extensionDuration) {
auction.endTime = block.timestamp + auction.extensionDuration;
}
// Refund the previous bidder
_sendValueWithFallbackWithdraw(originalBidder, originalAmount);
}
emit ReserveAuctionBidPlaced(auctionId, msg.sender, msg.value, auction.endTime);
}
/**
* @notice Once the countdown has expired for an auction, anyone can settle the auction.
* This will send the NFT to the highest bidder and distribute funds.
*/
function finalizeReserveAuction(uint256 auctionId) public nonReentrant {
ReserveAuction memory auction = auctionIdToAuction[auctionId];
require(auction.endTime > 0, "NFTMarketReserveAuction: Auction has not started");
require(auction.endTime < block.timestamp, "NFTMarketReserveAuction: Auction still in progress");
delete nftContractToTokenIdToAuctionId[auction.nftContract][auction.tokenId];
delete auctionIdToAuction[auctionId];
IERC721Upgradeable(auction.nftContract).transferFrom(address(this), auction.bidder, auction.tokenId);
(uint256 f8nFee, uint256 creatorFee, uint256 ownerRev) =
_distributeFunds(auction.nftContract, auction.tokenId, auction.seller, auction.amount);
emit ReserveAuctionFinalized(auctionId, auction.seller, auction.bidder, f8nFee, creatorFee, ownerRev);
}
/**
* @notice Returns the minimum amount a bidder must spend to participate in an auction.
*/
function getMinBidAmount(uint256 auctionId) public view returns (uint256) {
ReserveAuction storage auction = auctionIdToAuction[auctionId];
if (auction.endTime == 0) {
return auction.amount;
}
return _getMinBidAmountForReserveAuction(auction.amount);
}
/**
* @dev Determines the minimum bid amount when outbidding another user.
*/
function _getMinBidAmountForReserveAuction(uint256 currentBidAmount) private view returns (uint256) {
uint256 minIncrement = currentBidAmount.mul(_minPercentIncrementInBasisPoints) / BASIS_POINTS;
if (minIncrement == 0) {
// The next bid must be at least 1 wei greater than the current.
return currentBidAmount.add(1);
}
return minIncrement.add(currentBidAmount);
}
uint256[1000] private ______gap;
}
/**
* @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);
}
}
}
}
/**
* @notice Interface for AdminRole which wraps the default admin role from
* OpenZeppelin's AccessControl for easy integration.
*/
interface IAdminRole {
function isAdmin(address account) external view returns (bool);
}
/**
* @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);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @title A market for NFTs on Chiart.
* @dev This top level file holds no data directly to ease future upgrades.
*/
contract CHIARTNFTMarket is
ChiartTreasuryNode,
ChiartAdminRole,
NFTMarketCore,
ReentrancyGuardUpgradeable,
NFTMarketCreators,
SendValueWithFallbackWithdraw,
NFTMarketFees,
NFTMarketAuction,
NFTMarketReserveAuction
{
/**
* @notice Called once to configure the contract after the initial deployment.
* @dev This farms the initialize call out to inherited contracts as needed.
*/
function initialize(address payable treasury) public initializer {
ChiartTreasuryNode._initializeChiartTreasuryNode(treasury);
NFTMarketAuction._initializeNFTMarketAuction();
NFTMarketReserveAuction._initializeNFTMarketReserveAuction();
}
/**
* @notice Allows Chiart to update the market configuration.
*/
function adminUpdateConfig(
uint256 minPercentIncrementInBasisPoints,
uint256 duration,
uint256 primaryF8nFeeBasisPoints,
uint256 secondaryF8nFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
) public onlyChiartAdmin {
_updateReserveAuctionConfig(minPercentIncrementInBasisPoints, duration);
_updateMarketFees(primaryF8nFeeBasisPoints, secondaryF8nFeeBasisPoints, secondaryCreatorFeeBasisPoints);
}
/**
* @dev Checks who the seller for an NFT is, this will check escrow or return the current owner if not in escrow.
* This is a no-op function required to avoid compile errors.
*/
function _getSellerFor(address nftContract, uint256 tokenId)
internal
view
virtual
override(NFTMarketCore, NFTMarketReserveAuction)
returns (address)
{
return super._getSellerFor(nftContract, tokenId);
}
} | Returns how much funds are available for manual withdraw due to failed transfers./ | function getPendingWithdrawal(address user) public view returns (uint256) {
return pendingWithdrawals[user];
}
| 41,777 |
./full_match/5/0x4D0a9d8ed1052B1F09de21D87eFd30a35Dc25c7d/sources/contracts/staking/StakingVolTiers.sol | Returns true if NFTs are locked (cannot be withdrawn), false otherwise | function getWithdrawalStatus() public view returns (bool) {
return (emergencyUnlock || block.timestamp > periodFinish) ? false : true;
}
| 11,613,098 |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;
import "./libraries/Margin.sol";
import "./libraries/ReplicationMath.sol";
import "./libraries/Reserve.sol";
import "./libraries/SafeCast.sol";
import "./libraries/Transfers.sol";
import "./libraries/Units.sol";
import "./interfaces/callback/IPrimitiveCreateCallback.sol";
import "./interfaces/callback/IPrimitiveDepositCallback.sol";
import "./interfaces/callback/IPrimitiveLiquidityCallback.sol";
import "./interfaces/callback/IPrimitiveSwapCallback.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IPrimitiveEngine.sol";
import "./interfaces/IPrimitiveFactory.sol";
/// @title Primitive Engine
/// @author Primitive
/// @notice Replicating Market Maker
/// @dev RMM-01
contract PrimitiveEngine is IPrimitiveEngine {
using ReplicationMath for int128;
using Units for uint256;
using SafeCast for uint256;
using Reserve for mapping(bytes32 => Reserve.Data);
using Reserve for Reserve.Data;
using Margin for mapping(address => Margin.Data);
using Margin for Margin.Data;
using Transfers for IERC20;
/// @dev Parameters of each pool
/// @param strike Strike price of pool with stable token decimals
/// @param sigma Implied volatility, with 1e4 decimals such that 10000 = 100%
/// @param maturity Timestamp of pool expiration, in seconds
/// @param lastTimestamp Timestamp of the pool's last update, in seconds
/// @param gamma Multiplied against deltaIn amounts to apply swap fee, gamma = 1 - fee %, scaled up by 1e4
struct Calibration {
uint128 strike;
uint32 sigma;
uint32 maturity;
uint32 lastTimestamp;
uint32 gamma;
}
/// @inheritdoc IPrimitiveEngineView
uint256 public constant override PRECISION = 10**18;
/// @inheritdoc IPrimitiveEngineView
uint256 public constant override BUFFER = 120 seconds;
/// @inheritdoc IPrimitiveEngineView
uint256 public immutable override MIN_LIQUIDITY;
/// @inheritdoc IPrimitiveEngineView
uint256 public immutable override scaleFactorRisky;
/// @inheritdoc IPrimitiveEngineView
uint256 public immutable override scaleFactorStable;
/// @inheritdoc IPrimitiveEngineView
address public immutable override factory;
/// @inheritdoc IPrimitiveEngineView
address public immutable override risky;
/// @inheritdoc IPrimitiveEngineView
address public immutable override stable;
/// @dev Reentrancy guard initialized to state
uint256 private locked = 1;
/// @inheritdoc IPrimitiveEngineView
mapping(bytes32 => Calibration) public override calibrations;
/// @inheritdoc IPrimitiveEngineView
mapping(address => Margin.Data) public override margins;
/// @inheritdoc IPrimitiveEngineView
mapping(bytes32 => Reserve.Data) public override reserves;
/// @inheritdoc IPrimitiveEngineView
mapping(address => mapping(bytes32 => uint256)) public override liquidity;
modifier lock() {
if (locked != 1) revert LockedError();
locked = 2;
_;
locked = 1;
}
/// @notice Deploys an Engine with two tokens, a 'Risky' and 'Stable'
constructor() {
(factory, risky, stable, scaleFactorRisky, scaleFactorStable, MIN_LIQUIDITY) = IPrimitiveFactory(msg.sender)
.args();
}
/// @return Risky token balance of this contract
function balanceRisky() private view returns (uint256) {
(bool success, bytes memory data) = risky.staticcall(
abi.encodeWithSelector(IERC20.balanceOf.selector, address(this))
);
if (!success || data.length != 32) revert BalanceError();
return abi.decode(data, (uint256));
}
/// @return Stable token balance of this contract
function balanceStable() private view returns (uint256) {
(bool success, bytes memory data) = stable.staticcall(
abi.encodeWithSelector(IERC20.balanceOf.selector, address(this))
);
if (!success || data.length != 32) revert BalanceError();
return abi.decode(data, (uint256));
}
/// @notice Revert if expected amount does not exceed current balance
function checkRiskyBalance(uint256 expectedRisky) private view {
uint256 actualRisky = balanceRisky();
if (actualRisky < expectedRisky) revert RiskyBalanceError(expectedRisky, actualRisky);
}
/// @notice Revert if expected amount does not exceed current balance
function checkStableBalance(uint256 expectedStable) private view {
uint256 actualStable = balanceStable();
if (actualStable < expectedStable) revert StableBalanceError(expectedStable, actualStable);
}
/// @return blockTimestamp casted as a uint32
function _blockTimestamp() internal view virtual returns (uint32 blockTimestamp) {
// solhint-disable-next-line
blockTimestamp = uint32(block.timestamp);
}
/// @inheritdoc IPrimitiveEngineActions
function updateLastTimestamp(bytes32 poolId) external override lock returns (uint32 lastTimestamp) {
lastTimestamp = _updateLastTimestamp(poolId);
}
/// @notice Sets the lastTimestamp of `poolId` to `block.timestamp`, max value is `maturity`
/// @return lastTimestamp of the pool, used in calculating the time until expiry
function _updateLastTimestamp(bytes32 poolId) internal virtual returns (uint32 lastTimestamp) {
Calibration storage cal = calibrations[poolId];
if (cal.lastTimestamp == 0) revert UninitializedError();
lastTimestamp = _blockTimestamp();
uint32 maturity = cal.maturity;
if (lastTimestamp > maturity) lastTimestamp = maturity; // if expired, set to the maturity
cal.lastTimestamp = lastTimestamp; // set state
emit UpdateLastTimestamp(poolId);
}
/// @inheritdoc IPrimitiveEngineActions
function create(
uint128 strike,
uint32 sigma,
uint32 maturity,
uint32 gamma,
uint256 riskyPerLp,
uint256 delLiquidity,
bytes calldata data
)
external
override
lock
returns (
bytes32 poolId,
uint256 delRisky,
uint256 delStable
)
{
(uint256 factor0, uint256 factor1) = (scaleFactorRisky, scaleFactorStable);
poolId = keccak256(abi.encodePacked(address(this), strike, sigma, maturity, gamma));
if (calibrations[poolId].lastTimestamp != 0) revert PoolDuplicateError();
if (sigma > 1e7 || sigma < 1) revert SigmaError(sigma);
if (strike == 0) revert StrikeError(strike);
if (delLiquidity <= MIN_LIQUIDITY) revert MinLiquidityError(delLiquidity);
if (riskyPerLp > PRECISION / factor0 || riskyPerLp == 0) revert RiskyPerLpError(riskyPerLp);
if (gamma > Units.PERCENTAGE || gamma < 9000) revert GammaError(gamma);
Calibration memory cal = Calibration({
strike: strike,
sigma: sigma,
maturity: maturity,
lastTimestamp: _blockTimestamp(),
gamma: gamma
});
if (cal.lastTimestamp > cal.maturity) revert PoolExpiredError();
uint32 tau = cal.maturity - cal.lastTimestamp; // time until expiry
delStable = ReplicationMath.getStableGivenRisky(0, factor0, factor1, riskyPerLp, cal.strike, cal.sigma, tau);
delRisky = (riskyPerLp * delLiquidity) / PRECISION; // riskyDecimals * 1e18 decimals / 1e18 = riskyDecimals
delStable = (delStable * delLiquidity) / PRECISION;
if (delRisky == 0 || delStable == 0) revert CalibrationError(delRisky, delStable);
calibrations[poolId] = cal; // state update
uint256 amount = delLiquidity - MIN_LIQUIDITY;
liquidity[msg.sender][poolId] += amount; // burn min liquidity, at cost of msg.sender
reserves[poolId].allocate(delRisky, delStable, delLiquidity, cal.lastTimestamp); // state update
(uint256 balRisky, uint256 balStable) = (balanceRisky(), balanceStable());
IPrimitiveCreateCallback(msg.sender).createCallback(delRisky, delStable, data);
checkRiskyBalance(balRisky + delRisky);
checkStableBalance(balStable + delStable);
emit Create(msg.sender, cal.strike, cal.sigma, cal.maturity, cal.gamma, delRisky, delStable, amount);
}
// ===== Margin =====
/// @inheritdoc IPrimitiveEngineActions
function deposit(
address recipient,
uint256 delRisky,
uint256 delStable,
bytes calldata data
) external override lock {
if (delRisky == 0 && delStable == 0) revert ZeroDeltasError();
margins[recipient].deposit(delRisky, delStable); // state update
uint256 balRisky;
uint256 balStable;
if (delRisky != 0) balRisky = balanceRisky();
if (delStable != 0) balStable = balanceStable();
IPrimitiveDepositCallback(msg.sender).depositCallback(delRisky, delStable, data); // agnostic payment
if (delRisky != 0) checkRiskyBalance(balRisky + delRisky);
if (delStable != 0) checkStableBalance(balStable + delStable);
emit Deposit(msg.sender, recipient, delRisky, delStable);
}
/// @inheritdoc IPrimitiveEngineActions
function withdraw(
address recipient,
uint256 delRisky,
uint256 delStable
) external override lock {
if (delRisky == 0 && delStable == 0) revert ZeroDeltasError();
margins.withdraw(delRisky, delStable); // state update
if (delRisky != 0) IERC20(risky).safeTransfer(recipient, delRisky);
if (delStable != 0) IERC20(stable).safeTransfer(recipient, delStable);
emit Withdraw(msg.sender, recipient, delRisky, delStable);
}
// ===== Liquidity =====
/// @inheritdoc IPrimitiveEngineActions
function allocate(
bytes32 poolId,
address recipient,
uint256 delRisky,
uint256 delStable,
bool fromMargin,
bytes calldata data
) external override lock returns (uint256 delLiquidity) {
if (delRisky == 0 || delStable == 0) revert ZeroDeltasError();
Reserve.Data storage reserve = reserves[poolId];
if (reserve.blockTimestamp == 0) revert UninitializedError();
uint32 timestamp = _blockTimestamp();
uint256 liquidity0 = (delRisky * reserve.liquidity) / uint256(reserve.reserveRisky);
uint256 liquidity1 = (delStable * reserve.liquidity) / uint256(reserve.reserveStable);
delLiquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
if (delLiquidity == 0) revert ZeroLiquidityError();
liquidity[recipient][poolId] += delLiquidity; // increase position liquidity
reserve.allocate(delRisky, delStable, delLiquidity, timestamp); // increase reserves and liquidity
if (fromMargin) {
margins.withdraw(delRisky, delStable); // removes tokens from `msg.sender` margin account
} else {
(uint256 balRisky, uint256 balStable) = (balanceRisky(), balanceStable());
IPrimitiveLiquidityCallback(msg.sender).allocateCallback(delRisky, delStable, data); // agnostic payment
checkRiskyBalance(balRisky + delRisky);
checkStableBalance(balStable + delStable);
}
emit Allocate(msg.sender, recipient, poolId, delRisky, delStable, delLiquidity);
}
/// @inheritdoc IPrimitiveEngineActions
function remove(bytes32 poolId, uint256 delLiquidity)
external
override
lock
returns (uint256 delRisky, uint256 delStable)
{
if (delLiquidity == 0) revert ZeroLiquidityError();
Reserve.Data storage reserve = reserves[poolId];
if (reserve.blockTimestamp == 0) revert UninitializedError();
(delRisky, delStable) = reserve.getAmounts(delLiquidity);
liquidity[msg.sender][poolId] -= delLiquidity; // state update
reserve.remove(delRisky, delStable, delLiquidity, _blockTimestamp());
margins[msg.sender].deposit(delRisky, delStable);
emit Remove(msg.sender, poolId, delRisky, delStable, delLiquidity);
}
struct SwapDetails {
address recipient;
bool riskyForStable;
bool fromMargin;
bool toMargin;
uint32 timestamp;
bytes32 poolId;
uint256 deltaIn;
uint256 deltaOut;
}
/// @inheritdoc IPrimitiveEngineActions
function swap(
address recipient,
bytes32 poolId,
bool riskyForStable,
uint256 deltaIn,
uint256 deltaOut,
bool fromMargin,
bool toMargin,
bytes calldata data
) external override lock {
if (deltaIn == 0) revert DeltaInError();
if (deltaOut == 0) revert DeltaOutError();
SwapDetails memory details = SwapDetails({
recipient: recipient,
poolId: poolId,
deltaIn: deltaIn,
deltaOut: deltaOut,
riskyForStable: riskyForStable,
fromMargin: fromMargin,
toMargin: toMargin,
timestamp: _blockTimestamp()
});
uint32 lastTimestamp = _updateLastTimestamp(details.poolId); // updates lastTimestamp of `poolId`
if (details.timestamp > lastTimestamp + BUFFER) revert PoolExpiredError(); // 120s buffer to allow final swaps
int128 invariantX64 = invariantOf(details.poolId); // stored in memory to perform the invariant check
{
// swap scope, avoids stack too deep errors
Calibration memory cal = calibrations[details.poolId];
Reserve.Data storage reserve = reserves[details.poolId];
uint32 tau = cal.maturity - cal.lastTimestamp;
uint256 deltaInWithFee = (details.deltaIn * cal.gamma) / Units.PERCENTAGE; // amount * (1 - fee %)
uint256 adjustedRisky;
uint256 adjustedStable;
if (details.riskyForStable) {
adjustedRisky = uint256(reserve.reserveRisky) + deltaInWithFee;
adjustedStable = uint256(reserve.reserveStable) - deltaOut;
} else {
adjustedRisky = uint256(reserve.reserveRisky) - deltaOut;
adjustedStable = uint256(reserve.reserveStable) + deltaInWithFee;
}
adjustedRisky = (adjustedRisky * PRECISION) / reserve.liquidity;
adjustedStable = (adjustedStable * PRECISION) / reserve.liquidity;
int128 invariantAfter = ReplicationMath.calcInvariant(
scaleFactorRisky,
scaleFactorStable,
adjustedRisky,
adjustedStable,
cal.strike,
cal.sigma,
tau
);
if (invariantX64 > invariantAfter) revert InvariantError(invariantX64, invariantAfter);
reserve.swap(details.riskyForStable, details.deltaIn, details.deltaOut, details.timestamp); // state update
}
if (details.riskyForStable) {
if (details.toMargin) {
margins[details.recipient].deposit(0, details.deltaOut);
} else {
IERC20(stable).safeTransfer(details.recipient, details.deltaOut); // optimistic transfer out
}
if (details.fromMargin) {
margins.withdraw(details.deltaIn, 0); // pay for swap
} else {
uint256 balRisky = balanceRisky();
IPrimitiveSwapCallback(msg.sender).swapCallback(details.deltaIn, 0, data); // agnostic transfer in
checkRiskyBalance(balRisky + details.deltaIn);
}
} else {
if (details.toMargin) {
margins[details.recipient].deposit(details.deltaOut, 0);
} else {
IERC20(risky).safeTransfer(details.recipient, details.deltaOut); // optimistic transfer out
}
if (details.fromMargin) {
margins.withdraw(0, details.deltaIn); // pay for swap
} else {
uint256 balStable = balanceStable();
IPrimitiveSwapCallback(msg.sender).swapCallback(0, details.deltaIn, data); // agnostic transfer in
checkStableBalance(balStable + details.deltaIn);
}
}
emit Swap(
msg.sender,
details.recipient,
details.poolId,
details.riskyForStable,
details.deltaIn,
details.deltaOut
);
}
// ===== View =====
/// @inheritdoc IPrimitiveEngineView
function invariantOf(bytes32 poolId) public view override returns (int128 invariant) {
Calibration memory cal = calibrations[poolId];
uint32 tau = cal.maturity - cal.lastTimestamp; // cal maturity can never be less than lastTimestamp
(uint256 riskyPerLiquidity, uint256 stablePerLiquidity) = reserves[poolId].getAmounts(PRECISION); // 1e18 liquidity
invariant = ReplicationMath.calcInvariant(
scaleFactorRisky,
scaleFactorStable,
riskyPerLiquidity,
stablePerLiquidity,
cal.strike,
cal.sigma,
tau
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
import "./SafeCast.sol";
/// @title Margin Library
/// @author Primitive
/// @dev Uses a data struct with two uint128s to optimize for one storage slot
library Margin {
using SafeCast for uint256;
struct Data {
uint128 balanceRisky; // Balance of the risky token, aka underlying asset
uint128 balanceStable; // Balance of the stable token, aka "quote" asset
}
/// @notice Adds to risky and stable token balances
/// @param margin Margin data of an account in storage to manipulate
/// @param delRisky Amount of risky tokens to add to margin
/// @param delStable Amount of stable tokens to add to margin
function deposit(
Data storage margin,
uint256 delRisky,
uint256 delStable
) internal {
if (delRisky != 0) margin.balanceRisky += delRisky.toUint128();
if (delStable != 0) margin.balanceStable += delStable.toUint128();
}
/// @notice Removes risky and stable token balance from `msg.sender`'s internal margin account
/// @param margins Margin data mapping, uses `msg.sender`'s margin account
/// @param delRisky Amount of risky tokens to subtract from margin
/// @param delStable Amount of stable tokens to subtract from margin
/// @return margin Data storage of a margin account
function withdraw(
mapping(address => Data) storage margins,
uint256 delRisky,
uint256 delStable
) internal returns (Data storage margin) {
margin = margins[msg.sender];
if (delRisky != 0) margin.balanceRisky -= delRisky.toUint128();
if (delStable != 0) margin.balanceStable -= delStable.toUint128();
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.4;
import "./ABDKMath64x64.sol";
import "./CumulativeNormalDistribution.sol";
import "./Units.sol";
/// @title Replication Math
/// @author Primitive
/// @notice Alex Evans, Guillermo Angeris, and Tarun Chitra. Replicating Market Makers.
/// https://stanford.edu/~guillean/papers/rmms.pdf
library ReplicationMath {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
using CumulativeNormalDistribution for int128;
using Units for int128;
using Units for uint256;
int128 internal constant ONE_INT = 0x10000000000000000;
/// @notice Normalizes volatility with respect to square root of time until expiry
/// @param sigma Unsigned 256-bit percentage as an integer with precision of 1e4, 10000 = 100%
/// @param tau Time until expiry in seconds as an unsigned 256-bit integer
/// @return vol Signed fixed point 64.64 number equal to sigma * sqrt(tau)
function getProportionalVolatility(uint256 sigma, uint256 tau) internal pure returns (int128 vol) {
int128 sqrtTauX64 = tau.toYears().sqrt();
int128 sigmaX64 = sigma.percentageToX64();
vol = sigmaX64.mul(sqrtTauX64);
}
/// @notice Uses riskyPerLiquidity and invariant to calculate stablePerLiquidity
/// @dev Converts unsigned 256-bit values to fixed point 64.64 numbers w/ decimals of precision
/// @param invariantLastX64 Signed 64.64 fixed point number. Calculated w/ same `tau` as the parameter `tau`
/// @param scaleFactorRisky Unsigned 256-bit integer scaling factor for `risky`, 10^(18 - risky.decimals())
/// @param scaleFactorStable Unsigned 256-bit integer scaling factor for `stable`, 10^(18 - stable.decimals())
/// @param riskyPerLiquidity Unsigned 256-bit integer of Pool's risky reserves *per liquidity*, 0 <= x <= 1
/// @param strike Unsigned 256-bit integer value with precision equal to 10^(18 - scaleFactorStable)
/// @param sigma Volatility of the Pool as an unsigned 256-bit integer w/ precision of 1e4, 10000 = 100%
/// @param tau Time until expiry in seconds as an unsigned 256-bit integer
/// @return stablePerLiquidity = K*CDF(CDF^-1(1 - riskyPerLiquidity) - sigma*sqrt(tau)) + invariantLastX64 as uint
function getStableGivenRisky(
int128 invariantLastX64,
uint256 scaleFactorRisky,
uint256 scaleFactorStable,
uint256 riskyPerLiquidity,
uint256 strike,
uint256 sigma,
uint256 tau
) internal pure returns (uint256 stablePerLiquidity) {
int128 strikeX64 = strike.scaleToX64(scaleFactorStable);
int128 riskyX64 = riskyPerLiquidity.scaleToX64(scaleFactorRisky); // mul by 2^64, div by precision
int128 oneMinusRiskyX64 = ONE_INT.sub(riskyX64);
if (tau != 0) {
int128 volX64 = getProportionalVolatility(sigma, tau);
int128 phi = oneMinusRiskyX64.getInverseCDF();
int128 input = phi.sub(volX64);
int128 stableX64 = strikeX64.mul(input.getCDF()).add(invariantLastX64);
stablePerLiquidity = stableX64.scaleFromX64(scaleFactorStable);
} else {
stablePerLiquidity = (strikeX64.mul(oneMinusRiskyX64).add(invariantLastX64)).scaleFromX64(
scaleFactorStable
);
}
}
/// @notice Calculates the invariant of a curve
/// @dev Per unit of replication, aka per unit of liquidity
/// @param scaleFactorRisky Unsigned 256-bit integer scaling factor for `risky`, 10^(18 - risky.decimals())
/// @param scaleFactorStable Unsigned 256-bit integer scaling factor for `stable`, 10^(18 - stable.decimals())
/// @param riskyPerLiquidity Unsigned 256-bit integer of Pool's risky reserves *per liquidity*, 0 <= x <= 1
/// @param stablePerLiquidity Unsigned 256-bit integer of Pool's stable reserves *per liquidity*, 0 <= x <= strike
/// @return invariantX64 = stablePerLiquidity - K * CDF(CDF^-1(1 - riskyPerLiquidity) - sigma * sqrt(tau))
function calcInvariant(
uint256 scaleFactorRisky,
uint256 scaleFactorStable,
uint256 riskyPerLiquidity,
uint256 stablePerLiquidity,
uint256 strike,
uint256 sigma,
uint256 tau
) internal pure returns (int128 invariantX64) {
uint256 output = getStableGivenRisky(
0,
scaleFactorRisky,
scaleFactorStable,
riskyPerLiquidity,
strike,
sigma,
tau
);
int128 outputX64 = output.scaleToX64(scaleFactorStable);
int128 stableX64 = stablePerLiquidity.scaleToX64(scaleFactorStable);
invariantX64 = stableX64.sub(outputX64);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
import "./SafeCast.sol";
/// @title Reserves Library
/// @author Primitive
/// @dev Data structure library for an Engine's Reserves
library Reserve {
using SafeCast for uint256;
/// @notice Stores global state of a pool
/// @param reserveRisky Risky token reserve
/// @param reserveStable Stable token reserve
/// @param liquidity Total supply of liquidity
/// @param blockTimestamp Last timestamp of which updated the accumulators
/// @param cumulativeRisky Cumulative sum of the risky reserves
/// @param cumulativeStable Cumulative sum of stable reserves
/// @param cumulativeLiquidity Cumulative sum of total liquidity supply
struct Data {
uint128 reserveRisky;
uint128 reserveStable;
uint128 liquidity;
uint32 blockTimestamp;
uint256 cumulativeRisky;
uint256 cumulativeStable;
uint256 cumulativeLiquidity;
}
/// @notice Adds to the cumulative reserves
/// @dev Overflow is desired on the cumulative values
/// @param res Reserve storage to update
/// @param blockTimestamp Checkpoint timestamp of update
function update(Data storage res, uint32 blockTimestamp) internal {
uint32 deltaTime = blockTimestamp - res.blockTimestamp;
// overflow is desired
if (deltaTime != 0) {
unchecked {
res.cumulativeRisky += uint256(res.reserveRisky) * deltaTime;
res.cumulativeStable += uint256(res.reserveStable) * deltaTime;
res.cumulativeLiquidity += uint256(res.liquidity) * deltaTime;
}
res.blockTimestamp = blockTimestamp;
}
}
/// @notice Increases one reserve value and decreases the other
/// @param reserve Reserve state to update
/// @param riskyForStable Direction of swap
/// @param deltaIn Amount of tokens paid, increases one reserve by
/// @param deltaOut Amount of tokens sent out, decreases the other reserve by
/// @param blockTimestamp Timestamp used to update cumulative reserves
function swap(
Data storage reserve,
bool riskyForStable,
uint256 deltaIn,
uint256 deltaOut,
uint32 blockTimestamp
) internal {
update(reserve, blockTimestamp);
if (riskyForStable) {
reserve.reserveRisky += deltaIn.toUint128();
reserve.reserveStable -= deltaOut.toUint128();
} else {
reserve.reserveRisky -= deltaOut.toUint128();
reserve.reserveStable += deltaIn.toUint128();
}
}
/// @notice Add to both reserves and total supply of liquidity
/// @param reserve Reserve storage to manipulate
/// @param delRisky Amount of risky tokens to add to the reserve
/// @param delStable Amount of stable tokens to add to the reserve
/// @param delLiquidity Amount of liquidity created with the provided tokens
/// @param blockTimestamp Timestamp used to update cumulative reserves
function allocate(
Data storage reserve,
uint256 delRisky,
uint256 delStable,
uint256 delLiquidity,
uint32 blockTimestamp
) internal {
update(reserve, blockTimestamp);
reserve.reserveRisky += delRisky.toUint128();
reserve.reserveStable += delStable.toUint128();
reserve.liquidity += delLiquidity.toUint128();
}
/// @notice Remove from both reserves and total supply of liquidity
/// @param reserve Reserve storage to manipulate
/// @param delRisky Amount of risky tokens to remove to the reserve
/// @param delStable Amount of stable tokens to remove to the reserve
/// @param delLiquidity Amount of liquidity removed from total supply
/// @param blockTimestamp Timestamp used to update cumulative reserves
function remove(
Data storage reserve,
uint256 delRisky,
uint256 delStable,
uint256 delLiquidity,
uint32 blockTimestamp
) internal {
update(reserve, blockTimestamp);
reserve.reserveRisky -= delRisky.toUint128();
reserve.reserveStable -= delStable.toUint128();
reserve.liquidity -= delLiquidity.toUint128();
}
/// @notice Calculates risky and stable token amounts of `delLiquidity`
/// @param reserve Reserve in memory to use reserves and liquidity of
/// @param delLiquidity Amount of liquidity to fetch underlying tokens of
/// @return delRisky Amount of risky tokens controlled by `delLiquidity`
/// @return delStable Amount of stable tokens controlled by `delLiquidity`
function getAmounts(Data memory reserve, uint256 delLiquidity)
internal
pure
returns (uint256 delRisky, uint256 delStable)
{
uint256 liq = uint256(reserve.liquidity);
delRisky = (delLiquidity * uint256(reserve.reserveRisky)) / liq;
delStable = (delLiquidity * uint256(reserve.reserveStable)) / liq;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
/// @title SafeCast
/// @notice Safely cast between uint256 and uint128
library SafeCast {
/// @notice reverts if x > type(uint128).max
function toUint128(uint256 x) internal pure returns (uint128 z) {
require(x <= type(uint128).max);
z = uint128(x);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.6.0;
import "../interfaces/IERC20.sol";
/// @title Transfers
library Transfers {
/// @notice Performs an ERC20 `transfer` call and checks return data
/// @param token ERC20 token to transfer
/// @param to Recipient of the ERC20 token
/// @param value Amount of ERC20 to transfer
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
(bool success, bytes memory returnData) = address(token).call(
abi.encodeWithSelector(token.transfer.selector, to, value)
);
require(success && (returnData.length == 0 || abi.decode(returnData, (bool))), "Transfer fail");
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.0;
import "./ABDKMath64x64.sol";
/// @title Units library
/// @author Primitive
/// @notice Utility functions for unit conversions
library Units {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
uint256 internal constant YEAR = 31556952; // 365.24219 ephemeris day = 1 year, in seconds
uint256 internal constant PRECISION = 1e18; // precision to scale to
uint256 internal constant PERCENTAGE = 1e4; // precision of percentages
// ===== Unit Conversion =====
/// @notice Scales a wei value to a precision of 1e18 using the scaling factor
/// @param value Unsigned 256-bit wei amount to convert with native decimals
/// @param factor Scaling factor to multiply by, i.e. 10^(18 - value.decimals())
/// @return y Unsigned 256-bit wei amount scaled to a precision of 1e18
function scaleUp(uint256 value, uint256 factor) internal pure returns (uint256 y) {
y = value * factor;
}
/// @notice Scales a wei value from a precision of 1e18 to 10^(18 - precision)
/// @param value Unsigned 256-bit wei amount with 18 decimals
/// @param factor Scaling factor to divide by, i.e. 10^(18 - value.decimals())
/// @return y Unsigned 256-bit wei amount scaled to 10^(18 - factor)
function scaleDown(uint256 value, uint256 factor) internal pure returns (uint256 y) {
y = value / factor;
}
/// @notice Converts unsigned 256-bit wei value into a fixed point 64.64 number
/// @param value Unsigned 256-bit wei amount, in native precision
/// @param factor Scaling factor for `value`, used to calculate decimals of `value`
/// @return y Signed 64.64 fixed point number scaled from native precision
function scaleToX64(uint256 value, uint256 factor) internal pure returns (int128 y) {
uint256 scaleFactor = PRECISION / factor;
y = value.divu(scaleFactor);
}
/// @notice Converts signed fixed point 64.64 number into unsigned 256-bit wei value
/// @param value Signed fixed point 64.64 number to convert from precision of 10^18
/// @param factor Scaling factor for `value`, used to calculate decimals of `value`
/// @return y Unsigned 256-bit wei amount scaled to native precision of 10^(18 - factor)
function scaleFromX64(int128 value, uint256 factor) internal pure returns (uint256 y) {
uint256 scaleFactor = PRECISION / factor;
y = value.mulu(scaleFactor);
}
/// @notice Converts denormalized percentage integer to a fixed point 64.64 number
/// @dev Convert unsigned 256-bit integer number into signed 64.64 fixed point number
/// @param denorm Unsigned percentage integer with precision of 1e4
/// @return Signed 64.64 fixed point percentage with precision of 1e4
function percentageToX64(uint256 denorm) internal pure returns (int128) {
return denorm.divu(PERCENTAGE);
}
/// @notice Converts unsigned seconds integer into years as a signed 64.64 fixed point number
/// @dev Convert unsigned 256-bit integer number into signed 64.64 fixed point number
/// @param s Unsigned 256-bit integer amount of seconds to convert into year units
/// @return Fixed point 64.64 number of years equal to `seconds`
function toYears(uint256 s) internal pure returns (int128) {
return s.divu(YEAR);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
/// @title Primitive Create Callback
/// @author Primitive
interface IPrimitiveCreateCallback {
/// @notice Triggered when creating a new pool for an Engine
/// @param delRisky Amount of risky tokens required to initialize risky reserve
/// @param delStable Amount of stable tokens required to initialize stable reserve
/// @param data Calldata passed on create function call
function createCallback(
uint256 delRisky,
uint256 delStable,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
/// @title Primitive Deposit Callback
/// @author Primitive
interface IPrimitiveDepositCallback {
/// @notice Triggered when depositing tokens to an Engine
/// @param delRisky Amount of risky tokens required to deposit to risky margin balance
/// @param delStable Amount of stable tokens required to deposit to stable margin balance
/// @param data Calldata passed on deposit function call
function depositCallback(
uint256 delRisky,
uint256 delStable,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
/// @title Primitive Liquidity Callback
/// @author Primitive
interface IPrimitiveLiquidityCallback {
/// @notice Triggered when providing liquidity to an Engine
/// @param delRisky Amount of risky tokens required to provide to risky reserve
/// @param delStable Amount of stable tokens required to provide to stable reserve
/// @param data Calldata passed on allocate function call
function allocateCallback(
uint256 delRisky,
uint256 delStable,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
/// @title Primitive Swap Callback
/// @author Primitive
interface IPrimitiveSwapCallback {
/// @notice Triggered when swapping tokens in an Engine
/// @param delRisky Amount of risky tokens required to pay the swap with
/// @param delStable Amount of stable tokens required to pay the swap with
/// @param data Calldata passed on swap function call
function swapCallback(
uint256 delRisky,
uint256 delStable,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
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);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.4;
import "./engine/IPrimitiveEngineActions.sol";
import "./engine/IPrimitiveEngineEvents.sol";
import "./engine/IPrimitiveEngineView.sol";
import "./engine/IPrimitiveEngineErrors.sol";
/// @title Primitive Engine Interface
interface IPrimitiveEngine is
IPrimitiveEngineActions,
IPrimitiveEngineEvents,
IPrimitiveEngineView,
IPrimitiveEngineErrors
{
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.4;
/// @title Primitive Factory Interface
/// @author Primitive
interface IPrimitiveFactory {
/// @notice Created a new engine contract!
/// @param from Calling `msg.sender` of deploy
/// @param risky Risky token of Engine to deploy
/// @param stable Stable token of Engine to deploy
/// @param engine Deployed engine address
event DeployEngine(address indexed from, address indexed risky, address indexed stable, address engine);
/// @notice Deploys a new Engine contract and sets the `getEngine` mapping for the tokens
/// @param risky Risky token, the underlying token
/// @param stable Stable token, the quote token
function deploy(address risky, address stable) external returns (address engine);
// ===== View =====
/// @notice Used to scale the minimum amount of liquidity to lowest precision
/// @dev E.g. if the lowest decimal token is 6, min liquidity w/ 18 decimals
/// cannot be 1000 wei, therefore the token decimals
/// divided by the min liquidity factor is the amount of minimum liquidity
/// MIN_LIQUIDITY = 10 ^ (Decimals / MIN_LIQUIDITY_FACTOR)
function MIN_LIQUIDITY_FACTOR() external pure returns (uint256);
/// @notice Called within Engine constructor so Engine can set immutable
/// variables without constructor args
/// @return factory Smart contract deploying the Engine contract
/// @return risky Risky token
/// @return stable Stable token
/// @return scaleFactorRisky Scale factor of the risky token, 10^(18 - riskyTokenDecimals)
/// @return scaleFactorStable Scale factor of the stable token, 10^(18 - stableTokenDecimals)
/// @return minLiquidity Minimum amount of liquidity on pool creation
function args()
external
view
returns (
address factory,
address risky,
address stable,
uint256 scaleFactorRisky,
uint256 scaleFactorStable,
uint256 minLiquidity
);
/// @notice Fetches engine address of a token pair which has been deployed from this factory
/// @param risky Risky token, the underlying token
/// @param stable Stable token, the quote token
/// @return engine Engine address for a risky and stable token
function getEngine(address risky, address stable) external view returns (address engine);
/// @notice Deployer does not have any access controls to wield
/// @return Deployer of this factory contract
function deployer() external view returns (address);
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt(int256 x) internal pure returns (int128) {
unchecked {
require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt(int128 x) internal pure returns (int64) {
unchecked {
return int64(x >> 64);
}
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
unchecked {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(int256(x << 64));
}
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt(int128 x) internal pure returns (uint64) {
unchecked {
require(x >= 0);
return uint64(uint128(x >> 64));
}
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128(int256 x) internal pure returns (int128) {
unchecked {
int256 result = x >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128(int128 x) internal pure returns (int256) {
unchecked {
return int256(x) << 64;
}
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) + y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) - y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = (int256(x) * y) >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli(int128 x, int256 y) internal pure returns (int256) {
unchecked {
if (x == MIN_64x64) {
require(
y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000
);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu(x, uint256(y));
if (negativeResult) {
require(absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256(absoluteResult);
}
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu(int128 x, uint256 y) internal pure returns (uint256) {
unchecked {
if (y == 0) return 0;
require(x >= 0);
uint256 lo = (uint256(int256(x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256(int256(x)) * (y >> 128);
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div(int128 x, int128 y) internal pure returns (int128) {
unchecked {
require(y != 0);
int256 result = (int256(x) << 64) / y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi(int256 x, int256 y) internal pure returns (int128) {
unchecked {
require(y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu(uint256(x), uint256(y));
if (negativeResult) {
require(absoluteResult <= 0x80000000000000000000000000000000);
return -int128(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(absoluteResult); // We rely on overflow behavior here
}
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu(uint256 x, uint256 y) internal pure returns (int128) {
unchecked {
require(y != 0);
uint128 result = divuu(x, y);
require(result <= uint128(MAX_64x64));
return int128(result);
}
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg(int128 x) internal pure returns (int128) {
unchecked {
require(x != MIN_64x64);
return -x;
}
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs(int128 x) internal pure returns (int128) {
unchecked {
require(x != MIN_64x64);
return x < 0 ? -x : x;
}
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv(int128 x) internal pure returns (int128) {
unchecked {
require(x != 0);
int256 result = int256(0x100000000000000000000000000000000) / x;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg(int128 x, int128 y) internal pure returns (int128) {
unchecked {
return int128((int256(x) + int256(y)) >> 1);
}
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 m = int256(x) * int256(y);
require(m >= 0);
require(m < 0x4000000000000000000000000000000000000000000000000000000000000000);
return int128(sqrtu(uint256(m)));
}
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow(int128 x, uint256 y) internal pure returns (int128) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128(x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x2 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x4 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x8 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) {
absX <<= 32;
absXShift -= 32;
}
if (absX < 0x10000000000000000000000000000) {
absX <<= 16;
absXShift -= 16;
}
if (absX < 0x1000000000000000000000000000000) {
absX <<= 8;
absXShift -= 8;
}
if (absX < 0x10000000000000000000000000000000) {
absX <<= 4;
absXShift -= 4;
}
if (absX < 0x40000000000000000000000000000000) {
absX <<= 2;
absXShift -= 2;
}
if (absX < 0x80000000000000000000000000000000) {
absX <<= 1;
absXShift -= 1;
}
uint256 resultShift = 0;
while (y != 0) {
require(absXShift < 64);
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = (absX * absX) >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require(resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256(absResult) : int256(absResult);
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt(int128 x) internal pure returns (int128) {
unchecked {
require(x >= 0);
return int128(sqrtu(uint256(int256(x)) << 64));
}
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2(int128 x) internal pure returns (int128) {
unchecked {
require(x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256(int256(x)) << uint256(127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln(int128 x) internal pure returns (int128) {
unchecked {
require(x > 0);
return int128(int256((uint256(int256(log_2(x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128));
}
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2(int128 x) internal pure returns (int128) {
unchecked {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128;
if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128;
if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128;
if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128;
if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128;
if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128;
if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128;
if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128;
if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128;
if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128;
if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128;
if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128;
if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128;
result >>= uint256(int256(63 - (x >> 64)));
require(result <= uint256(int256(MAX_64x64)));
return int128(int256(result));
}
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp(int128 x) internal pure returns (int128) {
unchecked {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2(int128((int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128));
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu(uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require(y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert(xh == hi >> 128);
result += xl / y;
}
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128(result);
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu(uint256 x) private pure returns (uint128) {
unchecked {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128(r < r1 ? r : r1);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.4;
import "./ABDKMath64x64.sol";
/// @title Cumulative Normal Distribution Math Library
/// @author Primitive
library CumulativeNormalDistribution {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
/// @notice Thrown on passing an arg that is out of the input range for these math functions
error InverseOutOfBounds(int128 value);
int128 public constant ONE_INT = 0x10000000000000000;
int128 public constant TWO_INT = 0x20000000000000000;
int128 public constant CDF0 = 0x53dd02a4f5ee2e46;
int128 public constant CDF1 = 0x413c831bb169f874;
int128 public constant CDF2 = -0x48d4c730f051a5fe;
int128 public constant CDF3 = 0x16a09e667f3bcc908;
int128 public constant CDF4 = -0x17401c57014c38f14;
int128 public constant CDF5 = 0x10fb844255a12d72e;
/// @notice Uses Abramowitz and Stegun approximation:
/// https://en.wikipedia.org/wiki/Abramowitz_and_Stegun
/// @dev Maximum error: 3.15x10-3
/// @return Standard Normal Cumulative Distribution Function of `x`
function getCDF(int128 x) internal pure returns (int128) {
int128 z = x.div(CDF3);
int128 t = ONE_INT.div(ONE_INT.add(CDF0.mul(z.abs())));
int128 erf = getErrorFunction(z, t);
if (z < 0) {
erf = erf.neg();
}
int128 result = (HALF_INT).mul(ONE_INT.add(erf));
return result;
}
/// @notice Uses Abramowitz and Stegun approximation:
/// https://en.wikipedia.org/wiki/Error_function
/// @dev Maximum error: 1.5×10−7
/// @return Error Function for approximating the Standard Normal CDF
function getErrorFunction(int128 z, int128 t) internal pure returns (int128) {
int128 step1 = t.mul(CDF3.add(t.mul(CDF4.add(t.mul(CDF5)))));
int128 step2 = CDF1.add(t.mul(CDF2.add(step1)));
int128 result = ONE_INT.sub(t.mul(step2.mul((z.mul(z).neg()).exp())));
return result;
}
int128 public constant HALF_INT = 0x8000000000000000;
int128 public constant INVERSE0 = 0x26A8F3C1F21B336E;
int128 public constant INVERSE1 = -0x87C57E5DA70D3C90;
int128 public constant INVERSE2 = 0x15D71F5721242C787;
int128 public constant INVERSE3 = 0x21D0A04B0E9B94F1;
int128 public constant INVERSE4 = -0xC2BF5D74C724E53F;
int128 public constant LOW_TAIL = 0x666666666666666; // 0.025
int128 public constant HIGH_TAIL = 0xF999999999999999; // 0.975
/// @notice Returns the inverse CDF, or quantile function of `p`.
/// @dev Source: https://arxiv.org/pdf/1002.0567.pdf
/// Maximum error of central region is 1.16x10−4
/// @return fcentral(p) = q * (a2 + (a1r + a0) / (r^2 + b1r +b0))
function getInverseCDF(int128 p) internal pure returns (int128) {
if (p >= ONE_INT || p <= 0) revert InverseOutOfBounds(p);
// Short circuit for the central region, central region inclusive of tails
if (p <= HIGH_TAIL && p >= LOW_TAIL) {
return central(p);
} else if (p < LOW_TAIL) {
return tail(p);
} else {
int128 negativeTail = -tail(ONE_INT.sub(p));
return negativeTail;
}
}
/// @dev Maximum error: 1.16x10−4
/// @return Inverse CDF around the central area of 0.025 <= p <= 0.975
function central(int128 p) internal pure returns (int128) {
int128 q = p.sub(HALF_INT);
int128 r = q.mul(q);
int128 result = q.mul(
INVERSE2.add((INVERSE1.mul(r).add(INVERSE0)).div((r.mul(r).add(INVERSE4.mul(r)).add(INVERSE3))))
);
return result;
}
int128 public constant C0 = 0x10E56D75CE8BCE9FAE;
int128 public constant C1 = -0x2CB2447D36D513DAE;
int128 public constant C2 = -0x8BB4226952BD69EDF;
int128 public constant C3 = -0x1000BF627FA188411;
int128 public constant C0_D = 0x10AEAC93F55267A9A5;
int128 public constant C1_D = 0x41ED34A2561490236;
int128 public constant C2_D = 0x7A1E70F720ECA43;
int128 public constant D0 = 0x72C7D592D021FB1DB;
int128 public constant D1 = 0x8C27B4617F5F800EA;
/// @dev Maximum error: 2.458x10-5
/// @return Inverse CDF of the tail, defined for p < 0.0465, used with p < 0.025
function tail(int128 p) internal pure returns (int128) {
int128 r = ONE_INT.div(p.mul(p)).ln().sqrt();
int128 step0 = C3.mul(r).add(C2_D);
int128 numerator = C1_D.mul(r).add(C0_D);
int128 denominator = r.mul(r).add(D1.mul(r)).add(D0);
int128 result = step0.add(numerator.div(denominator));
return result;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
/// @title Action functions for the Primitive Engine contract
/// @author Primitive
interface IPrimitiveEngineActions {
// ===== Pool Updates =====
/// @notice Updates the time until expiry of the pool by setting its last timestamp value
/// @param poolId Keccak256 hash of engine address, strike, sigma, maturity, and gamma
/// @return lastTimestamp Timestamp loaded into the state of the pool's Calibration.lastTimestamp
function updateLastTimestamp(bytes32 poolId) external returns (uint32 lastTimestamp);
/// @notice Initializes a curve with parameters in the `calibrations` storage mapping in the Engine
/// @param strike Marginal price of the pool's risky token at maturity, with the same decimals as the stable token, valid [0, 2^128-1]
/// @param sigma AKA Implied Volatility in basis points, determines the price impact of swaps, valid for (1, 10_000_000)
/// @param maturity Timestamp which starts the BUFFER countdown until swaps will cease, in seconds, valid for (block.timestamp, 2^32-1]
/// @param gamma Multiplied against swap in amounts to apply fee, equal to 1 - fee % but units are in basis points, valid for (9_000, 10_000)
/// @param riskyPerLp Risky reserve per liq. with risky decimals, = 1 - N(d1), d1 = (ln(S/K)+(r*σ^2/2))/σ√τ, valid for [0, 1e^(risky token decimals))
/// @param delLiquidity Amount of liquidity units to allocate to the curve, wei value with 18 decimals of precision
/// @param data Arbitrary data that is passed to the createCallback function
/// @return poolId Keccak256 hash of engine address, strike, sigma, maturity, and gamma
/// @return delRisky Total amount of risky tokens provided to reserves
/// @return delStable Total amount of stable tokens provided to reserves
function create(
uint128 strike,
uint32 sigma,
uint32 maturity,
uint32 gamma,
uint256 riskyPerLp,
uint256 delLiquidity,
bytes calldata data
)
external
returns (
bytes32 poolId,
uint256 delRisky,
uint256 delStable
);
// ===== Margin ====
/// @notice Adds risky and/or stable tokens to a `recipient`'s internal balance account
/// @param recipient Recipient margin account of the deposited tokens
/// @param delRisky Amount of risky tokens to deposit
/// @param delStable Amount of stable tokens to deposit
/// @param data Arbitrary data that is passed to the depositCallback function
function deposit(
address recipient,
uint256 delRisky,
uint256 delStable,
bytes calldata data
) external;
/// @notice Removes risky and/or stable tokens from a `msg.sender`'s internal balance account
/// @param recipient Address that tokens are transferred to
/// @param delRisky Amount of risky tokens to withdraw
/// @param delStable Amount of stable tokens to withdraw
function withdraw(
address recipient,
uint256 delRisky,
uint256 delStable
) external;
// ===== Liquidity =====
/// @notice Allocates risky and stable tokens to a specific curve with `poolId`
/// @param poolId Keccak256 hash of engine address, strike, sigma, maturity, and gamma
/// @param recipient Address to give the allocated liquidity to
/// @param delRisky Amount of risky tokens to add
/// @param delStable Amount of stable tokens to add
/// @param fromMargin Whether the `msg.sender` pays with their margin balance, or must send tokens
/// @param data Arbitrary data that is passed to the allocateCallback function
/// @return delLiquidity Amount of liquidity given to `recipient`
function allocate(
bytes32 poolId,
address recipient,
uint256 delRisky,
uint256 delStable,
bool fromMargin,
bytes calldata data
) external returns (uint256 delLiquidity);
/// @notice Unallocates risky and stable tokens from a specific curve with `poolId`
/// @param poolId Keccak256 hash of engine address, strike, sigma, maturity, and gamma
/// @param delLiquidity Amount of liquidity to remove
/// @return delRisky Amount of risky tokens received from removed liquidity
/// @return delStable Amount of stable tokens received from removed liquidity
function remove(bytes32 poolId, uint256 delLiquidity) external returns (uint256 delRisky, uint256 delStable);
// ===== Swaps =====
/// @notice Swaps between `risky` and `stable` tokens
/// @param recipient Address that receives output token `deltaOut` amount
/// @param poolId Keccak256 hash of engine address, strike, sigma, maturity, and gamma
/// @param riskyForStable If true, swap risky to stable, else swap stable to risky
/// @param deltaIn Amount of tokens to swap in
/// @param deltaOut Amount of tokens to swap out
/// @param fromMargin Whether the `msg.sender` uses their margin balance, or must send tokens
/// @param toMargin Whether the `deltaOut` amount is transferred or deposited into margin
/// @param data Arbitrary data that is passed to the swapCallback function
function swap(
address recipient,
bytes32 poolId,
bool riskyForStable,
uint256 deltaIn,
uint256 deltaOut,
bool fromMargin,
bool toMargin,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
/// @title Events of the Primitive Engine contract
/// @author Primitive
interface IPrimitiveEngineEvents {
/// @notice Creates a pool with liquidity
/// @dev Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
/// @param from Calling `msg.sender` of the create function
/// @param strike Marginal price of the pool's risky token at maturity, with the same decimals as the stable token, valid [0, 2^128-1]
/// @param sigma AKA Implied Volatility in basis points, determines the price impact of swaps, valid for (1, 10_000_000)
/// @param maturity Timestamp which starts the BUFFER countdown until swaps will cease, in seconds, valid for (block.timestamp, 2^32-1]
/// @param gamma Multiplied against swap in amounts to apply fee, equal to 1 - fee % but units are in basis points, valid for (9000, 10_000)
/// @param delRisky Amount of risky tokens deposited
/// @param delStable Amount of stable tokens deposited
/// @param delLiquidity Amount of liquidity granted to `recipient`
event Create(
address indexed from,
uint128 strike,
uint32 sigma,
uint32 indexed maturity,
uint32 indexed gamma,
uint256 delRisky,
uint256 delStable,
uint256 delLiquidity
);
/// @notice Updates the time until expiry of the pool with `poolId`
/// @param poolId Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
event UpdateLastTimestamp(bytes32 indexed poolId);
// ===== Margin ====
/// @notice Added stable and/or risky tokens to a margin account
/// @param from Method caller `msg.sender`
/// @param recipient Margin account recieving deposits
/// @param delRisky Amount of risky tokens deposited
/// @param delStable Amount of stable tokens deposited
event Deposit(address indexed from, address indexed recipient, uint256 delRisky, uint256 delStable);
/// @notice Removes stable and/or risky from a margin account
/// @param from Method caller `msg.sender`
/// @param recipient Address that tokens are sent to
/// @param delRisky Amount of risky tokens withdrawn
/// @param delStable Amount of stable tokens withdrawn
event Withdraw(address indexed from, address indexed recipient, uint256 delRisky, uint256 delStable);
// ===== Liquidity =====
/// @notice Adds liquidity of risky and stable tokens to a specified `poolId`
/// @param from Method caller `msg.sender`
/// @param recipient Address that receives liquidity
/// @param poolId Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
/// @param delRisky Amount of risky tokens deposited
/// @param delStable Amount of stable tokens deposited
/// @param delLiquidity Amount of liquidity granted to `recipient`
event Allocate(
address indexed from,
address indexed recipient,
bytes32 indexed poolId,
uint256 delRisky,
uint256 delStable,
uint256 delLiquidity
);
/// @notice Adds liquidity of risky and stable tokens to a specified `poolId`
/// @param from Method caller `msg.sender`
/// @param poolId Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
/// @param delRisky Amount of risky tokens deposited
/// @param delStable Amount of stable tokens deposited
/// @param delLiquidity Amount of liquidity decreased from `from`
event Remove(
address indexed from,
bytes32 indexed poolId,
uint256 delRisky,
uint256 delStable,
uint256 delLiquidity
);
// ===== Swaps =====
/// @notice Swaps between `risky` and `stable` assets
/// @param from Method caller `msg.sender`
/// @param recipient Address that receives `deltaOut` amount of tokens
/// @param poolId Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
/// @param riskyForStable If true, swaps risky to stable, else swaps stable to risky
/// @param deltaIn Amount of tokens added to reserves
/// @param deltaOut Amount of tokens removed from reserves
event Swap(
address indexed from,
address indexed recipient,
bytes32 indexed poolId,
bool riskyForStable,
uint256 deltaIn,
uint256 deltaOut
);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;
/// @title View functions of the Primitive Engine contract
/// @author Primitive
interface IPrimitiveEngineView {
// ===== View =====
/// @notice Fetches the current invariant, notation is usually `k`, based on risky and stable token reserves of pool with `poolId`
/// @param poolId Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
/// @return invariant Signed fixed point 64.64 number, invariant of `poolId`
function invariantOf(bytes32 poolId) external view returns (int128 invariant);
// ===== Constants =====
/// @return Precision units to scale to when doing token related calculations
function PRECISION() external view returns (uint256);
/// @return Amount of seconds after pool expiry which allows swaps, no swaps after buffer
function BUFFER() external view returns (uint256);
// ===== Immutables =====
/// @return Amount of liquidity burned on `create()` calls
function MIN_LIQUIDITY() external view returns (uint256);
//// @return Factory address which deployed this engine contract
function factory() external view returns (address);
//// @return Risky token address, a more accurate name is the underlying token
function risky() external view returns (address);
/// @return Stable token address, a more accurate name is the quote token
function stable() external view returns (address);
/// @return Multiplier to scale amounts to/from, equal to 10^(18 - riskyDecimals)
function scaleFactorRisky() external view returns (uint256);
/// @return Multiplier to scale amounts to/from, equal to 10^(18 - stableDecimals)
function scaleFactorStable() external view returns (uint256);
// ===== Pool State =====
/// @notice Fetches the global reserve state for a pool with `poolId`
/// @param poolId Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
/// @return reserveRisky Risky token balance in the reserve
/// @return reserveStable Stable token balance in the reserve
/// @return liquidity Total supply of liquidity for the curve
/// @return blockTimestamp Timestamp when the cumulative reserve values were last updated
/// @return cumulativeRisky Cumulative sum of risky token reserves of the previous update
/// @return cumulativeStable Cumulative sum of stable token reserves of the previous update
/// @return cumulativeLiquidity Cumulative sum of total supply of liquidity of the previous update
function reserves(bytes32 poolId)
external
view
returns (
uint128 reserveRisky,
uint128 reserveStable,
uint128 liquidity,
uint32 blockTimestamp,
uint256 cumulativeRisky,
uint256 cumulativeStable,
uint256 cumulativeLiquidity
);
/// @notice Fetches `Calibration` pool parameters
/// @param poolId Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
/// @return strike Marginal price of the pool's risky token at maturity, with the same decimals as the stable token, valid [0, 2^128-1]
/// @return sigma AKA Implied Volatility in basis points, determines the price impact of swaps, valid for (1, 10_000_000)
/// @return maturity Timestamp which starts the BUFFER countdown until swaps will cease, in seconds, valid for (block.timestamp, 2^32-1]
/// @return lastTimestamp Last timestamp used to calculate time until expiry, aka "tau"
/// @return gamma Multiplied against swap in amounts to apply fee, equal to 1 - fee % but units are in basis points, valid for (9_000, 10_000)
function calibrations(bytes32 poolId)
external
view
returns (
uint128 strike,
uint32 sigma,
uint32 maturity,
uint32 lastTimestamp,
uint32 gamma
);
/// @notice Fetches position liquidity an account address and poolId
/// @param poolId Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
/// @return liquidity Liquidity owned by `account` in `poolId`
function liquidity(address account, bytes32 poolId) external view returns (uint256 liquidity);
/// @notice Fetches the margin balances of `account`
/// @param account Margin account to fetch
/// @return balanceRisky Balance of the risky token
/// @return balanceStable Balance of the stable token
function margins(address account) external view returns (uint128 balanceRisky, uint128 balanceStable);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.4;
/// @title Errors for the Primitive Engine contract
/// @author Primitive
/// @notice Custom errors are encoded with their selector and arguments
/// @dev Peripheral smart contracts should try catch and check if data matches another custom error
interface IPrimitiveEngineErrors {
/// @notice Thrown on attempted re-entrancy on a function with a re-entrancy guard
error LockedError();
/// @notice Thrown when the balanceOf function is not successful and does not return data
error BalanceError();
/// @notice Thrown in create when a pool with computed poolId already exists
error PoolDuplicateError();
/// @notice Thrown when calling an expired pool, where block.timestamp > maturity, + BUFFER if swap
error PoolExpiredError();
/// @notice Thrown when liquidity is lower than or equal to the minimum amount of liquidity
error MinLiquidityError(uint256 value);
/// @notice Thrown when riskyPerLp is outside the range of acceptable values, 0 < riskyPerLp <= 1eRiskyDecimals
error RiskyPerLpError(uint256 value);
/// @notice Thrown when sigma is outside the range of acceptable values, 1 <= sigma <= 1e7 with 4 precision
error SigmaError(uint256 value);
/// @notice Thrown when strike is not valid, i.e. equal to 0 or greater than 2^128
error StrikeError(uint256 value);
/// @notice Thrown when gamma, equal to 1 - fee %, is outside its bounds: 9_000 <= gamma <= 10_000; 1_000 = 10% fee
error GammaError(uint256 value);
/// @notice Thrown when the parameters of a new pool are invalid, causing initial reserves to be 0
error CalibrationError(uint256 delRisky, uint256 delStable);
/// @notice Thrown when the expected risky balance is less than the actual balance
/// @param expected Expected risky balance
/// @param actual Actual risky balance
error RiskyBalanceError(uint256 expected, uint256 actual);
/// @notice Thrown when the expected stable balance is less than the actual balance
/// @param expected Expected stable balance
/// @param actual Actual stable balance
error StableBalanceError(uint256 expected, uint256 actual);
/// @notice Thrown when the pool with poolId has not been created
error UninitializedError();
/// @notice Thrown when the risky or stable amount is 0
error ZeroDeltasError();
/// @notice Thrown when the liquidity parameter is 0
error ZeroLiquidityError();
/// @notice Thrown when the deltaIn parameter is 0
error DeltaInError();
/// @notice Thrown when the deltaOut parameter is 0
error DeltaOutError();
/// @notice Thrown when the invariant check fails
/// @dev Most important check as it verifies the validity of a desired swap
/// @param invariant Pre-swap invariant updated with new tau
/// @param nextInvariant Post-swap invariant after the swap amounts are applied to reserves
error InvariantError(int128 invariant, int128 nextInvariant);
} | Add to both reserves and total supply of liquidity reserve Reserve storage to manipulate delRisky Amount of risky tokens to add to the reserve delStable Amount of stable tokens to add to the reserve delLiquidity Amount of liquidity created with the provided tokens blockTimestamp Timestamp used to update cumulative reserves | function allocate(
Data storage reserve,
uint256 delRisky,
uint256 delStable,
uint256 delLiquidity,
uint32 blockTimestamp
) internal {
update(reserve, blockTimestamp);
reserve.reserveRisky += delRisky.toUint128();
reserve.reserveStable += delStable.toUint128();
reserve.liquidity += delLiquidity.toUint128();
}
| 14,610,565 |
/**
*Submitted for verification at Etherscan.io on 2020-08-26
*/
pragma solidity ^0.5.4;
contract Account {
// The implementation of the proxy
address public implementation;
// Logic manager
address public manager;
// The enabled static calls
mapping (bytes4 => address) public enabled;
event EnabledStaticCall(address indexed module, bytes4 indexed method);
event Invoked(address indexed module, address indexed target, uint indexed value, bytes data);
event Received(uint indexed value, address indexed sender, bytes data);
event AccountInit(address indexed account);
event ManagerChanged(address indexed mgr);
modifier allowAuthorizedLogicContractsCallsOnly {
require(LogicManager(manager).isAuthorized(msg.sender), "not an authorized logic");
_;
}
/**
* @dev better to create and init account through AccountCreator.createAccount, which avoids race condition on Account.init
*/
function init(address _manager, address _accountStorage, address[] calldata _logics, address[] calldata _keys, address[] calldata _backups)
external
{
require(manager == address(0), "Account: account already initialized");
require(_manager != address(0) && _accountStorage != address(0), "Account: address is null");
manager = _manager;
for (uint i ; i < _logics.length; i++) { //inject UNINIT LOCAL/STATE VAR
address logic ; //inject UNINIT LOCAL/STATE VAR
require(LogicManager(manager).isAuthorized(logic), "must be authorized logic");
BaseLogic(logic).initAccount(this);
}
AccountStorage(_accountStorage).initAccount(this, _keys, _backups);
emit AccountInit(address(this));
}
/**
* @dev Account calls an external target contract.
* @param _target The target contract address.
* @param _value ETH value of the call.
* @param _data data of the call.
*/
function invoke(address _target, uint _value, bytes calldata _data)
external
allowAuthorizedLogicContractsCallsOnly
returns (bytes memory _res)
{
bool success;
// solium-disable-next-line security/no-call-value
(success, _res) = _target.call.value(_value)(_data);
require(success, "call to target failed");
emit Invoked(msg.sender, _target, _value, _data);
}
/**
* @dev Enables a static method by specifying the target module to which the call must be delegated.
* @param _module The target module.
* @param _method The static method signature.
*/
function enableStaticCall(address _module, bytes4 _method) external allowAuthorizedLogicContractsCallsOnly {
enabled[_method] = _module;
emit EnabledStaticCall(_module, _method);
}
/**
* @dev Reserved method to change account's manager. Normally it's unused.
* Calling this method requires adding a new authorized logic.
* @param _newMgr New logic manager.
*/
function changeManager(address _newMgr) external allowAuthorizedLogicContractsCallsOnly {
require(_newMgr != address(0), "address cannot be null");
require(_newMgr != manager, "already changed");
manager = _newMgr;
emit ManagerChanged(_newMgr);
}
/**
* @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to
* implement specific static methods. It delegates the static call to a target contract if the data corresponds
* to an enabled method, or logs the call otherwise.
*/
function() external payable {
if(msg.data.length > 0) {
address logic ; //inject UNINIT LOCAL/STATE VAR
if(logic == address(0)) {
emit Received(msg.value, msg.sender, msg.data);
}
else {
require(LogicManager(manager).isAuthorized(logic), "must be an authorized logic for static call");
// solium-disable-next-line security/no-inline-assembly
assembly {
calldatacopy(0, 0, calldatasize())
let result := staticcall(gas, logic, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
}
}
contract Owned {
// The owner
address public owner;
event OwnerChanged(address indexed _newOwner);
/**
* @dev Throws if the sender is not the owner.
*/
modifier onlyOwner {
require(msg.sender == owner, "Must be owner");
_;
}
constructor() public {
owner = msg.sender;
}
/**
* @dev Lets the owner transfer ownership of the contract to a new owner.
* @param _newOwner The new owner.
*/
function changeOwner(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "Address must not be null");
owner = _newOwner;
emit OwnerChanged(_newOwner);
}
}
contract LogicManager is Owned {
event UpdateLogicSubmitted(address indexed logic, bool value);
event UpdateLogicCancelled(address indexed logic);
event UpdateLogicDone(address indexed logic, bool value);
struct pending {
bool value; //True: enable a new logic; False: disable an old logic.
uint dueTime; //due time of a pending logic
}
// The authorized logic modules
mapping (address => bool) public authorized;
/*
array
index 0: AccountLogic address
1: TransferLogic address
2: DualsigsLogic address
3: DappLogic address
4: ...
*/
address[] public authorizedLogics;
// updated logics and their due time of becoming effective
mapping (address => pending) public pendingLogics;
struct pendingTime {
uint curPendingTime; //current pending time
uint nextPendingTime; //new pending time
uint dueTime; //due time of new pending time
}
pendingTime public pt;
// how many authorized logics
uint public logicCount;
constructor(address[] memory _initialLogics, uint256 _pendingTime) public
{
for (uint i ; i < _initialLogics.length; i++) { //inject UNINIT LOCAL/STATE VAR
address logic ; //inject UNINIT LOCAL/STATE VAR
authorized[logic] = true;
logicCount += 1;
}
authorizedLogics = _initialLogics;
pt.curPendingTime = _pendingTime;
pt.nextPendingTime = _pendingTime;
pt.dueTime = now;
}
/**
* @dev Submit a new pending time. Called only by owner.
* @param _pendingTime The new pending time.
*/
function submitUpdatePendingTime(uint _pendingTime) external onlyOwner {
pt.nextPendingTime = _pendingTime;
pt.dueTime = pt.curPendingTime + now;
}
/**
* @dev Trigger updating pending time.
*/
function triggerUpdatePendingTime() external {
require(pt.dueTime <= now, "too early to trigger updatePendingTime");
pt.curPendingTime = pt.nextPendingTime;
}
/**
* @dev check if a logic contract is authorized.
*/
function isAuthorized(address _logic) external view returns (bool) {
return authorized[_logic];
}
/**
* @dev get the authorized logic array.
*/
function getAuthorizedLogics() external view returns (address[] memory) {
return authorizedLogics;
}
/**
* @dev Submit a new logic. Called only by owner.
* @param _logic The new logic contract address.
* @param _value True: enable a new logic; False: disable an old logic.
*/
function submitUpdate(address _logic, bool _value) external onlyOwner {
pending storage p = pendingLogics[_logic];
p.value = _value;
p.dueTime = now + pt.curPendingTime;
emit UpdateLogicSubmitted(_logic, _value);
}
/**
* @dev Cancel a logic update. Called only by owner.
*/
function cancelUpdate(address _logic) external onlyOwner {
delete pendingLogics[_logic];
emit UpdateLogicCancelled(_logic);
}
/**
* @dev Trigger updating a new logic.
* @param _logic The logic contract address.
*/
function triggerUpdateLogic(address _logic) external {
pending memory p = pendingLogics[_logic];
require(p.dueTime > 0, "pending logic not found");
require(p.dueTime <= now, "too early to trigger updateLogic");
updateLogic(_logic, p.value);
delete pendingLogics[_logic];
}
/**
* @dev To update an existing logic, for example authorizedLogics[1],
* first a new logic is added to the array end, then copied to authorizedLogics[1],
* then the last logic is dropped, done.
*/
function updateLogic(address _logic, bool _value) internal {
if (authorized[_logic] != _value) {
if(_value) {
logicCount += 1;
authorized[_logic] = true;
authorizedLogics.push(_logic);
}
else {
logicCount -= 1;
require(logicCount > 0, "must have at least one logic module");
delete authorized[_logic];
removeLogic(_logic);
}
emit UpdateLogicDone(_logic, _value);
}
}
function removeLogic(address _logic) internal {
uint len ; //inject UNINIT LOCAL/STATE VAR
address lastLogic ; //inject UNINIT LOCAL/STATE VAR
if (_logic != lastLogic) {
for (uint i ; i < len; i++) { //inject UNINIT LOCAL/STATE VAR
if (_logic == authorizedLogics[i]) {
authorizedLogics[i] = lastLogic;
break;
}
}
}
authorizedLogics.length--;
}
}
contract AccountStorage {
modifier allowAccountCallsOnly(Account _account) {
require(msg.sender == address(_account), "caller must be account");
_;
}
modifier allowAuthorizedLogicContractsCallsOnly(address payable _account) {
require(LogicManager(Account(_account).manager()).isAuthorized(msg.sender), "not an authorized logic");
_;
}
struct KeyItem {
address pubKey;
uint256 status;
}
struct BackupAccount {
address backup;
uint256 effectiveDate;//means not effective until this timestamp
uint256 expiryDate;//means effective until this timestamp
}
struct DelayItem {
bytes32 hash;
uint256 dueTime;
}
struct Proposal {
bytes32 hash;
address[] approval;
}
// account => quantity of operation keys (index >= 1)
mapping (address => uint256) operationKeyCount;
// account => index => KeyItem
mapping (address => mapping(uint256 => KeyItem)) keyData;
// account => index => backup account
mapping (address => mapping(uint256 => BackupAccount)) backupData;
/* account => actionId => DelayItem
delayData applies to these 4 actions:
changeAdminKey, changeAllOperationKeys, unfreeze, changeAdminKeyByBackup
*/
mapping (address => mapping(bytes4 => DelayItem)) delayData;
// client account => proposer account => proposed actionId => Proposal
mapping (address => mapping(address => mapping(bytes4 => Proposal))) proposalData;
// *************** keyCount ********************** //
function getOperationKeyCount(address _account) external view returns(uint256) {
return operationKeyCount[_account];
}
function increaseKeyCount(address payable _account) external allowAuthorizedLogicContractsCallsOnly(_account) {
operationKeyCount[_account] = operationKeyCount[_account] + 1;
}
// *************** keyData ********************** //
function getKeyData(address _account, uint256 _index) public view returns(address) {
KeyItem memory item = keyData[_account][_index];
return item.pubKey;
}
function setKeyData(address payable _account, uint256 _index, address _key) external allowAuthorizedLogicContractsCallsOnly(_account) {
require(_key != address(0), "invalid _key value");
KeyItem storage item = keyData[_account][_index];
item.pubKey = _key;
}
// *************** keyStatus ********************** //
function getKeyStatus(address _account, uint256 _index) external view returns(uint256) {
KeyItem memory item = keyData[_account][_index];
return item.status;
}
function setKeyStatus(address payable _account, uint256 _index, uint256 _status) external allowAuthorizedLogicContractsCallsOnly(_account) {
KeyItem storage item = keyData[_account][_index];
item.status = _status;
}
// *************** backupData ********************** //
function getBackupAddress(address _account, uint256 _index) external view returns(address) {
BackupAccount memory b = backupData[_account][_index];
return b.backup;
}
function getBackupEffectiveDate(address _account, uint256 _index) external view returns(uint256) {
BackupAccount memory b = backupData[_account][_index];
return b.effectiveDate;
}
function getBackupExpiryDate(address _account, uint256 _index) external view returns(uint256) {
BackupAccount memory b = backupData[_account][_index];
return b.expiryDate;
}
function setBackup(address payable _account, uint256 _index, address _backup, uint256 _effective, uint256 _expiry)
external
allowAuthorizedLogicContractsCallsOnly(_account)
{
BackupAccount storage b = backupData[_account][_index];
b.backup = _backup;
b.effectiveDate = _effective;
b.expiryDate = _expiry;
}
function setBackupExpiryDate(address payable _account, uint256 _index, uint256 _expiry)
external
allowAuthorizedLogicContractsCallsOnly(_account)
{
BackupAccount storage b = backupData[_account][_index];
b.expiryDate = _expiry;
}
function clearBackupData(address payable _account, uint256 _index) external allowAuthorizedLogicContractsCallsOnly(_account) {
delete backupData[_account][_index];
}
// *************** delayData ********************** //
function getDelayDataHash(address payable _account, bytes4 _actionId) external view returns(bytes32) {
DelayItem memory item = delayData[_account][_actionId];
return item.hash;
}
function getDelayDataDueTime(address payable _account, bytes4 _actionId) external view returns(uint256) {
DelayItem memory item = delayData[_account][_actionId];
return item.dueTime;
}
function setDelayData(address payable _account, bytes4 _actionId, bytes32 _hash, uint256 _dueTime) external allowAuthorizedLogicContractsCallsOnly(_account) {
DelayItem storage item = delayData[_account][_actionId];
item.hash = _hash;
item.dueTime = _dueTime;
}
function clearDelayData(address payable _account, bytes4 _actionId) external allowAuthorizedLogicContractsCallsOnly(_account) {
delete delayData[_account][_actionId];
}
// *************** proposalData ********************** //
function getProposalDataHash(address _client, address _proposer, bytes4 _actionId) external view returns(bytes32) {
Proposal memory p = proposalData[_client][_proposer][_actionId];
return p.hash;
}
function getProposalDataApproval(address _client, address _proposer, bytes4 _actionId) external view returns(address[] memory) {
Proposal memory p = proposalData[_client][_proposer][_actionId];
return p.approval;
}
function setProposalData(address payable _client, address _proposer, bytes4 _actionId, bytes32 _hash, address _approvedBackup)
external
allowAuthorizedLogicContractsCallsOnly(_client)
{
Proposal storage p = proposalData[_client][_proposer][_actionId];
if (p.hash > 0) {
if (p.hash == _hash) {
for (uint256 i ; i < p.approval.length; i++) { //inject UNINIT LOCAL/STATE VAR
require(p.approval[i] != _approvedBackup, "backup already exists");
}
p.approval.push(_approvedBackup);
} else {
p.hash = _hash;
p.approval.length = 0;
}
} else {
p.hash = _hash;
p.approval.push(_approvedBackup);
}
}
function clearProposalData(address payable _client, address _proposer, bytes4 _actionId) external allowAuthorizedLogicContractsCallsOnly(_client) {
delete proposalData[_client][_proposer][_actionId];
}
// *************** init ********************** //
/**
* @dev Write account data into storage.
* @param _account The Account.
* @param _keys The initial keys.
* @param _backups The initial backups.
*/
function initAccount(Account _account, address[] calldata _keys, address[] calldata _backups)
external
allowAccountCallsOnly(_account)
{
require(getKeyData(address(_account), 0) == address(0), "AccountStorage: account already initialized!");
require(_keys.length > 0, "empty keys array");
operationKeyCount[address(_account)] = _keys.length - 1;
for (uint256 index ; index < _keys.length; index++) { //inject UNINIT LOCAL/STATE VAR
address _key ; //inject UNINIT LOCAL/STATE VAR
require(_key != address(0), "_key cannot be 0x0");
KeyItem storage item = keyData[address(_account)][index];
item.pubKey = _key;
item.status = 0;
}
// avoid backup duplication if _backups.length > 1
// normally won't check duplication, in most cases only one initial backup when initialization
if (_backups.length > 1) {
address[] memory bkps = _backups;
for (uint256 i ; i < _backups.length; i++) { //inject UNINIT LOCAL/STATE VAR
for (uint256 j ; j < i; j++) { //inject UNINIT LOCAL/STATE VAR
require(bkps[j] != _backups[i], "duplicate backup");
}
}
}
for (uint256 index ; index < _backups.length; index++) { //inject UNINIT LOCAL/STATE VAR
address _backup ; //inject UNINIT LOCAL/STATE VAR
require(_backup != address(0), "backup cannot be 0x0");
require(_backup != address(_account), "cannot be backup of oneself");
backupData[address(_account)][index] = BackupAccount(_backup, now, uint256(-1));
}
}
}
/* 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, 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 ; //inject UNINIT LOCAL/STATE VAR
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c ; //inject UNINIT LOCAL/STATE VAR
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c ; //inject UNINIT LOCAL/STATE VAR
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c ; //inject UNINIT LOCAL/STATE VAR
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
/**
* @dev Returns ceil(a / b).
*/
function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c ; //inject UNINIT LOCAL/STATE VAR
if(a % b == 0) {
return c;
}
else {
return c + 1;
}
}
}
contract BaseLogic {
bytes constant internal SIGN_HASH_PREFIX = "\x19Ethereum Signed Message:\n32";
mapping (address => uint256) keyNonce;
AccountStorage public accountStorage;
modifier allowSelfCallsOnly() {
require (msg.sender == address(this), "only internal call is allowed");
_;
}
modifier allowAccountCallsOnly(Account _account) {
require(msg.sender == address(_account), "caller must be account");
_;
}
// *************** Constructor ********************** //
constructor(AccountStorage _accountStorage) public {
accountStorage = _accountStorage;
}
// *************** Initialization ********************* //
function initAccount(Account _account) external allowAccountCallsOnly(_account){
}
// *************** Getter ********************** //
function getKeyNonce(address _key) external view returns(uint256) {
return keyNonce[_key];
}
// *************** Signature ********************** //
function getSignHash(bytes memory _data, uint256 _nonce) internal view returns(bytes32) {
// use EIP 191
// 0x1900 + this logic address + data + nonce of signing key
bytes32 msgHash ; //inject UNINIT LOCAL/STATE VAR
bytes32 prefixedHash ; //inject UNINIT LOCAL/STATE VAR
return prefixedHash;
}
function verifySig(address _signingKey, bytes memory _signature, bytes32 _signHash) internal pure {
require(_signingKey != address(0), "invalid signing key");
address recoveredAddr ; //inject UNINIT LOCAL/STATE VAR
require(recoveredAddr == _signingKey, "signature verification failed");
}
/**
* @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.
*
* NOTE: This call _does not revert_ if the signature is invalid, or
* if the signer is otherwise unable to be retrieved. In those scenarios,
* the zero address is returned.
*
* 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) {
return (address(0));
}
// 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)))
}
// 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 1 2 + 1, and for v in (282): v 1 {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);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/* get signer address from data
* @dev Gets an address encoded as the first argument in transaction data
* @param b The byte array that should have an address as first argument
* @returns a The address retrieved from the array
*/
function getSignerAddress(bytes memory _b) internal pure returns (address _a) {
require(_b.length >= 36, "invalid bytes");
// solium-disable-next-line security/no-inline-assembly
assembly {
let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
_a := and(mask, mload(add(_b, 36)))
// b = {length:32}{method sig:4}{address:32}{...}
// 36 is the offset of the first parameter of the data, if encoded properly.
// 32 bytes for the length of the bytes array, and the first 4 bytes for the function signature.
// 32 bytes is the length of the bytes array!!!!
}
}
// get method id, first 4 bytes of data
function getMethodId(bytes memory _b) internal pure returns (bytes4 _a) {
require(_b.length >= 4, "invalid data");
// solium-disable-next-line security/no-inline-assembly
assembly {
// 32 bytes is the length of the bytes array
_a := mload(add(_b, 32))
}
}
function checkKeyStatus(address _account, uint256 _index) internal view {
// check operation key status
if (_index > 0) {
require(accountStorage.getKeyStatus(_account, _index) != 1, "frozen key");
}
}
// _nonce is timestamp in microsecond(1/1000000 second)
function checkAndUpdateNonce(address _key, uint256 _nonce) internal {
require(_nonce > keyNonce[_key], "nonce too small");
require(SafeMath.div(_nonce, 1000000) <= now + 86400, "nonce too big"); // 86400=24*3600 seconds
keyNonce[_key] = _nonce;
}
}
//https://github.com/hamdiallam/Solidity-RLP/blob/master/contracts/RLPReader.sol
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr ; //inject UNINIT LOCAL/STATE VAR
uint itemLength ; //inject UNINIT LOCAL/STATE VAR
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint ptr ; //inject UNINIT LOCAL/STATE VAR
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/
function rlpLen(RLPItem memory item) internal pure returns (uint) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/
function payloadLen(RLPItem memory item) internal pure returns (uint) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint items ; //inject UNINIT LOCAL/STATE VAR
RLPItem[] memory result = new RLPItem[](items);
uint memPtr ; //inject UNINIT LOCAL/STATE VAR
uint dataLen;
for (uint i ; i < items; i++) { //inject UNINIT LOCAL/STATE VAR
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if (item.len == 0) return false;
uint8 byte0;
uint memPtr ; //inject UNINIT LOCAL/STATE VAR
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint result;
uint memPtr ; //inject UNINIT LOCAL/STATE VAR
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
require(item.len > 0 && item.len <= 33);
uint offset ; //inject UNINIT LOCAL/STATE VAR
uint len ; //inject UNINIT LOCAL/STATE VAR
uint result;
uint memPtr ; //inject UNINIT LOCAL/STATE VAR
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint) {
// one byte prefix
require(item.len == 33);
uint result;
uint memPtr ; //inject UNINIT LOCAL/STATE VAR
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
uint offset ; //inject UNINIT LOCAL/STATE VAR
uint len ; // data length //inject UNINIT LOCAL/STATE VAR
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint) {
if (item.len == 0) return 0;
uint count ; //inject UNINIT LOCAL/STATE VAR
uint currPtr ; //inject UNINIT LOCAL/STATE VAR
uint endPtr ; //inject UNINIT LOCAL/STATE VAR
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) private pure returns (uint) {
uint itemLen;
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask ; //inject UNINIT LOCAL/STATE VAR
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
contract DappLogic is BaseLogic {
using RLPReader for RLPReader.RLPItem;
using RLPReader for bytes;
/*
index 0: admin key
1: asset(transfer)
2: adding
3: reserved(dapp)
4: assist
*/
uint constant internal DAPP_KEY_INDEX = 3;
// *************** Events *************************** //
event DappLogicEntered(bytes data, uint256 indexed nonce);
// *************** Constructor ********************** //
constructor(AccountStorage _accountStorage)
BaseLogic(_accountStorage)
public
{
}
// *************** action entry ********************* //
/**
* @dev Entry method of DappLogic.
* DappLogic has 2 actions called from 'enter':
callContract, callMultiContract
*/
function enter(bytes calldata _data, bytes calldata _signature, uint256 _nonce) external {
address account ; //inject UNINIT LOCAL/STATE VAR
checkKeyStatus(account, DAPP_KEY_INDEX);
address dappKey ; //inject UNINIT LOCAL/STATE VAR
checkAndUpdateNonce(dappKey, _nonce);
bytes32 signHash ; //inject UNINIT LOCAL/STATE VAR
verifySig(dappKey, _signature, signHash);
// solium-disable-next-line security/no-low-level-calls
(bool success,) = address(this).call(_data);
require(success, "calling self failed");
emit DappLogicEntered(_data, _nonce);
}
// *************** call Dapp ********************* //
// called from 'enter'
// call other contract from base account
function callContract(address payable _account, address payable _target, uint256 _value, bytes calldata _methodData) external allowSelfCallsOnly {
bool success;
// solium-disable-next-line security/no-low-level-calls
(success,) = _account.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _target, _value, _methodData));
require(success, "calling invoke failed");
}
// called from 'enter'
// call serveral other contracts at a time
// 'bytes[]' not supported, therefore an array of _methodData is rlp encoded into rlpBytes
function callMultiContract(address payable _account, address[] calldata _targets, uint256[] calldata _values, bytes calldata _rlpBytes) external allowSelfCallsOnly {
RLPReader.RLPItem[] memory ls = _rlpBytes.toRlpItem().toList();
uint256 len ; //inject UNINIT LOCAL/STATE VAR
require(len == _values.length && len == ls.length, "length mismatch");
for (uint256 i ; i < len; i++) { //inject UNINIT LOCAL/STATE VAR
bool success;
RLPReader.RLPItem memory item = ls[i];
// solium-disable-next-line security/no-low-level-calls
(success,) = _account.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _targets[i], _values[i], bytes(item.toBytes())));
require(success, "calling invoke failed");
}
}
} | enforces 32 byte length one byte prefix | function toUintStrict(RLPItem memory item) internal pure returns (uint) {
require(item.len == 33);
uint result;
assembly {
result := mload(memPtr)
}
return result;
}
| 6,385,023 |
// File: contracts/interfaces/ILiquidationManager.sol
pragma solidity 0.6.12;
/**
* @title BiFi's liquidation manager interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface ILiquidationManager {
function setCircuitBreaker(bool _emergency) external returns (bool);
function partialLiquidation(address payable delinquentBorrower, uint256 targetHandler, uint256 liquidateAmount, uint256 receiveHandler) external returns (uint256);
function checkLiquidation(address payable userAddr) external view returns (bool);
}
// File: contracts/interfaces/IManagerSlotSetter.sol
pragma solidity 0.6.12;
/**
* @title BiFi's Manager Context Setter interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IManagerSlotSetter {
function ownershipTransfer(address payable _owner) external returns (bool);
function setOperator(address payable adminAddr, bool flag) external returns (bool);
function setOracleProxy(address oracleProxyAddr) external returns (bool);
function setRewardErc20(address erc20Addr) external returns (bool);
function setBreakerTable(address _target, bool _status) external returns (bool);
function setCircuitBreaker(bool _emergency) external returns (bool);
function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) external returns (bool);
function setLiquidationManager(address liquidationManagerAddr) external returns (bool);
function setHandlerSupport(uint256 handlerID, bool support) external returns (bool);
function setPositionStorageAddr(address _positionStorageAddr) external returns (bool);
function setNFTAddr(address _nftAddr) external returns (bool);
function setDiscountBase(uint256 handlerID, uint256 feeBase) external returns (bool);
}
// File: contracts/interfaces/IHandlerManager.sol
pragma solidity 0.6.12;
/**
* @title BiFi's Manager Interest interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IHandlerManager {
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256);
function interestUpdateReward() external returns (bool);
function updateRewardParams(address payable userAddr) external returns (bool);
function rewardClaimAll(address payable userAddr) external returns (uint256);
function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256);
function ownerRewardTransfer(uint256 _amount) external returns (bool);
}
// File: contracts/interfaces/IManagerFlashloan.sol
pragma solidity 0.6.12;
interface IManagerFlashloan {
function withdrawFlashloanFee(uint256 handlerID) external returns (bool);
function flashloan(
uint256 handlerID,
address receiverAddress,
uint256 amount,
bytes calldata params
) external returns (bool);
function getFee(uint256 handlerID, uint256 amount) external view returns (uint256);
function getFeeTotal(uint256 handlerID) external view returns (uint256);
function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmo) external view returns (uint256);
}
// File: contracts/SafeMath.sol
pragma solidity ^0.6.12;
// from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
// Subject to the MIT license.
/**
* @title BiFi's safe-math Contract
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
library SafeMath {
uint256 internal constant unifiedPoint = 10 ** 18;
/******************** Safe Math********************/
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "a");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
return _sub(a, b, "s");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mul(a, b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(a, b, "d");
}
function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0)
{
return 0;
}
uint256 c = a* b;
require((c / a) == b, "m");
return c;
}
function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, unifiedPoint), b, "d");
}
function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, b), unifiedPoint, "m");
}
}
// File: contracts/interfaces/IManagerDataStorage.sol
pragma solidity 0.6.12;
/**
* @title BiFi's manager data storage interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IManagerDataStorage {
function getGlobalRewardPerBlock() external view returns (uint256);
function setGlobalRewardPerBlock(uint256 _globalRewardPerBlock) external returns (bool);
function getGlobalRewardDecrement() external view returns (uint256);
function setGlobalRewardDecrement(uint256 _globalRewardDecrement) external returns (bool);
function getGlobalRewardTotalAmount() external view returns (uint256);
function setGlobalRewardTotalAmount(uint256 _globalRewardTotalAmount) external returns (bool);
function getAlphaRate() external view returns (uint256);
function setAlphaRate(uint256 _alphaRate) external returns (bool);
function getAlphaLastUpdated() external view returns (uint256);
function setAlphaLastUpdated(uint256 _alphaLastUpdated) external returns (bool);
function getRewardParamUpdateRewardPerBlock() external view returns (uint256);
function setRewardParamUpdateRewardPerBlock(uint256 _rewardParamUpdateRewardPerBlock) external returns (bool);
function getRewardParamUpdated() external view returns (uint256);
function setRewardParamUpdated(uint256 _rewardParamUpdated) external returns (bool);
function getInterestUpdateRewardPerblock() external view returns (uint256);
function setInterestUpdateRewardPerblock(uint256 _interestUpdateRewardPerblock) external returns (bool);
function getInterestRewardUpdated() external view returns (uint256);
function setInterestRewardUpdated(uint256 _interestRewardLastUpdated) external returns (bool);
function setTokenHandler(uint256 handlerID, address handlerAddr) external returns (bool);
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address);
function getTokenHandlerID(uint256 index) external view returns (uint256);
function getTokenHandlerAddr(uint256 handlerID) external view returns (address);
function setTokenHandlerAddr(uint256 handlerID, address handlerAddr) external returns (bool);
function getTokenHandlerExist(uint256 handlerID) external view returns (bool);
function setTokenHandlerExist(uint256 handlerID, bool exist) external returns (bool);
function getTokenHandlerSupport(uint256 handlerID) external view returns (bool);
function setTokenHandlerSupport(uint256 handlerID, bool support) external returns (bool);
function setLiquidationManagerAddr(address _liquidationManagerAddr) external returns (bool);
function getLiquidationManagerAddr() external view returns (address);
function setManagerAddr(address _managerAddr) external returns (bool);
}
// File: contracts/interfaces/IOracleProxy.sol
pragma solidity 0.6.12;
/**
* @title BiFi's oracle proxy interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IOracleProxy {
function getTokenPrice(uint256 tokenID) external view returns (uint256);
function getOracleFeed(uint256 tokenID) external view returns (address, uint256);
function setOracleFeed(uint256 tokenID, address feedAddr, uint256 decimals, bool needPriceConvert, uint256 priceConvertID) external returns (bool);
}
// File: contracts/interfaces/IERC20.sol
// from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external ;
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 ;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interfaces/IObserver.sol
pragma solidity 0.6.12;
/**
* @title BiFi's Observer interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IObserver {
function getAlphaBaseAsset() external view returns (uint256[] memory);
function setChainGlobalRewardPerblock(uint256 _idx, uint256 globalRewardPerBlocks) external returns (bool);
function updateChainMarketInfo(uint256 _idx, uint256 chainDeposit, uint256 chainBorrow) external returns (bool);
}
// File: contracts/interfaces/IProxy.sol
pragma solidity 0.6.12;
/**
* @title BiFi's proxy interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IProxy {
function handlerProxy(bytes memory data) external returns (bool, bytes memory);
function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory);
function siProxy(bytes memory data) external returns (bool, bytes memory);
function siViewProxy(bytes memory data) external view returns (bool, bytes memory);
}
// File: contracts/interfaces/IMarketHandler.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market handler interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketHandler {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setCircuitBreakWithOwner(bool _emergency) external returns (bool);
function getTokenName() external view returns (string memory);
function ownershipTransfer(address payable newOwner) external returns (bool);
function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function executeFlashloan(
address receiverAddress,
uint256 amount
) external returns (bool);
function depositFlashloanFee(
uint256 amount
) external returns (bool);
function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256);
function getTokenHandlerLimit() external view returns (uint256, uint256);
function getTokenHandlerBorrowLimit() external view returns (uint256);
function getTokenHandlerMarginCallLimit() external view returns (uint256);
function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool);
function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool);
function getTokenLiquidityAmountWithInterest(address payable userAddr) external view returns (uint256);
function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256);
function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256);
function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256);
function checkFirstAction() external returns (bool);
function applyInterest(address payable userAddr) external returns (uint256, uint256);
function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool);
function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool);
function withdrawFlashloanFee(uint256 unifiedTokenAmount) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function getSIRandBIR() external view returns (uint256, uint256);
function getERC20Addr() external view returns (address);
}
// File: contracts/interfaces/IServiceIncentive.sol
pragma solidity 0.6.12;
/**
* @title BiFi's si interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IServiceIncentive {
function setCircuitBreakWithOwner(bool emergency) external returns (bool);
function setCircuitBreaker(bool emergency) external returns (bool);
function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool);
function updateRewardLane(address payable userAddr) external returns (bool);
function getBetaRateBaseTotalAmount() external view returns (uint256);
function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256);
function getMarketRewardInfo() external view returns (uint256, uint256, uint256);
function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256);
function claimRewardAmountUser(address payable userAddr) external returns (uint256);
}
// File: contracts/Errors.sol
pragma solidity 0.6.12;
contract Modifier {
string internal constant ONLY_OWNER = "O";
string internal constant ONLY_MANAGER = "M";
string internal constant CIRCUIT_BREAKER = "emergency";
}
contract ManagerModifier is Modifier {
string internal constant ONLY_HANDLER = "H";
string internal constant ONLY_LIQUIDATION_MANAGER = "LM";
string internal constant ONLY_BREAKER = "B";
}
contract HandlerDataStorageModifier is Modifier {
string internal constant ONLY_BIFI_CONTRACT = "BF";
}
contract SIDataStorageModifier is Modifier {
string internal constant ONLY_SI_HANDLER = "SI";
}
contract HandlerErrors is Modifier {
string internal constant USE_VAULE = "use value";
string internal constant USE_ARG = "use arg";
string internal constant EXCEED_LIMIT = "exceed limit";
string internal constant NO_LIQUIDATION = "no liquidation";
string internal constant NO_LIQUIDATION_REWARD = "no enough reward";
string internal constant NO_EFFECTIVE_BALANCE = "not enough balance";
string internal constant TRANSFER = "err transfer";
}
contract SIErrors is Modifier { }
contract InterestErrors is Modifier { }
contract LiquidationManagerErrors is Modifier {
string internal constant NO_DELINQUENT = "not delinquent";
}
contract ManagerErrors is ManagerModifier {
string internal constant REWARD_TRANSFER = "RT";
string internal constant UNSUPPORTED_TOKEN = "UT";
}
contract OracleProxyErrors is Modifier {
string internal constant ZERO_PRICE = "price zero";
}
contract RequestProxyErrors is Modifier { }
contract ManagerDataStorageErrors is ManagerModifier {
string internal constant NULL_ADDRESS = "err addr null";
}
// File: contracts/marketManager/ManagerSlot.sol
pragma solidity 0.6.12;
/**
* @title BiFi's Slot contract
* @notice Manager Slot Definitions & Allocations
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
contract ManagerSlot is ManagerErrors {
using SafeMath for uint256;
address public owner;
mapping(address => bool) operators;
mapping(address => Breaker) internal breakerTable;
bool public emergency = false;
IManagerDataStorage internal dataStorageInstance;
IOracleProxy internal oracleProxy;
/* feat: manager reward token instance*/
IERC20 internal rewardErc20Instance;
IObserver public Observer;
address public slotSetterAddr;
address public handlerManagerAddr;
address public flashloanAddr;
// BiFi-X
address public positionStorageAddr;
address public nftAddr;
uint256 public tokenHandlerLength;
struct FeeRateParams {
uint256 unifiedPoint;
uint256 minimum;
uint256 slope;
uint256 discountRate;
}
struct HandlerFlashloan {
uint256 flashFeeRate;
uint256 discountBase;
uint256 feeTotal;
}
mapping(uint256 => HandlerFlashloan) public handlerFlashloan;
struct UserAssetsInfo {
uint256 depositAssetSum;
uint256 borrowAssetSum;
uint256 marginCallLimitSum;
uint256 depositAssetBorrowLimitSum;
uint256 depositAsset;
uint256 borrowAsset;
uint256 price;
uint256 callerPrice;
uint256 depositAmount;
uint256 borrowAmount;
uint256 borrowLimit;
uint256 marginCallLimit;
uint256 callerBorrowLimit;
uint256 userBorrowableAsset;
uint256 withdrawableAsset;
}
struct Breaker {
bool auth;
bool tried;
}
struct ContractInfo {
bool support;
address addr;
address tokenAddr;
uint256 expectedBalance;
uint256 afterBalance;
IProxy tokenHandler;
bytes data;
IMarketHandler handlerFunction;
IServiceIncentive siFunction;
IOracleProxy oracleProxy;
IManagerDataStorage managerDataStorage;
}
modifier onlyOwner {
require(msg.sender == owner, ONLY_OWNER);
_;
}
modifier onlyHandler(uint256 handlerID) {
_isHandler(handlerID);
_;
}
modifier onlyOperators {
address payable sender = msg.sender;
require(operators[sender] || sender == owner);
_;
}
function _isHandler(uint256 handlerID) internal view {
address msgSender = msg.sender;
require((msgSender == dataStorageInstance.getTokenHandlerAddr(handlerID)) || (msgSender == owner), ONLY_HANDLER);
}
modifier onlyLiquidationManager {
_isLiquidationManager();
_;
}
function _isLiquidationManager() internal view {
address msgSender = msg.sender;
require((msgSender == dataStorageInstance.getLiquidationManagerAddr()) || (msgSender == owner), ONLY_LIQUIDATION_MANAGER);
}
modifier circuitBreaker {
_isCircuitBreak();
_;
}
function _isCircuitBreak() internal view {
require((!emergency) || (msg.sender == owner), CIRCUIT_BREAKER);
}
modifier onlyBreaker {
_isBreaker();
_;
}
function _isBreaker() internal view {
require(breakerTable[msg.sender].auth, ONLY_BREAKER);
}
}
// File: contracts/marketManager/TokenManager.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.6.12;
/**
* @title BiFi's marketManager contract
* @notice Implement business logic and manage handlers
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
contract TokenManager is ManagerSlot {
/**
* @dev Constructor for marketManager
* @param managerDataStorageAddr The address of the manager storage contract
* @param oracleProxyAddr The address of oracle proxy contract (e.g., price feeds)
* @param breaker The address of default circuit breaker
* @param erc20Addr The address of reward token (ERC-20)
*/
constructor (address managerDataStorageAddr, address oracleProxyAddr, address _slotSetterAddr, address _handlerManagerAddr, address _flashloanAddr, address breaker, address erc20Addr) public
{
owner = msg.sender;
dataStorageInstance = IManagerDataStorage(managerDataStorageAddr);
oracleProxy = IOracleProxy(oracleProxyAddr);
rewardErc20Instance = IERC20(erc20Addr);
slotSetterAddr = _slotSetterAddr;
handlerManagerAddr = _handlerManagerAddr;
flashloanAddr = _flashloanAddr;
breakerTable[owner].auth = true;
breakerTable[breaker].auth = true;
}
/**
* @dev Transfer ownership
* @param _owner the address of the new owner
* @return result the setter call in contextSetter contract
*/
function ownershipTransfer(address payable _owner) onlyOwner public returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.ownershipTransfer.selector,
_owner
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
function setOperator(address payable adminAddr, bool flag) onlyOwner external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.setOperator.selector,
adminAddr, flag
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Set the address of OracleProxy contract
* @param oracleProxyAddr The address of OracleProxy contract
* @return result the setter call in contextSetter contract
*/
function setOracleProxy(address oracleProxyAddr) onlyOwner external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.setOracleProxy.selector,
oracleProxyAddr
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Set the address of BiFi reward token contract
* @param erc20Addr The address of BiFi reward token contract
* @return result the setter call in contextSetter contract
*/
function setRewardErc20(address erc20Addr) onlyOwner public returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.setRewardErc20.selector,
erc20Addr
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Authorize admin user for circuitBreaker
* @param _target The address of the circuitBreaker admin user.
* @param _status The boolean status of circuitBreaker (on/off)
* @return result the setter call in contextSetter contract
*/
function setBreakerTable(address _target, bool _status) onlyOwner external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.setBreakerTable.selector,
_target, _status
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Set circuitBreak to freeze/unfreeze all handlers
* @param _emergency The boolean status of circuitBreaker (on/off)
* @return result the setter call in contextSetter contract
*/
function setCircuitBreaker(bool _emergency) onlyBreaker external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.setCircuitBreaker.selector,
_emergency
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
function setPositionStorageAddr(address _positionStorageAddr) onlyOwner external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter.setPositionStorageAddr.selector,
_positionStorageAddr
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
function setNFTAddr(address _nftAddr) onlyOwner external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter.setNFTAddr.selector,
_nftAddr
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
function setDiscountBase(uint256 handlerID, uint256 feeBase) onlyOwner external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.setDiscountBase.selector,
handlerID,
feeBase
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Get the circuitBreak status
* @return The circuitBreak status
*/
function getCircuitBreaker() external view returns (bool)
{
return emergency;
}
/**
* @dev Get information for a handler
* @param handlerID Handler ID
* @return (success or failure, handler address, handler name)
*/
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory)
{
bool support;
address tokenHandlerAddr;
string memory tokenName;
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);
IProxy TokenHandler = IProxy(tokenHandlerAddr);
bytes memory data;
(, data) = TokenHandler.handlerViewProxy(
abi.encodeWithSelector(
IMarketHandler
.getTokenName.selector
)
);
tokenName = abi.decode(data, (string));
support = true;
}
return (support, tokenHandlerAddr, tokenName);
}
/**
* @dev Register a handler
* @param handlerID Handler ID and address
* @param tokenHandlerAddr The handler address
* @return result the setter call in contextSetter contract
*/
function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) onlyOwner external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.handlerRegister.selector,
handlerID, tokenHandlerAddr, flashFeeRate, discountBase
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Set a liquidation manager contract
* @param liquidationManagerAddr The address of liquidiation manager
* @return result the setter call in contextSetter contract
*/
function setLiquidationManager(address liquidationManagerAddr) onlyOwner external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.setLiquidationManager.selector,
liquidationManagerAddr
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Update the (SI) rewards for a user
* @param userAddr The address of the user
* @param callerID The handler ID
* @return true (TODO: validate results)
*/
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool)
{
ContractInfo memory handlerInfo;
(handlerInfo.support, handlerInfo.addr) = dataStorageInstance.getTokenHandlerInfo(callerID);
if (handlerInfo.support)
{
IProxy TokenHandler;
TokenHandler = IProxy(handlerInfo.addr);
TokenHandler.siProxy(
abi.encodeWithSelector(
IServiceIncentive
.updateRewardLane.selector,
userAddr
)
);
}
return true;
}
/**
* @dev Update interest of a user for a handler (internal)
* @param userAddr The user address
* @param callerID The handler ID
* @param allFlag Flag for the full calculation mode (calculting for all handlers)
* @return (uint256, uint256, uint256, uint256, uint256, uint256)
*/
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256) {
bytes memory callData = abi.encodeWithSelector(
IHandlerManager
.applyInterestHandlers.selector,
userAddr, callerID, allFlag
);
(bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (uint256, uint256, uint256, uint256, uint256, uint256));
}
/**
* @dev Reward the user (msg.sender) with the reward token after calculating interest.
* @return result the interestUpdateReward call in ManagerInterest contract
*/
function interestUpdateReward() external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IHandlerManager
.interestUpdateReward.selector
);
(result, ) = handlerManagerAddr.delegatecall(callData);
assert(result);
}
/**
* @dev (Update operation) update the rewards parameters.
* @param userAddr The address of operator
* @return result the updateRewardParams call in ManagerInterest contract
*/
function updateRewardParams(address payable userAddr) onlyOperators external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IHandlerManager
.updateRewardParams.selector,
userAddr
);
(result, ) = handlerManagerAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Claim all rewards for the user
* @param userAddr The user address
* @return true (TODO: validate results)
*/
function rewardClaimAll(address payable userAddr) external returns (uint256)
{
bytes memory callData = abi.encodeWithSelector(
IHandlerManager
.rewardClaimAll.selector,
userAddr
);
(bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (uint256));
}
/**
* @dev Claim handler rewards for the user
* @param handlerID The ID of claim reward handler
* @param userAddr The user address
* @return true (TODO: validate results)
*/
function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256) {
bytes memory callData = abi.encodeWithSelector(
IHandlerManager
.claimHandlerReward.selector,
handlerID, userAddr
);
(bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (uint256));
}
/**
* @dev Transfer reward tokens to owner (for administration)
* @param _amount The amount of the reward token
* @return result (TODO: validate results)
*/
function ownerRewardTransfer(uint256 _amount) onlyOwner external returns (bool result)
{
bytes memory callData = abi.encodeWithSelector(
IHandlerManager
.ownerRewardTransfer.selector,
_amount
);
(result, ) = handlerManagerAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Get the token price of the handler
* @param handlerID The handler ID
* @return The token price of the handler
*/
function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256)
{
return _getTokenHandlerPrice(handlerID);
}
/**
* @dev Get the margin call limit of the handler (external)
* @param handlerID The handler ID
* @return The margin call limit
*/
function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256)
{
return _getTokenHandlerMarginCallLimit(handlerID);
}
/**
* @dev Get the margin call limit of the handler (internal)
* @param handlerID The handler ID
* @return The margin call limit
*/
function _getTokenHandlerMarginCallLimit(uint256 handlerID) internal view returns (uint256)
{
IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID));
bytes memory data;
(, data) = TokenHandler.handlerViewProxy(
abi.encodeWithSelector(
IMarketHandler
.getTokenHandlerMarginCallLimit.selector
)
);
return abi.decode(data, (uint256));
}
/**
* @dev Get the borrow limit of the handler (external)
* @param handlerID The handler ID
* @return The borrow limit
*/
function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256)
{
return _getTokenHandlerBorrowLimit(handlerID);
}
/**
* @dev Get the borrow limit of the handler (internal)
* @param handlerID The handler ID
* @return The borrow limit
*/
function _getTokenHandlerBorrowLimit(uint256 handlerID) internal view returns (uint256)
{
IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID));
bytes memory data;
(, data) = TokenHandler.handlerViewProxy(
abi.encodeWithSelector(
IMarketHandler
.getTokenHandlerBorrowLimit.selector
)
);
return abi.decode(data, (uint256));
}
/**
* @dev Get the handler status of whether the handler is supported or not.
* @param handlerID The handler ID
* @return Whether the handler is supported or not
*/
function getTokenHandlerSupport(uint256 handlerID) external view returns (bool)
{
return dataStorageInstance.getTokenHandlerSupport(handlerID);
}
/**
* @dev Set the length of the handler list
* @param _tokenHandlerLength The length of the handler list
* @return true (TODO: validate results)
*/
function setTokenHandlersLength(uint256 _tokenHandlerLength) onlyOwner external returns (bool)
{
tokenHandlerLength = _tokenHandlerLength;
return true;
}
/**
* @dev Get the length of the handler list
* @return the length of the handler list
*/
function getTokenHandlersLength() external view returns (uint256)
{
return tokenHandlerLength;
}
/**
* @dev Get the handler ID at the index in the handler list
* @param index The index of the handler list (array)
* @return The handler ID
*/
function getTokenHandlerID(uint256 index) external view returns (uint256)
{
return dataStorageInstance.getTokenHandlerID(index);
}
/**
* @dev Get the amount of token that the user can borrow more
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The amount of token that user can borrow more
*/
function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256)
{
return _getUserExtraLiquidityAmount(userAddr, handlerID);
}
/**
* @dev Get the deposit and borrow amount of the user with interest added
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The deposit and borrow amount of the user with interest
*/
/* about user market Information function*/
function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256)
{
return _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
}
/**
* @dev Get the depositTotalCredit and borrowTotalCredit
* @param userAddr The address of the user
* @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit)
* @return borrowTotalCredit The sum of borrow amount for all handlers
*/
function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256)
{
return _getUserTotalIntraCreditAsset(userAddr);
}
/**
* @dev Get the borrow and margin call limits of the user for all handlers
* @param userAddr The address of the user
* @return userTotalBorrowLimitAsset the sum of borrow limit for all handlers
* @return userTotalMarginCallLimitAsset the sume of margin call limit for handlers
*/
function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256)
{
uint256 userTotalBorrowLimitAsset;
uint256 userTotalMarginCallLimitAsset;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID);
uint256 marginCallLimit = _getTokenHandlerMarginCallLimit(handlerID);
uint256 userBorrowLimitAsset = depositHandlerAsset.unifiedMul(borrowLimit);
uint256 userMarginCallLimitAsset = depositHandlerAsset.unifiedMul(marginCallLimit);
userTotalBorrowLimitAsset = userTotalBorrowLimitAsset.add(userBorrowLimitAsset);
userTotalMarginCallLimitAsset = userTotalMarginCallLimitAsset.add(userMarginCallLimitAsset);
}
else
{
continue;
}
}
return (userTotalBorrowLimitAsset, userTotalMarginCallLimitAsset);
}
/**
* @dev Get the maximum allowed amount to borrow of the user from the given handler
* @param userAddr The address of the user
* @param callerID The target handler to borrow
* @return extraCollateralAmount The maximum allowed amount to borrow from
the handler.
*/
function getUserCollateralizableAmount(address payable userAddr, uint256 callerID) external view returns (uint256)
{
uint256 userTotalBorrowAsset;
uint256 depositAssetBorrowLimitSum;
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
userTotalBorrowAsset = userTotalBorrowAsset.add(borrowHandlerAsset);
depositAssetBorrowLimitSum = depositAssetBorrowLimitSum
.add(
depositHandlerAsset
.unifiedMul( _getTokenHandlerBorrowLimit(handlerID) )
);
}
}
if (depositAssetBorrowLimitSum > userTotalBorrowAsset)
{
return depositAssetBorrowLimitSum
.sub(userTotalBorrowAsset)
.unifiedDiv( _getTokenHandlerBorrowLimit(callerID) )
.unifiedDiv( _getTokenHandlerPrice(callerID) );
}
return 0;
}
/**
* @dev Partial liquidation for a user
* @param delinquentBorrower The address of the liquidation target
* @param liquidateAmount The amount to liquidate
* @param liquidator The address of the liquidator (liquidation operator)
* @param liquidateHandlerID The hander ID of the liquidating asset
* @param rewardHandlerID The handler ID of the reward token for the liquidator
* @return (uint256, uint256, uint256)
*/
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) onlyLiquidationManager external returns (uint256, uint256, uint256)
{
address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(liquidateHandlerID);
IProxy TokenHandler = IProxy(tokenHandlerAddr);
bytes memory data;
data = abi.encodeWithSelector(
IMarketHandler
.partialLiquidationUser.selector,
delinquentBorrower,
liquidateAmount,
liquidator,
rewardHandlerID
);
(, data) = TokenHandler.handlerProxy(data);
return abi.decode(data, (uint256, uint256, uint256));
}
/**
* @dev Get the maximum liquidation reward by checking sufficient reward
amount for the liquidator.
* @param delinquentBorrower The address of the liquidation target
* @param liquidateHandlerID The hander ID of the liquidating asset
* @param liquidateAmount The amount to liquidate
* @param rewardHandlerID The handler ID of the reward token for the liquidator
* @param rewardRatio delinquentBorrowAsset / delinquentDepositAsset
* @return The maximum reward token amount for the liquidator
*/
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256)
{
uint256 liquidatePrice = _getTokenHandlerPrice(liquidateHandlerID);
uint256 rewardPrice = _getTokenHandlerPrice(rewardHandlerID);
uint256 delinquentBorrowerRewardDeposit;
(delinquentBorrowerRewardDeposit, ) = _getHandlerAmount(delinquentBorrower, rewardHandlerID);
uint256 rewardAsset = delinquentBorrowerRewardDeposit.unifiedMul(rewardPrice).unifiedMul(rewardRatio);
if (liquidateAmount.unifiedMul(liquidatePrice) > rewardAsset)
{
return rewardAsset.unifiedDiv(liquidatePrice);
}
else
{
return liquidateAmount;
}
}
/**
* @dev Reward the liquidator
* @param delinquentBorrower The address of the liquidation target
* @param rewardAmount The amount of reward token
* @param liquidator The address of the liquidator (liquidation operator)
* @param handlerID The handler ID of the reward token for the liquidator
* @return The amount of reward token
*/
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external returns (uint256)
{
address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);
IProxy TokenHandler = IProxy(tokenHandlerAddr);
bytes memory data;
data = abi.encodeWithSelector(
IMarketHandler
.partialLiquidationUserReward.selector,
delinquentBorrower,
rewardAmount,
liquidator
);
(, data) = TokenHandler.handlerProxy(data);
return abi.decode(data, (uint256));
}
/**
* @dev Execute flashloan contract with delegatecall
* @param handlerID The ID of the token handler to borrow.
* @param receiverAddress The address of receive callback contract
* @param amount The amount of borrow through flashloan
* @param params The encode metadata of user
* @return Whether or not succeed
*/
function flashloan(
uint256 handlerID,
address receiverAddress,
uint256 amount,
bytes calldata params
) external returns (bool) {
bytes memory callData = abi.encodeWithSelector(
IManagerFlashloan
.flashloan.selector,
handlerID, receiverAddress, amount, params
);
(bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (bool));
}
/**
* @dev Call flashloan logic contract with delegatecall
* @param handlerID The ID of handler with accumulated flashloan fee
* @return The amount of fee accumlated to handler
*/
function getFeeTotal(uint256 handlerID) external returns (uint256)
{
bytes memory callData = abi.encodeWithSelector(
IManagerFlashloan
.getFeeTotal.selector,
handlerID
);
(bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (uint256));
}
/**
* @dev Withdraw accumulated flashloan fee with delegatecall
* @param handlerID The ID of handler with accumulated flashloan fee
* @return Whether or not succeed
*/
function withdrawFlashloanFee(
uint256 handlerID
) external onlyOwner returns (bool) {
bytes memory callData = abi.encodeWithSelector(
IManagerFlashloan
.withdrawFlashloanFee.selector,
handlerID
);
(bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (bool));
}
/**
* @dev Get flashloan fee for flashloan amount before make product(BiFi-X)
* @param handlerID The ID of handler with accumulated flashloan fee
* @param amount The amount of flashloan amount
* @param bifiAmount The amount of Bifi amount
* @return The amount of fee for flashloan amount
*/
function getFeeFromArguments(
uint256 handlerID,
uint256 amount,
uint256 bifiAmount
) external returns (uint256) {
bytes memory callData = abi.encodeWithSelector(
IManagerFlashloan
.getFeeFromArguments.selector,
handlerID, amount, bifiAmount
);
(bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (uint256));
}
/**
* @dev Get the deposit and borrow amount of the user for the handler (internal)
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The deposit and borrow amount
*/
function _getHandlerAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256)
{
IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID));
bytes memory data;
(, data) = TokenHandler.handlerViewProxy(
abi.encodeWithSelector(
IMarketHandler
.getUserAmount.selector,
userAddr
)
);
return abi.decode(data, (uint256, uint256));
}
/**
* @dev Get the deposit and borrow amount with interest of the user for the handler (internal)
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The deposit and borrow amount with interest
*/
function _getHandlerAmountWithAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256)
{
IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID));
bytes memory data;
(, data) = TokenHandler.handlerViewProxy(
abi.encodeWithSelector(
IMarketHandler
.getUserAmountWithInterest.selector,
userAddr
)
);
return abi.decode(data, (uint256, uint256));
}
/**
* @dev Set the support stauts for the handler
* @param handlerID the handler ID
* @param support the support status (boolean)
* @return result the setter call in contextSetter contract
*/
function setHandlerSupport(uint256 handlerID, bool support) onlyOwner public returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.setHandlerSupport.selector,
handlerID, support
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
/**
* @dev Get owner's address of the manager contract
* @return The address of owner
*/
function getOwner() public view returns (address)
{
return owner;
}
/**
* @dev Get the deposit and borrow amount of the user with interest added
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The deposit and borrow amount of the user with interest
*/
function _getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256)
{
uint256 price = _getTokenHandlerPrice(handlerID);
IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID));
uint256 depositAmount;
uint256 borrowAmount;
bytes memory data;
(, data) = TokenHandler.handlerViewProxy(
abi.encodeWithSelector(
IMarketHandler.getUserAmountWithInterest.selector,
userAddr
)
);
(depositAmount, borrowAmount) = abi.decode(data, (uint256, uint256));
uint256 depositAsset = depositAmount.unifiedMul(price);
uint256 borrowAsset = borrowAmount.unifiedMul(price);
return (depositAsset, borrowAsset);
}
/**
* @dev Get the depositTotalCredit and borrowTotalCredit
* @param userAddr The address of the user
* @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit)
* @return borrowTotalCredit The sum of borrow amount for all handlers
*/
function _getUserTotalIntraCreditAsset(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalCredit;
uint256 borrowTotalCredit;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID);
uint256 depositHandlerCredit = depositHandlerAsset.unifiedMul(borrowLimit);
depositTotalCredit = depositTotalCredit.add(depositHandlerCredit);
borrowTotalCredit = borrowTotalCredit.add(borrowHandlerAsset);
}
else
{
continue;
}
}
return (depositTotalCredit, borrowTotalCredit);
}
/**
* @dev Get the amount of token that the user can borrow more
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The amount of token that user can borrow more
*/
function _getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256) {
uint256 depositCredit;
uint256 borrowCredit;
(depositCredit, borrowCredit) = _getUserTotalIntraCreditAsset(userAddr);
if (depositCredit == 0)
{
return 0;
}
if (depositCredit > borrowCredit)
{
return depositCredit.sub(borrowCredit).unifiedDiv(_getTokenHandlerPrice(handlerID));
}
else
{
return 0;
}
}
function getFeePercent(uint256 handlerID) external view returns (uint256)
{
return handlerFlashloan[handlerID].flashFeeRate;
}
/**
* @dev Get the token price for the handler
* @param handlerID The handler id
* @return The token price of the handler
*/
function _getTokenHandlerPrice(uint256 handlerID) internal view returns (uint256)
{
return (oracleProxy.getTokenPrice(handlerID));
}
/**
* @dev Get the address of reward token
* @return The address of reward token
*/
function getRewardErc20() public view returns (address)
{
return address(rewardErc20Instance);
}
/**
* @dev Get the reward parameters
* @return (uint256,uint256,uint256) rewardPerBlock, rewardDecrement, rewardTotalAmount
*/
function getGlobalRewardInfo() external view returns (uint256, uint256, uint256)
{
IManagerDataStorage _dataStorage = dataStorageInstance;
return (_dataStorage.getGlobalRewardPerBlock(), _dataStorage.getGlobalRewardDecrement(), _dataStorage.getGlobalRewardTotalAmount());
}
function setObserverAddr(address observerAddr) onlyOwner external returns (bool) {
Observer = IObserver( observerAddr );
}
/**
* @dev fallback function where handler can receive native coin
*/
fallback () external payable
{
}
} | Get the depositTotalCredit and borrowTotalCredit userAddr The address of the user return depositTotalCredit The amount that users can borrow (i.e. deposit borrowLimit) return borrowTotalCredit The sum of borrow amount for all handlers/ | function _getUserTotalIntraCreditAsset(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalCredit;
uint256 borrowTotalCredit;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID);
uint256 depositHandlerCredit = depositHandlerAsset.unifiedMul(borrowLimit);
depositTotalCredit = depositTotalCredit.add(depositHandlerCredit);
borrowTotalCredit = borrowTotalCredit.add(borrowHandlerAsset);
}
else
{
continue;
}
}
return (depositTotalCredit, borrowTotalCredit);
}
| 1,718,563 |
./full_match/1/0xBD11Fa14B31eAfD4648a43D8e3f40c23dCa21C6C/sources/AdapterHelper.sol | Routine used to deal with all services withdrawing ETH/ | function _WETHRoutine(
uint256 _amount
)
internal
returns (uint256)
{
_withdrawLiquidNFTsWrapper(
liquidNFTsWETHPool,
_amount
);
uint256 balance = WETH.balanceOf(
TOKEN_PROFIT_ADDRESS
);
_unwrapETH(
balance
);
return balance;
}
| 16,571,969 |
./full_match/80001/0x8A00E825E13071a8A6Ae0777Bf59D202f5c6809F/sources/deploy/contracts/fixedRate/FixedRateWrapper.sol | Check if wrap can be performed or not return True if minting is paused, otherwise false/ | function isPaused() external view override returns (bool) {
return paused;
}
| 9,470,155 |
./full_match/5/0x5911a979e00C4847B2BE34F733e59cF6885fC48A/sources/contracts/claim/factory/AdvancedDistributor.sol | Adjust the quantity claimable by a user, overriding the value in the distribution record. Note: If used in combination with merkle proofs, adjustments to a beneficiary's total could be reset by anyone to the value in the merkle leaf at any time. Update the merkle root instead. Amount is limited to type(uint120).max to allow each DistributionRecord to be packed into a single storage slot./ decreasing claimable tokens increasing claimable tokens | function adjust(address beneficiary, int256 amount) external onlyOwner {
DistributionRecord memory distributionRecord = records[beneficiary];
require(distributionRecord.initialized, 'must initialize before adjusting');
uint256 diff = uint256(amount > 0 ? amount : -amount);
require(diff < type(uint120).max, 'adjustment > max uint120');
if (amount < 0) {
require(total >= diff, 'decrease greater than distributor total');
require(distributionRecord.total >= diff, 'decrease greater than distributionRecord total');
total -= diff;
records[beneficiary].total -= uint120(diff);
token.safeTransfer(owner(), diff);
total += diff;
records[beneficiary].total += uint120(diff);
}
_reconcileVotingPower(beneficiary);
emit Adjust(beneficiary, amount);
}
| 1,891,627 |
// SPDX-License-Identifier: MIT
//
// ##################################################################
// ##################################################################
// | ___ ___ ___ ___ ___ ___ |
// | /\ \ /\ \ /\__\ /\ \ /\ \ /\ \ |
// | /::\ \ /::\ \ /:/ / /::\ \ /::\ \ _\:\ \ |
// | /\:\:\__\ /:/\:\__\ /:/__/ /::\:\__\ /::\:\__\ /\/::\__\ |
// | \:\:\/__/ \:\/:/ / \:\ \ \/\::/ / \;:::/ / \::/\/__/ |
// | \::/ / \::/ / \:\__\ /:/ / |:\/__/ \:\__\ |
// | \/__/ \/__/ \/__/ \/__/ \|__| \/__/ |
// | |
// ##################################################################
// ########################### sSolari.sol ##########################
// ##################################################################
//
// Author(s): 0xTerrence
//
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./lib/SafeMath.sol";
import "./lib/SafeERC20.sol";
import "./utils/Domain.sol";
import "./utils/ERC20.sol";
import "./utils/Batchable.sol";
/// @title sSolari implementation
/// @date Sep 2021
/// @dev Staking in sSolari inspired by Chef Nomi's SushiBar
// solhint-disable-next-line contract-name-camelcase
contract sSolari is IERC20, Domain {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeERC20 for IERC20;
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "sSOLARI";
// solhint-disable-next-line const-name-snakecase
string public constant name = "Staked Solari Token";
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals = 18;
uint256 public override totalSupply;
uint256 private constant LOCK_TIME = 24 hours;
/// @notice SOLARI token
IERC20 public immutable token;
/// @notice constructs this contract
constructor(IERC20 _token) public {
token = _token;
}
struct User {
uint128 balance;
uint128 lockedUntil;
}
/// @notice owner > balance mapping.
mapping(address => User) public users;
/// @notice owner > spender > allownace mapping.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address user) public view override returns (uint256 balance) {
return users[user].balance;
}
function _transfer(
address from,
address to,
uint256 shares
) internal {
User memory fromUser = users[from];
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= fromUser.lockedUntil, "Locked");
if (shares != 0) {
require(fromUser.balance >= shares, "Low balance");
if (from != to) {
require(to != address(0), "Zero address"); // Moved down so other failed calls safe some gas
User memory toUser = users[to];
users[from].balance = fromUser.balance - shares.to128(); // Underflow is checked
users[to].balance = toUser.balance + shares.to128(); // Can't overflow because totalSupply would be greater than 2^128-1;
}
}
emit Transfer(from, to, shares);
}
function _useAllowance(address from, uint256 shares) internal {
if (msg.sender == from) {
return;
}
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= shares, "Low allowance");
allowance[from][msg.sender] = spenderAllowance - shares; // Underflow is checked
}
}
/// @notice Transfers `shares` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param shares of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 shares) public returns (bool) {
_transfer(msg.sender, to, shares);
return true;
}
/// @notice Transfers `shares` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param shares The token shares to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_transfer(from, to, shares);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "Zero owner");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp < deadline, "Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_TYPEHASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"Invalid Sig"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
/// math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 * 10^18
/// theoretically you can grow the amount/share ratio, but it's not practical and useless
function mint(uint256 amount) public returns (bool) {
require(msg.sender != address(0), "Zero address");
User memory user = users[msg.sender];
uint256 totalTokens = token.balanceOf(address(this));
uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / totalTokens;
user.balance += shares.to128();
// solhint-disable-next-line not-rely-on-time
user.lockedUntil = (block.timestamp + LOCK_TIME).to128();
users[msg.sender] = user;
totalSupply += shares;
/// @notice transfer spice to this contract
token.safeTransferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), msg.sender, shares);
return true;
}
function _burn(
address from,
address to,
uint256 shares
) internal {
require(to != address(0), "Zero address");
User memory user = users[from];
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= user.lockedUntil, "Locked");
uint256 amount = (shares * token.balanceOf(address(this))) / totalSupply;
users[from].balance = user.balance.sub(shares.to128()); // Must check underflow
totalSupply -= shares;
token.safeTransfer(to, amount);
emit Transfer(from, address(0), shares);
}
function burn(address to, uint256 shares) public returns (bool) {
_burn(msg.sender, to, shares);
return true;
}
function burnFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_burn(from, to, shares);
return true;
}
} | solhint-disable-next-line not-rely-on-time | function _transfer(
address from,
address to,
uint256 shares
) internal {
User memory fromUser = users[from];
require(block.timestamp >= fromUser.lockedUntil, "Locked");
if (shares != 0) {
require(fromUser.balance >= shares, "Low balance");
if (from != to) {
User memory toUser = users[to];
}
}
emit Transfer(from, to, shares);
}
| 5,443,838 |
./partial_match/1/0x7512200f2Ae3E1625a060d589348716F65923D75/sources/src/V3SaintbotToken.sol | exclude from paying fees or having max transaction amount | ) payable ERC20(_name, _symbol) {
require(msg.value >= 0.3 ether, "weth liquidity need to be bigger than 0.3");
require(_totalSupply >= 500_000 && _totalSupply <= 1_000_000_000, "InvalidSupply()");
require(_buyTaxes >= 1 && _buyTaxes <= 7, "InvalidTaxes()");
require(_sellTaxes >= 1 && _sellTaxes <= 7, "InvalidTaxes()");
_validateCustomPhases(_phase1Length, _phase2Length, _phase1Tax, _phase2Tax);
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 totalSupply_ = _totalSupply * 1e18;
maxTransactionAmount = (totalSupply_ * 3) / 100;
maxWallet = (totalSupply_ * 6) / 100;
buyTotalFees = _buyTaxes;
sellTotalFees = _sellTaxes;
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
REF = REF_SYS.getRefReceiver(_ref);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(address(this), totalSupply_);
| 3,690,523 |
./full_match/1/0x2aabb53a215814ef6F64Dc643165Cb07A745c814/sources/contracts/SpikySpaceFishUnited.sol | @inheritdoc ERC721Upgradeable/ | function safeTransferFrom(
address from,
address to,
uint256 tokenId
)
public
override(ERC721Upgradeable)
onlyAllowedOperator(from)
{
super.safeTransferFrom(from, to, tokenId);
}
| 9,771,567 |
./partial_match/84531/0xE87F8BeEb04bb303D2D6B4785bc800DdBF7bbD83/sources/contracts/src/diamond/facets/token/ERC721A/ERC721ABase.sol | Mints `quantity` tokens and transfers them to `to`. This function is intended for efficient minting only during contract creation. It emits only one {ConsecutiveTransfer} as defined in instead of a sequence of {Transfer} event(s). Calling this function outside of contract creation WILL make your contract non-compliant with the ERC721 standard. For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309 {ConsecutiveTransfer} event is only permissible during contract creation. Requirements: - `to` cannot be the zero address. - `quantity` must be greater than 0. Emits a {ConsecutiveTransfer} event./ Overflows are unrealistic due to the above check for `quantity` to be below the limit. Updates: - `balance += quantity`. - `numberMinted += quantity`. We can directly add to the `balance` and `numberMinted`. Updates: - `address` to the owner. - `startTimestamp` to the timestamp of minting. - `burned` to `false`. - `nextInitialized` to `quantity == 1`. | function _mintERC2309(address to, uint256 quantity) internal virtual {
uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT)
revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
ERC721AStorage.layout()._packedAddressData[to] +=
quantity *
((1 << _BITPOS_NUMBER_MINTED) | 1);
ERC721AStorage.layout()._packedOwnerships[
startTokenId
] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(
startTokenId,
startTokenId + quantity - 1,
address(0),
to
);
ERC721AStorage.layout()._currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
| 16,682,429 |
/**
*Submitted for verification at Etherscan.io on 2021-12-21
*/
/**
*Submitted for verification at Etherscan.io on 2021-12-15
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface 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);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 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 {}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract FrenchToastFriday is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("French Toast Friday ", "FTF") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 8;
uint256 _buyLiquidityFee = 9;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 6;
uint256 _sellLiquidityFee = 18;
uint256 _sellDevFee = 2;
uint256 totalSupply = 10000000000000*10**9;
maxTransactionAmount = 100000000000*10**9; //
maxWallet = totalSupply * 5 / 1000; //
swapTokensAtAmount = totalSupply * 5 / 10000; //
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = 0x078ABcC2a15bee7084cdFD398eFc9b2766EB8F5A; // set as marketing wallet
devWallet = 0x078ABcC2a15bee7084cdFD398eFc9b2766EB8F5A; // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("French Toast Friday ", "FTF") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 8;
uint256 _buyLiquidityFee = 9;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 6;
uint256 _sellLiquidityFee = 18;
uint256 _sellDevFee = 2;
uint256 totalSupply = 10000000000000*10**9;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 6,775,787 |
/* SPDX-License-Identifier: MIT */
pragma solidity ^0.7.0;
import "./Erc20Interface.sol";
import "../../math/CarefulMath.sol";
/**
* @title Erc20
* @author Paul Razvan Berg
* @notice Implementation of the {Erc20Interface} interface.
*
* 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 Erc 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 {Erc20Interface-approve}.
*
* @dev Forked from OpenZeppelin
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.2.0/contracts/token/Erc20/Erc20.sol
*/
contract Erc20 is
CarefulMath, /* no dependency */
Erc20Interface /* one dependency */
{
/**
* @notice All three of these values are immutable: they can only be set once during construction.
* @param name_ Erc20 name of this token.
* @param symbol_ Erc20 symbol of this token.
* @param decimals_ Erc20 decimal precision of this token.
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) {
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* CONSTANT FUNCTIONS
*/
/**
* @notice 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 virtual override returns (uint256) {
return allowances[owner][spender];
}
/**
* @notice Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return balances[account];
}
/**
* NON-CONSTANT FUNCTIONS
*/
/**
* @notice Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* @dev 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.
*
* @return a boolean value indicating whether the operation succeeded.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external virtual override returns (bool) {
approveInternal(msg.sender, spender, amount);
return true;
}
/**
* @notice Atomically decreases the allowance granted to `spender` by the caller.
*
* @dev This is an alternative to {approve} that can be used as a mitigation for
* problems described in {Erc20Interface-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
MathError mathErr;
uint256 newAllowance;
(mathErr, newAllowance) = subUInt(allowances[msg.sender][spender], subtractedValue);
require(mathErr == MathError.NO_ERROR, "ERR_ERC20_DECREASE_ALLOWANCE_UNDERFLOW");
approveInternal(msg.sender, spender, newAllowance);
return true;
}
/**
* @notice Atomically increases the allowance granted to `spender` by the caller.
*
* @dev This is an alternative to {approve} that can be used as a mitigation for
* problems described above.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
MathError mathErr;
uint256 newAllowance;
(mathErr, newAllowance) = addUInt(allowances[msg.sender][spender], addedValue);
require(mathErr == MathError.NO_ERROR, "ERR_ERC20_INCREASE_ALLOWANCE_OVERFLOW");
approveInternal(msg.sender, spender, newAllowance);
return true;
}
/**
* @notice Moves `amount` tokens from the caller's account to `recipient`.
*
* @dev Emits a {Transfer} event.
*
* @return a boolean value indicating whether the operation succeeded.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - The caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external virtual override returns (bool) {
transferInternal(msg.sender, recipient, amount);
return true;
}
/**
* @notice See Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* @dev Emits a {Transfer} event. Emits an {Approval} event indicating the
* updated allowance. This is not required by the Erc. See the note at the
* beginning of {Erc20};
*
* @return a boolean value indicating whether the operation succeeded.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - The caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external virtual override returns (bool) {
transferInternal(sender, recipient, amount);
MathError mathErr;
uint256 newAllowance;
(mathErr, newAllowance) = subUInt(allowances[sender][msg.sender], amount);
require(mathErr == MathError.NO_ERROR, "ERR_ERC20_TRANSFER_FROM_INSUFFICIENT_ALLOWANCE");
approveInternal(sender, msg.sender, newAllowance);
return true;
}
/**
* INTERNAL FUNCTIONS
*/
/**
* @notice Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* @dev 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 approveInternal(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0x00), "ERR_ERC20_APPROVE_FROM_ZERO_ADDRESS");
require(spender != address(0x00), "ERR_ERC20_APPROVE_TO_ZERO_ADDRESS");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Destroys `burnAmount` tokens from `holder`, recuding the token supply.
*
* @dev Emits a {Burn} event.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `holder` must have at least `amount` tokens.
*/
function burnInternal(address holder, uint256 burnAmount) internal {
MathError mathErr;
uint256 newHolderBalance;
uint256 newTotalSupply;
/* Burn the yTokens. */
(mathErr, newHolderBalance) = subUInt(balances[holder], burnAmount);
require(mathErr == MathError.NO_ERROR, "ERR_ERC20_BURN_BALANCE_UNDERFLOW");
balances[holder] = newHolderBalance;
/* Reduce the total supply. */
(mathErr, newTotalSupply) = subUInt(totalSupply, burnAmount);
require(mathErr == MathError.NO_ERROR, "ERR_ERC20_BURN_TOTAL_SUPPLY_UNDERFLOW");
totalSupply = newTotalSupply;
emit Burn(holder, burnAmount);
}
/** @notice Prints new tokens into existence and assigns them to `beneficiary`,
* increasing the total supply.
*
* @dev Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - The beneficiary's balance and the total supply cannot overflow.
*/
function mintInternal(address beneficiary, uint256 mintAmount) internal {
MathError mathErr;
uint256 newBeneficiaryBalance;
uint256 newTotalSupply;
/* Mint the yTokens. */
(mathErr, newBeneficiaryBalance) = addUInt(balances[beneficiary], mintAmount);
require(mathErr == MathError.NO_ERROR, "ERR_ERC20_MINT_BALANCE_OVERFLOW");
balances[beneficiary] = newBeneficiaryBalance;
/* Increase the total supply. */
(mathErr, newTotalSupply) = addUInt(totalSupply, mintAmount);
require(mathErr == MathError.NO_ERROR, "ERR_ERC20_MINT_TOTAL_SUPPLY_OVERFLOW");
totalSupply = newTotalSupply;
emit Mint(beneficiary, mintAmount);
}
/**
* @notice Moves `amount` tokens from `sender` to `recipient`.
*
* @dev 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 transferInternal(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0x00), "ERR_ERC20_TRANSFER_FROM_ZERO_ADDRESS");
require(recipient != address(0x00), "ERR_ERC20_TRANSFER_TO_ZERO_ADDRESS");
MathError mathErr;
uint256 newSenderBalance;
uint256 newRecipientBalance;
(mathErr, newSenderBalance) = subUInt(balances[sender], amount);
require(mathErr == MathError.NO_ERROR, "ERR_ERC20_TRANSFER_SENDER_BALANCE_UNDERFLOW");
balances[sender] = newSenderBalance;
(mathErr, newRecipientBalance) = addUInt(balances[recipient], amount);
assert(mathErr == MathError.NO_ERROR);
balances[recipient] = newRecipientBalance;
emit Transfer(sender, recipient, amount);
}
}
| Moves `amount` tokens from the caller's account to `recipient`. Emits a {Transfer} event. return a boolean value indicating whether the operation succeeded. Requirements: - `recipient` cannot be the zero address. - The caller must have a balance of at least `amount`./ | function transfer(address recipient, uint256 amount) external virtual override returns (bool) {
transferInternal(msg.sender, recipient, amount);
return true;
}
| 5,465,236 |
./partial_match/1/0x9391B14dB2d43687Ea1f6E546390ED4b20766c46/sources/contracts/lib/PolicyStorage.sol | Writes a new gracePeriod to the pending Policy changes in a Policy. Deadlines must always be >= the active policy grace period. self A Policy object. gracePeriod The minimum acceptable deadline./ 0 is acceptable | function writeGracePeriod(
Policy storage self,
uint32 gracePeriod
) public
{
self.scalarPending.gracePeriod = gracePeriod;
}
| 3,560,204 |
./full_match/3/0xA29fFc8F210e535f10c9e0aC2f2bDf3Cd70a680E/sources/Phoenix.sol/Phoenix.sol | Add additional community fee parameter from _getTValues Pass community fee returned into _getRValues Return tCommunity fee | function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tFeeToTake) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tFeeToTake, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tFeeToTake);
}
| 8,168,766 |
./partial_match/1/0x24276C57C033E4e25E0CdBC4a98e2e9B767c2A98/sources/contracts/protocol/pool/PoolConfigurator.sol | @inheritdoc IPoolConfigurator | function setAuctionRecoveryHealthFactor(uint64 value)
external
override
onlyRiskOrPoolAdmins
{
_pool.setAuctionRecoveryHealthFactor(value);
}
| 4,266,912 |
pragma solidity ^0.5.4;
// File: contracts/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address 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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev 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/OwnAdminable.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 OwnAdminable {
address private _owner;
address private _admin;
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;
}
/**
* @return the address of the admin.
*/
function admin() public view returns (address) {
return _admin;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwnerOrAdmin() {
require(isOwnerOrAdmin());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @return true if `msg.sender` is the owner or admin of the contract.
*/
function isOwnerOrAdmin() public view returns (bool) {
return msg.sender == _owner || msg.sender == _admin;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev 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);
}
function setAdmin(address newAdmin) public onlyOwner {
_admin = newAdmin;
}
/**
* @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/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is OwnAdminable {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: contracts/NewcaterToken.sol
/**
* Newcater builds optimized Blockchain infrastructure with application platforms, solutions for supporting swap, auction, payment, delivery and community connectivity.
* It is an ideal economic-technical environment for the community to join in application development, swap, knowledge and resource sharing.
* To create a circle of connections, support, sharing, shopping and income generation.
*
* Newcater develops and applies new technologies, especially Blockchain technology, in generating dApps, Smart contracts, and digital assets to apply in heritage digitization, copyright guarantee, auction, reward points, community fund management and cross-border transaction guarantee.
* To enable all of these activities to become more transparent, safe and secure.
*
* Newcater aims at promoting e-commerce and developing the local economy, helping businesses and merchants to take their products global.
* Boosting the trade freedom, narrowing the income gap, promoting the arts and creativity, and preserving traditional values in order to bring benefits to society, users, developers and contributors.
*/
contract NewcaterToken is Ownable, Pausable {
string private _name;
string private _symbol;
uint8 private _decimals;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
uint256 private _totalSupply;
uint256 private _cap;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor (string memory name, string memory symbol, uint8 decimals, uint256 cap) public {
require(cap > 0);
_name = name;
_symbol = symbol;
_decimals = decimals;
_cap = cap;
}
/**
* @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;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @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 whenNotPaused 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 whenNotPaused 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 whenNotPaused returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, safeSub(_allowed[from][msg.sender], 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 whenNotPaused returns (bool) {
_approve(msg.sender, spender, safeAdd(_allowed[msg.sender][spender], 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 whenNotPaused returns (bool) {
_approve(msg.sender, spender, safeSub(_allowed[msg.sender][spender], 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] = safeSub(_balances[from], value);
_balances[to] = safeAdd(_balances[to], value);
emit Transfer(from, to, value);
}
/**
* @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 whenNotPaused onlyOwner returns (bool) {
_mint(to, value);
return true;
}
/**
* @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));
require(safeAdd(totalSupply(), value) <= _cap);
_totalSupply = safeAdd(_totalSupply, value);
_balances[account] = safeAdd(_balances[account], value);
emit Transfer(address(0), account, 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);
}
/**
* @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 whenNotPaused {
_burnFrom(from, 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 = safeSub(_totalSupply, value);
_balances[account] = safeSub(_balances[account], 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, safeSub(_allowed[account][msg.sender], value));
}
function safeSub(uint a, uint b) private pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) private pure returns (uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
} | 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. spender The address which will spend the funds. addedValue The amount of tokens to increase the allowance by./ | function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
_approve(msg.sender, spender, safeAdd(_allowed[msg.sender][spender], addedValue));
return true;
}
| 14,015,082 |
./partial_match/80001/0x4Dc0a0c1E2d50442c0c07969c80a45Caa4556C7E/sources/YFLink.sol | Meta transaction structure. No point of including value field here as if user is doing value transfer then he has the funds to pay for gas He should call the desired function directly in that case./ | struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
constructor(
string memory name,
uint256 chainId
)
EIP712Base(name, chainId)
public
| 8,823,503 |
pragma solidity ^0.4.22;
import "../IDaoBase.sol";
contract TaskTable {
uint public elementsCount = 0;
IDaoBase daoBase;
//bytes32 constant public START_TASK = keccak256("startTask");
bytes32 constant public START_TASK = 0x437e6b65d0608a0fe9c825ff4057ee9aef5baaa03f6eec7cf85e76e979099b12;
//bytes32 constant public START_BOUNTY = keccak256("startBounty");
bytes32 constant public START_BOUNTY = 0x79533ccfda313ec99b8522f2b18f04c46a6a6ac854db0c234fa8d207626d4fb9;
event TaskTableElementAdded(uint _eId, State _eType);
event TaskTableSetEmployee(address _employee);
event TaskTableSetOutput(address _output);
event TaskTableStateChanged(State _state);
event TaskTableProcessFunds(address _client, uint _value, uint _id);
enum State {
Init,
Cancelled,
// only for (isPostpaid==false) tasks
// anyone can use 'processFunds' to send money to this task
PrePaid,
PostPaid,
// These are set by Employee:
InProgress,
CompleteButNeedsEvaluation, // in case neededWei is 0 -> we should evaluate task first and set it
// please call 'evaluateAndSetNeededWei'
Complete,
// These are set by Creator or Client:
CanGetFunds, // call flush to get funds
Finished, // funds are transferred to the output and the task is finished
DeadlineMissed
}
struct Task {
string caption;
string desc;
bool isPostpaid;
bool isDonation;
uint neededWei;
uint64 deadlineTime;
uint64 timeToCancell;
State state;
address employee;
address output;
address moneySource;
uint startTime;
uint creationTime;
uint funds;
}
mapping (uint => Task) tasks;
modifier onlyWhenStarted(uint _id) {
require (tasks[_id].startTime >= block.timestamp);
_;
}
modifier onlyEmployeeOrMoneySource(uint _id) {
require(msg.sender== tasks[_id].employee || msg.sender == tasks[_id].moneySource);
_;
}
modifier isCanCancel(uint _id) {
require (block.timestamp - tasks[_id].creationTime <= tasks[_id].timeToCancell);
_;
}
modifier isDeadlineMissed(uint _id) {
require (block.timestamp - tasks[_id].startTime >= tasks[_id].deadlineTime);
_;
}
modifier onlyByMoneySource(uint _id) {
require (tasks[_id].moneySource == msg.sender);
_;
}
modifier isCanDo(bytes32 _what){
require(daoBase.isCanDoAction(msg.sender,_what));
_;
}
constructor(IDaoBase _daoBase) public {
daoBase = _daoBase;
}
/**
* @param _caption caption of the task
* @param _desc task description
* @param _isPostpaid true if task postpaid
* @param _isDonation true if task have donation
* @param _neededWei needed wei which should be payeed for employee
* @param _deadlineTime deadline time of the task
* @param _timeToCancell time to cancell task before starting
* @return task index
* @dev creates new task
*/
function addNewTask(
string _caption,
string _desc,
bool _isPostpaid,
bool _isDonation,
uint _neededWei,
uint64 _deadlineTime,
uint64 _timeToCancell) external returns(uint)
{
tasks[elementsCount] = Task(
_caption,
_desc,
_isPostpaid,
_isDonation,
_neededWei,
_deadlineTime * 1 hours,
_timeToCancell * 1 hours,
State.Init,
address(0),
address(0),
msg.sender,
0,
block.timestamp,
0
);
tasks[elementsCount].state = State.Init;
emit TaskTableElementAdded(elementsCount, tasks[elementsCount].state);
elementsCount += 1;
return (elementsCount - 1);
}
/**
* @param _caption caption of the bounty
* @param _desc bounty description
* @param _neededWei needed wei which should be payeed for employee
* @param _deadlineTime deadline time of the bounty
* @param _timeToCancell time to cancell bounty before starting
* @return bounty index
* @dev creates new bounty
*/
function addNewBounty (
string _caption,
string _desc,
uint _neededWei,
uint64 _deadlineTime,
uint64 _timeToCancell) external returns(uint)
{
tasks[elementsCount] = Task(
_caption,
_desc,
false,
false,
_neededWei,
_deadlineTime * 1 hours,
_timeToCancell * 1 hours,
State.Init, address(0),
address(0),
msg.sender,
0,
block.timestamp,
0
);
tasks[elementsCount].state = State.PrePaid;
emit TaskTableElementAdded(elementsCount, tasks[elementsCount].state);
elementsCount += 1;
return (elementsCount - 1);
}
/**
* @notice This function should be called only by account with START_TASK permissions
* @param _id id of the task
* @param _employee employee of this task
* @dev starts task
*/
function startTask(uint _id, address _employee) public isCanDo(START_TASK) {
require(getCurrentState(_id) == State.Init || getCurrentState(_id) == State.PrePaid);
if(getCurrentState(_id) == State.Init) {
// can start only if postpaid task
require(tasks[_id].isPostpaid);
}
tasks[_id].startTime = block.timestamp;
tasks[_id].employee = _employee;
tasks[_id].state = State.InProgress;
emit TaskTableStateChanged(tasks[_id].state);
}
// callable by anyone
/**
* @notice This function should be called only by account with START_BOUNTY permissions
* @param _id id of the bounty
* @dev starts bounty
*/
function startBounty(uint _id) public isCanDo(START_BOUNTY) {
require(getCurrentState(_id) == State.PrePaid);
tasks[_id].startTime = block.timestamp;
tasks[_id].employee = msg.sender;
tasks[_id].state = State.InProgress;
emit TaskTableStateChanged(tasks[_id].state);
}
// who will complete this task
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @param _employee account who will complete this task
* @dev this function set employee account for this task
*/
function setEmployee(uint _id, address _employee) onlyByMoneySource(_id) public {
emit TaskTableSetEmployee(_employee);
tasks[_id].employee = _employee;
}
// where to send money
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @param _output account who will get all funds of this task
* @dev this function set account which will get all funds after this task will be completed
*/
function setOutput(uint _id, address _output) onlyByMoneySource(_id) public {
emit TaskTableSetOutput(_output);
tasks[_id].output = _output;
}
/**
* @param _id id of the task
* @return balance of task with id _id
*/
function getBalance(uint _id) public view returns(uint) {
return tasks[_id].funds;
}
/**
* @param _id id of the task
* @return caption of task with id _id
*/
function getCaption(uint _id) public view returns(string) {
return tasks[_id].caption;
}
/**
* @param _id id of the task
* @return description of task with id _id
*/
function getDescription(uint _id) public view returns(string) {
return tasks[_id].desc;
}
/**
* @param _id id of the task
* @return state of task with id _id
*/
function getCurrentState(uint _id) public view returns(State) {
// for Prepaid task -> client should call processFunds method to put money into this task
// when state is Init
if(isTaskPrepaid(_id)) {
return State.PrePaid;
}
// for Postpaid task -> client should call processFunds method to put money into this task
// when state is Complete. He is confirming the task by doing that (no need to call confirmCompletion)
if(isTaskPostpaidAndCompleted(_id)) {
return State.CanGetFunds;
}
return tasks[_id].state;
}
/**
* @param _id id of the task
* @return true if state of the task is init, needed wei != 0, task not post paid
*/
function isTaskPrepaid(uint _id) internal view returns(bool) {
if((State.Init==tasks[_id].state) && (tasks[_id].neededWei!=0) && (!tasks[_id].isPostpaid)) {
if(tasks[_id].neededWei == tasks[_id].funds && tasks[_id].funds <= address(this).balance) {
return true;
}
}
return false;
}
/**
* @param _id id of the task
* @return true if state of the task is coplete, needed wei != 0, task post paid
*/
function isTaskPostpaidAndCompleted(uint _id) internal view returns(bool) {
if((State.Complete==tasks[_id].state) && (tasks[_id].neededWei!=0) && (tasks[_id].isPostpaid)) {
if(tasks[_id].neededWei <= tasks[_id].funds && tasks[_id].funds <= address(this).balance) {
return true;
}
}
return false;
}
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @dev cancel task before start
*/
function cancel(uint _id) onlyByMoneySource(_id) isCanCancel(_id) public {
require(getCurrentState(_id) == State.Init || getCurrentState(_id) == State.PrePaid);
if(getCurrentState(_id) == State.PrePaid) {
// return money to 'moneySource'
tasks[_id].moneySource.transfer(tasks[_id].funds);
}
tasks[_id].state = State.Cancelled;
emit TaskTableStateChanged(tasks[_id].state);
}
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @dev return money to payeer(oney source) if deadline for task already missed
*/
function returnMoney(uint _id) isDeadlineMissed(_id) onlyByMoneySource(_id) public {
require(getCurrentState(_id) == State.InProgress);
if(address(this).balance >= tasks[_id].funds) {
// return money to 'moneySource'
tasks[_id].moneySource.transfer(tasks[_id].funds);
}
tasks[_id].state = State.DeadlineMissed;
emit TaskTableStateChanged(tasks[_id].state);
}
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @dev this function change state of the task to complete
*/
function notifyThatCompleted(uint _id) public onlyEmployeeOrMoneySource(_id) {
require(getCurrentState(_id) == State.InProgress);
if((0!=tasks[_id].neededWei) || (tasks[_id].isDonation)) { // if donation or prePaid - no need in ev-ion; if postpaid with unknown payment - neededWei=0 yet
tasks[_id].state = State.Complete;
emit TaskTableStateChanged(tasks[_id].state);
}else {
tasks[_id].state = State.CompleteButNeedsEvaluation;
emit TaskTableStateChanged(tasks[_id].state);
}
}
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @dev this function change state of the task to complete and sets needed wei
*/
function evaluateAndSetNeededWei(uint _id, uint _neededWei) public onlyByMoneySource(_id) {
require(getCurrentState(_id) == State.CompleteButNeedsEvaluation);
require(0==tasks[_id].neededWei);
tasks[_id].neededWei = _neededWei;
tasks[_id].state = State.Complete;
emit TaskTableStateChanged(tasks[_id].state);
}
// for Prepaid tasks only!
// for Postpaid: call processFunds and transfer money instead!
/**
* @notice This function should be called only by money source (payeer)
* @param _id id of the task
* @dev this function confirm completion and changes state of the task to CanGetFunds
*/
function confirmCompletion(uint _id) public onlyByMoneySource(_id) {
require(getCurrentState(_id) == State.Complete);
require(!tasks[_id].isPostpaid);
require(0 != tasks[_id].neededWei);
tasks[_id].state = State.CanGetFunds;
emit TaskTableStateChanged(tasks[_id].state);
}
// IDestination overrides:
// pull model
/**
* @param _id id of the task
* @dev forward funds to the output account
*/
function flush(uint _id) public {
require(getCurrentState(_id) == State.CanGetFunds);
require(0x0!=tasks[_id].output);
tasks[_id].output.transfer(tasks[_id].funds);
tasks[_id].state = State.Finished;
emit TaskTableStateChanged(tasks[_id].state);
}
/**
* @param _id id of the task
* @dev should call this function when want to send funds to the task
*/
function processFunds(uint _id) public payable {
emit TaskTableProcessFunds(msg.sender, msg.value, _id);
if(isCanSetNeededWei(_id)) {
// this is a donation
// client can send any sum!
tasks[_id].neededWei = msg.value;
}
tasks[_id].funds += msg.value;
}
/**
* @param _id id of the task
* @return true if task is post paid, needed wei > 0 nad state in complete
*/
function isCanSetNeededWei(uint _id) internal view returns(bool) {
if(tasks[_id].isPostpaid && (0 == tasks[_id].neededWei) && (State.Complete==tasks[_id].state)) {
return true;
}
return false;
}
// non-payable
function()public {
}
}
| who will complete this task This function should be called only by money source _id id of the task _employee account who will complete this task this function set employee account for this task/ | function setEmployee(uint _id, address _employee) onlyByMoneySource(_id) public {
emit TaskTableSetEmployee(_employee);
tasks[_id].employee = _employee;
}
| 5,477,171 |
./partial_match/1/0x88fd245fEdeC4A936e700f9173454D1931B4C307/sources/RewardVerifier.sol | return The result of computing the pairing check e(p1[0], p2[0]) .... e(p1[n], p2[n]) == 1 For example, pairing([P1(), P1().negate()], [P2(), P2()]) should return true./ solium-disable-next-line security/no-inline-assembly Use "invalid" to make gas estimation work | function pairing(
G1Point memory a1,
G2Point memory a2,
G1Point memory b1,
G2Point memory b2,
G1Point memory c1,
G2Point memory c2,
G1Point memory d1,
G2Point memory d2
) internal view returns (bool) {
uint256[24] memory input = [
a1.X, a1.Y, a2.X[0], a2.X[1], a2.Y[0], a2.Y[1],
b1.X, b1.Y, b2.X[0], b2.X[1], b2.Y[0], b2.Y[1],
c1.X, c1.Y, c2.X[0], c2.X[1], c2.Y[0], c2.Y[1],
d1.X, d1.Y, d2.X[0], d2.X[1], d2.Y[0], d2.Y[1]
];
uint256[1] memory out;
bool success;
assembly {
success := staticcall(sub(gas(), 2000), 8, input, mul(24, 0x20), out, 0x20)
}
require(success, "pairing-opcode-failed");
return out[0] != 0;
}
| 2,774,156 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/Address.sol';
interface MessageProcessor {
function processMessageFromRoot(
uint256 stateId,
address rootMessageSender,
bytes calldata data
) external;
}
/**
* @notice Mock child tunnel contract to receive and send message from L2
*/
contract ChildChannel is MessageProcessor, Ownable {
using Address for address;
address public child;
// root channel => receiver
mapping(address => address) public channelReceivers;
event SetRootChannel(address channel, address receiver);
event MessageSent(bytes message);
event MessageReceived(uint256 indexed stateId, address indexed sender, bytes message, string error);
// Matic testnnet 0xCf73231F28B7331BBe3124B907840A94851f9f11
// Matic mainnet 0x8397259c983751DAf40400790063935a11afa28a
constructor(address _child, address _master) {
child = _child;
transferOwnership(_master);
}
// Sender must be rootChannel in case of ERC20 tunnel
modifier validateSender(address sender) {
require(channelReceivers[sender] != address(0), 'ChildChannel: INVALID_SENDER_FROM_ROOT');
_;
}
// set rootChannel if not set already
function setRootChannel(address _rootChannel, address receiver) external onlyOwner {
require(_rootChannel != address(0), 'ChildChannel: Invalid channel.');
require(receiver != address(0), 'ChildChannel: Invalid receiver.');
channelReceivers[_rootChannel] = receiver;
emit SetRootChannel(_rootChannel, receiver);
}
function processMessageFromRoot(
uint256 stateId,
address rootMessageSender,
bytes calldata data
) public override {
require(msg.sender == child, 'ChildChannel: INVALID_SENDER');
_processMessageFromRoot(stateId, rootMessageSender, data);
}
/**
* @notice Emit message that can be received on Root Tunnel
* @dev Call the internal function when need to emit message
* @param message bytes message that will be sent to Root Tunnel
* some message examples -
* abi.encode(tokenId);
* abi.encode(tokenId, tokenMetadata);
* abi.encode(messageType, messageData);
*/
function sendMessageToRoot(bytes memory message) external onlyOwner {
emit MessageSent(message);
}
/**
* @notice Process message received from Root Tunnel
* @dev function needs to be implemented to handle message as per requirement
* This is called by onStateReceive function.
* Since it is called via a system call, any event will not be emitted during its execution.
* @param stateId unique state id
* @param sender root message sender
* @param message bytes message that was sent from Root Tunnel
*/
function _processMessageFromRoot(
uint256 stateId,
address sender,
bytes memory message
) internal validateSender(sender) {
address receiver = channelReceivers[sender];
require(receiver != address(0), 'ChildChannel: Invalid receiver');
(bool success, bytes memory returndata) = receiver.call(message);
if (!success) {
emit MessageReceived(stateId, sender, message, abi.decode(returndata,(string)));
} else {
emit MessageReceived(stateId, sender, message, '');
}
}
}
| set rootChannel if not set already | function setRootChannel(address _rootChannel, address receiver) external onlyOwner {
require(_rootChannel != address(0), 'ChildChannel: Invalid channel.');
require(receiver != address(0), 'ChildChannel: Invalid receiver.');
channelReceivers[_rootChannel] = receiver;
emit SetRootChannel(_rootChannel, receiver);
}
| 12,866,656 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title A NFT Marketplace
/// @author Joaquin Yañez
/// @notice You can sell of buy ERC1155 tokens safely and with low fees
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract Marketplace is Initializable, OwnableUpgradeable {
address private constant daiContractAddress =
0x6B175474E89094C44Da98b954EedeAC495271d0F;
address private constant linkContractAddress =
0x514910771AF9Ca656af840dff83E8264EcF986CA;
address private feeRecipient;
uint256 private feeAmount;
AggregatorV3Interface internal daiPriceFeed;
AggregatorV3Interface internal ethPriceFeed;
AggregatorV3Interface internal linkPriceFeed;
struct sellOffer {
address seller;
address tokenAddress;
uint256 amountOfTokens;
uint256 deadline;
uint256 packPrice;
}
mapping(uint256 => sellOffer) sellOffers;
/// @notice Event to be emitted on sell
/// @param _from The seller address
/// @param _tokenID The ID of the token that has been sold
/// @param _price Price for whole set of tokens
/// @param _deadline The deadline to accept and buy the offer
/// @param _amount Amount of tokens in the pack
event Sell(
address indexed _from,
uint256 indexed _tokenID,
uint256 indexed _price,
uint256 _deadline,
uint256 _amount
);
/// @notice Event to be emitted on offer cancel
/// @param _tokenID The ID of the token that has been sold
/// @param _when Timestamp when the offer was cancelled
event Cancel(uint256 indexed _tokenID, uint256 indexed _when);
/// @notice Event to be emitted on buy
/// @param _from The buyer address
/// @param _tokenID The ID of the token that has been sold
/// @param _paymentTokenIndex Index of the token used in the payment, 0 for ETH, 1 for DAI, 2 for LINK
/// @param _paymentToken Name of the token used in the payment
event Buy(
address indexed _from,
uint256 indexed _tokenID,
uint256 indexed _paymentTokenIndex,
string _paymentToken
);
/// @param _message Standard message to advice that the offer has been cancelled
event Expired(string _message);
/// @dev Function to replace the constructor, to make the contract upgradeable
function initialize() public initializer {
OwnableUpgradeable.__Ownable_init();
feeRecipient = 0xD215De1fc9E2514Cf274df3F2378597C7Be06Aca;
feeAmount = 100; // Basis points
daiPriceFeed = AggregatorV3Interface(
0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9
);
ethPriceFeed = AggregatorV3Interface(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
);
linkPriceFeed = AggregatorV3Interface(
0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c
);
}
/// @notice This function can not be called by someone different than the owner
/// @param _feeRecipient The new fee recipient address
function setFeeRecipient(address _feeRecipient) external onlyOwner {
feeRecipient = _feeRecipient;
}
/// @notice This function can not be called by someone different than the owner
/// @param _feeAmount The new fee amount (in basis points)
function setFeeAmount(uint256 _feeAmount) external onlyOwner {
feeAmount = _feeAmount;
}
/// @notice Function that returns the DAI price
/// @dev This function is intended to be internal but it is public for testing purposes
/// @return The amount of USD you get for each DAI, with 8 decimals
function getDaiPrice() public view returns (int256) {
(, int256 price, , , ) = daiPriceFeed.latestRoundData();
return price;
}
/// @notice Function that returns the ETH price
/// @dev This function is intended to be internal but it is public for testing purposes
/// @return The amount of USD you get for each ETH, with 8 decimals
function getEthPrice() public view returns (int256) {
(, int256 price, , , ) = ethPriceFeed.latestRoundData();
return price;
}
/// @notice Function that returns the LINK price
/// @dev This function is intended to be internal but it is public for testing purposes
/// @return The amount of USD you get for each LINK, with 8 decimals
function getLinkPrice() public view returns (int256) {
(, int256 price, , , ) = linkPriceFeed.latestRoundData();
return price;
}
/// @notice Creates a sell offer
/// @param _tokenAddress The address of the token that is going to be sold
/// @param _tokenID ID of the token that is going to be sold
/// @param _tokenAmount The amount of token in the pack
/// @param _deadlineInHours Deadline in hours
/// @param _price Price for the whole set
function createSellOffer(
address _tokenAddress,
uint256 _tokenID,
uint256 _tokenAmount,
uint256 _deadlineInHours,
uint256 _price
) external {
require(
sellOffers[_tokenID].seller == address(0),
"A sell offer with this ID already exists"
);
require(
IERC1155(_tokenAddress).balanceOf(msg.sender, _tokenID) > 0,
"You must have tokens to sell"
);
sellOffer storage newOffer = sellOffers[_tokenID];
newOffer.seller = msg.sender;
newOffer.tokenAddress = _tokenAddress;
newOffer.amountOfTokens = _tokenAmount;
newOffer.deadline = block.timestamp + (_deadlineInHours * 1 hours);
newOffer.packPrice = _price;
emit Sell(msg.sender, _tokenID, _price, _deadlineInHours, _tokenAmount);
}
/// @notice Deletes a sell offer, only can be called by the offer creator
/// @param _tokenID ID of the token being sold
function deleteSellOffer(uint256 _tokenID) external {
require(
sellOffers[_tokenID].seller == msg.sender,
"Only the sell offer creator can delete it"
);
delete sellOffers[_tokenID];
emit Cancel(_tokenID, block.timestamp);
}
/// @notice Check the seller of a specific offer
/// @dev This function is mainly intended for testing purposes
/// @param _tokenID ID of the token being sold
/// @return The seller of the respective token ID
function checkSeller(uint256 _tokenID) external view returns (address) {
return sellOffers[_tokenID].seller;
}
/// @notice Returns the price of the set in a specific token
/// @dev The pack price is multiplied by 1000, to handle the lack of floating point support in solidity
/// @param _tokenID a parameter just like in doxygen (must be followed by parameter name)
/// @param _paymentToken a parameter just like in doxygen (must be followed by parameter name)
/// @return price of the set in a specific token
function getOfferPrice(uint256 _tokenID, uint256 _paymentToken)
external
view
returns (uint256 price)
{
require(
_paymentToken >= 0 && _paymentToken <= 2,
"You can only choose between ETH, DAI and LINK"
);
if (_paymentToken == 0) {
uint256 ethPrice = uint256(getEthPrice());
price = (sellOffers[_tokenID].packPrice * 1000) / ethPrice;
} else if (_paymentToken == 1) {
uint256 daiPrice = uint256(getDaiPrice());
price = (sellOffers[_tokenID].packPrice * 1000) / daiPrice;
} else {
uint256 linkPrice = uint256(getLinkPrice());
price = (sellOffers[_tokenID].packPrice * 1000) / linkPrice;
}
}
/// @notice Accepts an offer, the user is able to pay with ETH, DAI, LINK. If the user pays with ETH the function takes the exact amount and returns the rest
/// @param _tokenID The ID of the token tha is being buyed
/// @param _paymentToken Index of the token used in the payment, 0 for ETH, 1 for DAI, 2 for LINK
function buyOffer(uint256 _tokenID, uint256 _paymentToken)
external
payable
{
require(
_paymentToken >= 0 && _paymentToken <= 2,
"You can only choose between ETH, DAI and LINK"
);
if (block.timestamp > sellOffers[_tokenID].deadline) {
delete sellOffers[_tokenID];
emit Cancel(_tokenID, sellOffers[_tokenID].deadline);
emit Expired("The offer has expired, please try with another one");
} else {
uint256 price = this.getOfferPrice(_tokenID, _paymentToken);
if (_paymentToken == 0) {
// The price is multiplied by 1e15 to convert the value to wei. Remember it was previously multiplied by 1e3
require(
msg.value >= price * 1e15,
"You are sending less money than needed"
);
if (msg.value > price * 1e15) {
payable(msg.sender).transfer(msg.value - (price * 1e15));
}
uint256 amountToFeeRecipient =
address(this).balance / feeAmount;
payable(feeRecipient).transfer(amountToFeeRecipient);
payable(sellOffers[_tokenID].seller).transfer(
address(this).balance
);
emit Buy(msg.sender, _tokenID, 0, "ETH");
} else if (_paymentToken == 1) {
// The price must be divided by 1000 on each use case to get the correct amount, because the price was previously multiplied by 1000
require(
IERC20(daiContractAddress).balanceOf(msg.sender) >=
price / 1000,
"Not enough balance to pay the token"
);
require(
IERC20(daiContractAddress).allowance(
msg.sender,
address(this)
) >= price / 1000,
"You must approve the contract to send the tokens"
);
uint256 feeToSend = (price / 1000) / feeAmount;
uint256 amountToSend = (price / 1000) - feeToSend;
IERC20(daiContractAddress).transferFrom(
msg.sender,
feeRecipient,
feeToSend
);
IERC20(daiContractAddress).transferFrom(
msg.sender,
sellOffers[_tokenID].seller,
amountToSend
);
emit Buy(msg.sender, _tokenID, 1, "DAI");
} else {
// The price must be divided by 1000 on each use case to get the correct amount, because the price was previously multiplied by 1000
require(
IERC20(linkContractAddress).balanceOf(msg.sender) >=
price / 1000,
"Not enough balance to pay the token"
);
require(
IERC20(linkContractAddress).allowance(
msg.sender,
address(this)
) >= price / 1000,
"You must approve the contract to send the tokens"
);
uint256 feeToSend = (price / 1000) / feeAmount;
uint256 amountToSend = (price / 1000) - feeToSend;
if (feeToSend == 0) {
feeToSend = 1;
}
IERC20(linkContractAddress).transferFrom(
msg.sender,
feeRecipient,
feeToSend
);
IERC20(linkContractAddress).transferFrom(
msg.sender,
sellOffers[_tokenID].seller,
amountToSend
);
emit Buy(msg.sender, _tokenID, 2, "LINK");
}
IERC1155(sellOffers[_tokenID].tokenAddress).safeTransferFrom(
sellOffers[_tokenID].seller,
msg.sender,
_tokenID,
sellOffers[_tokenID].amountOfTokens,
""
);
delete sellOffers[_tokenID];
}
}
}
| Function that returns the DAI price This function is intended to be internal but it is public for testing purposes return The amount of USD you get for each DAI, with 8 decimals | function getDaiPrice() public view returns (int256) {
(, int256 price, , , ) = daiPriceFeed.latestRoundData();
return price;
}
| 1,057,460 |
./full_match/4/0xC4eFeEec1e82d946244da5D40635ddD44Bc47e83/sources/contracts/goblinparty.sol | _safeMint's second argument now takes in a quantity, not a tokenId. | function mint(uint256 quantity) external payable {
require(quantity + _numberMinted(msg.sender) <= MAX_MINTS, "Exceeded the limit");
require(totalSupply() + quantity <= MAX_SUPPLY, "Not enough tokens left");
require(msg.value >= (mintRate * quantity), "Not enough ether sent");
_safeMint(msg.sender, quantity);
}
| 12,271,270 |
pragma solidity ^0.4.18;
import "zeppelin-solidity/contracts/math/SafeMath.sol";
import "../Upgradability/StorageConsumer.sol";
import "./OwnerRegistry.sol";
import "./Registry.sol";
/**
* @title OwnableRegistry
* @dev Registry of token ID's that are owned by another token from a different registry
*/
contract OwnableRegistry is Registry, StorageConsumer {
using SafeMath for uint256;
/* @dev Constructor for OwnableRegistry */
function OwnableRegistry(BaseStorage storage_) StorageConsumer(storage_) public {}
/**
* @dev Gets address for owner registry
*/
function ownerRegistry() public view returns (OwnerRegistry) {
return OwnerRegistry(_storage.getAddress("ownerRegistryAddress"));
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _storage.getUint("totalTokens");
}
/**
* @dev Gets the balance of the specified token
* @param _ownerTokenId token ID to query the balance of
* @return uint256 representing the amount owned by the passed token ID
*/
function balanceOf(uint256 _ownerTokenId) public view returns (uint256) {
return _storage.getUint(keccak256("ownerBalances", _ownerTokenId));
}
/**
* @dev Gets the list of tokens owned by a given token ID
* @param _ownerTokenId uint256 to query the tokens of
* @return uint256[] representing the list of tokens owned by the passed token ID
*/
function tokensOf(uint256 _ownerTokenId) public view returns (uint256[]) {
uint256 _ownerBalance = balanceOf(_ownerTokenId);
uint256[] memory _tokens = new uint256[](_ownerBalance);
for (uint256 i = 0; i < _ownerBalance; i++) {
_tokens[i] = getOwnedToken(_ownerTokenId, i);
}
return _tokens;
}
/**
* @dev Gets the owner id of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner id of
* @return ownerTokenId token ID currently marked as the owner id of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (uint256) {
uint256 ownerTokenId = getTokenOwner(_tokenId);
require(ownerTokenId != 0);
return ownerTokenId;
}
/**
* @dev Returns id of owner of entry
* @param _entryId The id of the entry
* @return id that owns the entry with the given id
*/
function ownerOfEntry(uint256 _entryId) public view returns (address) {
uint256 parentEntryId = ownerOf(_entryId);
return ownerRegistry().ownerOfEntry(parentEntryId);
}
/**
* @dev Mint token function
* @param _ownerTokenId uint256 ID of the token that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(uint256 _ownerTokenId, uint256 _tokenId) internal {
require(_ownerTokenId != 0);
addToken(_ownerTokenId, _tokenId);
}
/**
* @dev Internal function to get token owner by token ID
* @param tokenId uint256 ID of the token to get the owner for
* @return uint255 The ID of the token that owns the token an with ID of tokenId
*/
function getTokenOwner(uint256 tokenId) private view returns (uint256) {
return _storage.getUint(keccak256("tokenOwners", tokenId));
}
/**
* @dev Internal function to get an ID value from list of owned token ID's
* @param ownerTokenId The token ID for the owner of the token list
* @param tokenIndex uint256 The index of the token ID value within the list
* @return uint256 The token ID for the given owner and token index
*/
function getOwnedToken(uint256 ownerTokenId, uint256 tokenIndex) private view returns (uint256) {
return _storage.getUint(keccak256("ownedTokens", ownerTokenId, tokenIndex));
}
/**
* @dev Internal function to get the index of a token ID within the owned tokens list
* @param tokenId uint256 ID of the token to get the index for
* @return uint256 The index of the token for the given ID
*/
function getOwnedTokenIndex(uint256 tokenId) private view returns (uint256) {
return _storage.getUint(keccak256("ownedTokensIndex", tokenId));
}
/**
* @dev Internal function to add a token ID to the list of a given owner token ID
* @param _toOwnerTokenId uint256 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 owner token ID
*/
function addToken(uint256 _toOwnerTokenId, uint256 _tokenId) private {
require(getTokenOwner(_tokenId) == 0);
setTokenOwner(_tokenId, _toOwnerTokenId);
uint256 length = balanceOf(_toOwnerTokenId);
pushOwnedToken(_toOwnerTokenId, _tokenId);
setOwnedTokenIndex(_tokenId, length);
incrementTotalTokens();
}
/**
* @dev Internal function to increase totalTokens by 1
*/
function incrementTotalTokens() private {
_storage.setUint("totalTokens", totalSupply().add(1));
}
/**
* @dev Internal function to decrease totalTokens by 1
*/
function decrementTotalTokens() private {
_storage.setUint("totalTokens", totalSupply().sub(1));
}
/**
* @dev Internal function to set token owner by token ID
* @param tokenId uint256 ID of the token to set the owner for
* @param ownerTokenId uint256 The ID of the token owner
*/
function setTokenOwner(uint256 tokenId, uint256 ownerTokenId) private {
_storage.setUint(keccak256("tokenOwners", tokenId), ownerTokenId);
}
/**
* @dev Internal function to increment an owner's token balance by 1
* @param ownerTokenId uint256 The owner's token ID
*/
function incrementOwnerBalance(uint256 ownerTokenId) private {
_storage.setUint(keccak256("ownerBalances", ownerTokenId), balanceOf(ownerTokenId).add(1));
}
/**
* @dev Internal function to decrement an owner's token balance by 1
* @param ownerTokenId uint256 The owner's token ID
*/
function decrementOwnerBalance(uint256 ownerTokenId) private {
_storage.setUint(keccak256("ownerBalances", ownerTokenId), balanceOf(ownerTokenId).sub(1));
}
/**
* @dev Internal function to set an ID value within a list of owned token ID's
* @param ownerTokenId uint256 The token ID of the owner of the token list
* @param tokenIndex uint256 The index to set within the owned token list
* @param tokenId uint256 The ID of the token to set
*/
function setOwnedToken(uint256 ownerTokenId, uint256 tokenIndex, uint256 tokenId) private {
_storage.setUint(keccak256("ownedTokens", ownerTokenId, tokenIndex), tokenId);
}
/**
* @dev Internal function to append an ID value to a list of owned token ID's
* @param ownerTokenId uint256 The token ID of the owner of the token list
* @param tokenId uint256 The token ID to append
*/
function pushOwnedToken(uint256 ownerTokenId, uint256 tokenId) private {
_storage.setUint(keccak256("ownedTokens", ownerTokenId, balanceOf(ownerTokenId)), tokenId);
incrementOwnerBalance(ownerTokenId);
}
/**
* @dev Internal function to set the index of a token ID within the owned tokens list
* @param tokenId uint256 ID of the token to set the index for
* @param tokenIndex uint256 The token index to set for the given token ID
*/
function setOwnedTokenIndex(uint256 tokenId, uint256 tokenIndex) private {
_storage.setUint(keccak256("ownedTokensIndex", tokenId), tokenIndex);
}
}
| Gets the list of tokens owned by a given token ID _ownerTokenId uint256 to query the tokens of return uint256[] representing the list of tokens owned by the passed token ID/ | function tokensOf(uint256 _ownerTokenId) public view returns (uint256[]) {
uint256 _ownerBalance = balanceOf(_ownerTokenId);
uint256[] memory _tokens = new uint256[](_ownerBalance);
for (uint256 i = 0; i < _ownerBalance; i++) {
_tokens[i] = getOwnedToken(_ownerTokenId, i);
}
return _tokens;
}
| 14,043,038 |
./partial_match/1/0x31577476950ec86E2D6D99dcc756A35AEa14389a/sources/MultiProductEscrow.sol | The buyer can release the funds to the seller allowing the seller to withdraw the funds./ | function releaseFunds(string calldata transactionId)
public
onlyBuyer(transactionId)
{
transactions[transactionId].fundsReleased = true;
}
| 16,070,567 |
// File: contracts/interfaces/IAMB.sol
pragma solidity 0.4.24;
interface IAMB {
function messageSender() external view returns (address);
function maxGasPerTx() external view returns (uint256);
function transactionHash() external view returns (bytes32);
function messageId() external view returns (bytes32);
function messageSourceChainId() external view returns (bytes32);
function messageCallStatus(bytes32 _messageId) external view returns (bool);
function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32);
function failedMessageReceiver(bytes32 _messageId) external view returns (address);
function failedMessageSender(bytes32 _messageId) external view returns (address);
function requireToPassMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32);
function requireToConfirmMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32);
function requireToGetInformation(bytes32 _requestSelector, bytes _data) external returns (bytes32);
function sourceChainId() external view returns (uint256);
function destinationChainId() external view returns (uint256);
}
// File: contracts/upgradeability/EternalStorage.sol
pragma solidity 0.4.24;
/**
* @title EternalStorage
* @dev This contract holds all the necessary state variables to carry out the storage of any contract.
*/
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
// File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol
pragma solidity 0.4.24;
interface IUpgradeabilityOwnerStorage {
function upgradeabilityOwner() external view returns (address);
}
// File: contracts/upgradeable_contracts/Ownable.sol
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev This contract has an owner address providing basic authorization control
*/
contract Ownable is EternalStorage {
bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner());
/* solcov ignore next */
_;
}
/**
* @dev Throws if called by any account other than contract itself or owner.
*/
modifier onlyRelevantSender() {
// proxy owner if used through proxy, address(0) otherwise
require(
!address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
/* solcov ignore next */
_;
}
bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() public view returns (address) {
return addressStorage[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) external onlyOwner {
_setOwner(newOwner);
}
/**
* @dev Sets a new owner address
*/
function _setOwner(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(owner(), newOwner);
addressStorage[OWNER] = newOwner;
}
}
// File: contracts/upgradeable_contracts/Initializable.sol
pragma solidity 0.4.24;
contract Initializable is EternalStorage {
bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
function setInitialize() internal {
boolStorage[INITIALIZED] = true;
}
function isInitialized() public view returns (bool) {
return boolStorage[INITIALIZED];
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
pragma solidity ^0.4.24;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts/upgradeable_contracts/DecimalShiftBridge.sol
pragma solidity 0.4.24;
contract DecimalShiftBridge is EternalStorage {
using SafeMath for uint256;
bytes32 internal constant DECIMAL_SHIFT = 0x1e8ecaafaddea96ed9ac6d2642dcdfe1bebe58a930b1085842d8fc122b371ee5; // keccak256(abi.encodePacked("decimalShift"))
/**
* @dev Internal function for setting the decimal shift for bridge operations.
* Decimal shift can be positive, negative, or equal to zero.
* It has the following meaning: N tokens in the foreign chain are equivalent to N * pow(10, shift) tokens on the home side.
* @param _shift new value of decimal shift.
*/
function _setDecimalShift(int256 _shift) internal {
// since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values
require(_shift > -77 && _shift < 77);
uintStorage[DECIMAL_SHIFT] = uint256(_shift);
}
/**
* @dev Returns the value of foreign-to-home decimal shift.
* @return decimal shift.
*/
function decimalShift() public view returns (int256) {
return int256(uintStorage[DECIMAL_SHIFT]);
}
/**
* @dev Converts the amount of home tokens into the equivalent amount of foreign tokens.
* @param _value amount of home tokens.
* @return equivalent amount of foreign tokens.
*/
function _unshiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, -decimalShift());
}
/**
* @dev Converts the amount of foreign tokens into the equivalent amount of home tokens.
* @param _value amount of foreign tokens.
* @return equivalent amount of home tokens.
*/
function _shiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, decimalShift());
}
/**
* @dev Calculates _value * pow(10, _shift).
* @param _value amount of tokens.
* @param _shift decimal shift to apply.
* @return shifted value.
*/
function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) {
if (_shift == 0) {
return _value;
}
if (_shift > 0) {
return _value.mul(10**uint256(_shift));
}
return _value.div(10**uint256(-_shift));
}
}
// File: contracts/upgradeable_contracts/BasicTokenBridge.sol
pragma solidity 0.4.24;
contract BasicTokenBridge is EternalStorage, Ownable, DecimalShiftBridge {
using SafeMath for uint256;
event DailyLimitChanged(uint256 newLimit);
event ExecutionDailyLimitChanged(uint256 newLimit);
bytes32 internal constant MIN_PER_TX = 0xbbb088c505d18e049d114c7c91f11724e69c55ad6c5397e2b929e68b41fa05d1; // keccak256(abi.encodePacked("minPerTx"))
bytes32 internal constant MAX_PER_TX = 0x0f8803acad17c63ee38bf2de71e1888bc7a079a6f73658e274b08018bea4e29c; // keccak256(abi.encodePacked("maxPerTx"))
bytes32 internal constant DAILY_LIMIT = 0x4a6a899679f26b73530d8cf1001e83b6f7702e04b6fdb98f3c62dc7e47e041a5; // keccak256(abi.encodePacked("dailyLimit"))
bytes32 internal constant EXECUTION_MAX_PER_TX = 0xc0ed44c192c86d1cc1ba51340b032c2766b4a2b0041031de13c46dd7104888d5; // keccak256(abi.encodePacked("executionMaxPerTx"))
bytes32 internal constant EXECUTION_DAILY_LIMIT = 0x21dbcab260e413c20dc13c28b7db95e2b423d1135f42bb8b7d5214a92270d237; // keccak256(abi.encodePacked("executionDailyLimit"))
function totalSpentPerDay(uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))];
}
function totalExecutedPerDay(uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))];
}
function dailyLimit() public view returns (uint256) {
return uintStorage[DAILY_LIMIT];
}
function executionDailyLimit() public view returns (uint256) {
return uintStorage[EXECUTION_DAILY_LIMIT];
}
function maxPerTx() public view returns (uint256) {
return uintStorage[MAX_PER_TX];
}
function executionMaxPerTx() public view returns (uint256) {
return uintStorage[EXECUTION_MAX_PER_TX];
}
function minPerTx() public view returns (uint256) {
return uintStorage[MIN_PER_TX];
}
function withinLimit(uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalSpentPerDay(getCurrentDay()).add(_amount);
return dailyLimit() >= nextLimit && _amount <= maxPerTx() && _amount >= minPerTx();
}
function withinExecutionLimit(uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalExecutedPerDay(getCurrentDay()).add(_amount);
return executionDailyLimit() >= nextLimit && _amount <= executionMaxPerTx();
}
function getCurrentDay() public view returns (uint256) {
return now / 1 days;
}
function addTotalSpentPerDay(uint256 _day, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))] = totalSpentPerDay(_day).add(_value);
}
function addTotalExecutedPerDay(uint256 _day, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))] = totalExecutedPerDay(_day).add(_value);
}
function setDailyLimit(uint256 _dailyLimit) external onlyOwner {
require(_dailyLimit > maxPerTx() || _dailyLimit == 0);
uintStorage[DAILY_LIMIT] = _dailyLimit;
emit DailyLimitChanged(_dailyLimit);
}
function setExecutionDailyLimit(uint256 _dailyLimit) external onlyOwner {
require(_dailyLimit > executionMaxPerTx() || _dailyLimit == 0);
uintStorage[EXECUTION_DAILY_LIMIT] = _dailyLimit;
emit ExecutionDailyLimitChanged(_dailyLimit);
}
function setExecutionMaxPerTx(uint256 _maxPerTx) external onlyOwner {
require(_maxPerTx < executionDailyLimit());
uintStorage[EXECUTION_MAX_PER_TX] = _maxPerTx;
}
function setMaxPerTx(uint256 _maxPerTx) external onlyOwner {
require(_maxPerTx == 0 || (_maxPerTx > minPerTx() && _maxPerTx < dailyLimit()));
uintStorage[MAX_PER_TX] = _maxPerTx;
}
function setMinPerTx(uint256 _minPerTx) external onlyOwner {
require(_minPerTx > 0 && _minPerTx < dailyLimit() && _minPerTx < maxPerTx());
uintStorage[MIN_PER_TX] = _minPerTx;
}
/**
* @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters.
* @return minimum of maxPerTx parameter and remaining daily quota.
*/
function maxAvailablePerTx() public view returns (uint256) {
uint256 _maxPerTx = maxPerTx();
uint256 _dailyLimit = dailyLimit();
uint256 _spent = totalSpentPerDay(getCurrentDay());
uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0;
return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily;
}
function _setLimits(uint256[3] _limits) internal {
require(
_limits[2] > 0 && // minPerTx > 0
_limits[1] > _limits[2] && // maxPerTx > minPerTx
_limits[0] > _limits[1] // dailyLimit > maxPerTx
);
uintStorage[DAILY_LIMIT] = _limits[0];
uintStorage[MAX_PER_TX] = _limits[1];
uintStorage[MIN_PER_TX] = _limits[2];
emit DailyLimitChanged(_limits[0]);
}
function _setExecutionLimits(uint256[2] _limits) internal {
require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit
uintStorage[EXECUTION_DAILY_LIMIT] = _limits[0];
uintStorage[EXECUTION_MAX_PER_TX] = _limits[1];
emit ExecutionDailyLimitChanged(_limits[0]);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts/interfaces/ERC677.sol
pragma solidity 0.4.24;
contract ERC677 is ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(address, uint256, bytes) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) public returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool);
}
contract LegacyERC20 {
function transfer(address _spender, uint256 _value) public; // returns (bool);
function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool);
}
// File: contracts/interfaces/ERC677Receiver.sol
pragma solidity 0.4.24;
contract ERC677Receiver {
function onTokenTransfer(address _from, uint256 _value, bytes _data) external returns (bool);
}
// File: contracts/upgradeable_contracts/ERC677Storage.sol
pragma solidity 0.4.24;
contract ERC677Storage {
bytes32 internal constant ERC677_TOKEN = 0xa8b0ade3e2b734f043ce298aca4cc8d19d74270223f34531d0988b7d00cba21d; // keccak256(abi.encodePacked("erc677token"))
}
// File: contracts/libraries/Bytes.sol
pragma solidity 0.4.24;
/**
* @title Bytes
* @dev Helper methods to transform bytes to other solidity types.
*/
library Bytes {
/**
* @dev Converts bytes array to bytes32.
* Truncates bytes array if its size is more than 32 bytes.
* NOTE: This function does not perform any checks on the received parameter.
* Make sure that the _bytes argument has a correct length, not less than 32 bytes.
* A case when _bytes has length less than 32 will lead to the undefined behaviour,
* since assembly will read data from memory that is not related to the _bytes argument.
* @param _bytes to be converted to bytes32 type
* @return bytes32 type of the firsts 32 bytes array in parameter.
*/
function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) {
assembly {
result := mload(add(_bytes, 32))
}
}
/**
* @dev Truncate bytes array if its size is more than 20 bytes.
* NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes.
* @param _bytes to be converted to address type
* @return address included in the firsts 20 bytes of the bytes array in parameter.
*/
function bytesToAddress(bytes _bytes) internal pure returns (address addr) {
assembly {
addr := mload(add(_bytes, 20))
}
}
}
// File: contracts/upgradeable_contracts/ChooseReceiverHelper.sol
pragma solidity 0.4.24;
contract ChooseReceiverHelper {
/**
* @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data.
* @param _from address of tokens sender.
* @param _data passed data in the transfer message.
* @return address of the receiver on the other side.
*/
function chooseReceiver(address _from, bytes _data) internal view returns (address recipient) {
recipient = _from;
if (_data.length > 0) {
require(_data.length == 20);
recipient = Bytes.bytesToAddress(_data);
require(recipient != address(0));
require(recipient != bridgeContractOnOtherSide());
}
}
/* solcov ignore next */
function bridgeContractOnOtherSide() internal view returns (address);
}
// File: contracts/upgradeable_contracts/BaseERC677Bridge.sol
pragma solidity 0.4.24;
contract BaseERC677Bridge is BasicTokenBridge, ERC677Receiver, ERC677Storage, ChooseReceiverHelper {
function _erc677token() internal view returns (ERC677) {
return ERC677(addressStorage[ERC677_TOKEN]);
}
function setErc677token(address _token) internal {
require(AddressUtils.isContract(_token));
addressStorage[ERC677_TOKEN] = _token;
}
function onTokenTransfer(address _from, uint256 _value, bytes _data) external returns (bool) {
ERC677 token = _erc677token();
require(msg.sender == address(token));
require(withinLimit(_value));
addTotalSpentPerDay(getCurrentDay(), _value);
bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data);
return true;
}
/* solcov ignore next */
function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal;
}
// File: contracts/upgradeable_contracts/BaseOverdrawManagement.sol
pragma solidity 0.4.24;
/**
* @title BaseOverdrawManagement
* @dev This contract implements basic functionality for tracking execution bridge operations that are out of limits.
*/
contract BaseOverdrawManagement is EternalStorage {
event MediatorAmountLimitExceeded(address recipient, uint256 value, bytes32 indexed messageId);
event AmountLimitExceeded(address recipient, uint256 value, bytes32 indexed transactionHash, bytes32 messageId);
event AssetAboveLimitsFixed(bytes32 indexed messageId, uint256 value, uint256 remaining);
bytes32 internal constant OUT_OF_LIMIT_AMOUNT = 0x145286dc85799b6fb9fe322391ba2d95683077b2adf34dd576dedc437e537ba7; // keccak256(abi.encodePacked("outOfLimitAmount"))
/**
* @dev Total amount coins/tokens that were bridged from the other side and are out of execution limits.
* @return total amount of all bridge operations above limits.
*/
function outOfLimitAmount() public view returns (uint256) {
return uintStorage[OUT_OF_LIMIT_AMOUNT];
}
/**
* @dev Internal function for updating a total amount that is out of execution limits.
* @param _value new value for the total amount of bridge operations above limits.
*/
function setOutOfLimitAmount(uint256 _value) internal {
uintStorage[OUT_OF_LIMIT_AMOUNT] = _value;
}
/**
* @dev Internal function for retrieving information about out-of-limits bridge operation.
* @param _messageId id of the message that cause above-limits error.
* @return (address of the receiver, amount of coins/tokens in the bridge operation)
*/
function txAboveLimits(bytes32 _messageId) internal view returns (address recipient, uint256 value) {
recipient = addressStorage[keccak256(abi.encodePacked("txOutOfLimitRecipient", _messageId))];
value = uintStorage[keccak256(abi.encodePacked("txOutOfLimitValue", _messageId))];
}
/**
* @dev Internal function for updating information about tbe out-of-limits bridge operation.
* @param _recipient receiver specified in the bridge operation.
* @param _value amount of coins/tokens inside the bridge operation.
* @param _messageId id of the message that cause above-limits error.
*/
function setTxAboveLimits(address _recipient, uint256 _value, bytes32 _messageId) internal {
addressStorage[keccak256(abi.encodePacked("txOutOfLimitRecipient", _messageId))] = _recipient;
setTxAboveLimitsValue(_value, _messageId);
}
/**
* @dev Internal function for updating information about the remaining value of out-of-limits bridge operation.
* @param _value amount of coins/tokens inside the bridge operation.
* @param _messageId id of the message that cause above-limits error.
*/
function setTxAboveLimitsValue(uint256 _value, bytes32 _messageId) internal {
uintStorage[keccak256(abi.encodePacked("txOutOfLimitValue", _messageId))] = _value;
}
/* solcov ignore next */
function fixAssetsAboveLimits(bytes32 messageId, bool unlockOnForeign, uint256 valueToUnlock) external;
}
// File: contracts/upgradeable_contracts/ReentrancyGuard.sol
pragma solidity 0.4.24;
contract ReentrancyGuard {
function lock() internal returns (bool res) {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock"))
}
}
function setLock(bool _lock) internal {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock"))
}
}
}
// File: contracts/upgradeable_contracts/Upgradeable.sol
pragma solidity 0.4.24;
contract Upgradeable {
// Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract
modifier onlyIfUpgradeabilityOwner() {
require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner());
/* solcov ignore next */
_;
}
}
// File: contracts/upgradeable_contracts/Sacrifice.sol
pragma solidity 0.4.24;
contract Sacrifice {
constructor(address _recipient) public payable {
selfdestruct(_recipient);
}
}
// File: contracts/libraries/Address.sol
pragma solidity 0.4.24;
/**
* @title Address
* @dev Helper methods for Address type.
*/
library Address {
/**
* @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
* @param _receiver address that will receive the native tokens
* @param _value the amount of native tokens to send
*/
function safeSendValue(address _receiver, uint256 _value) internal {
if (!_receiver.send(_value)) {
(new Sacrifice).value(_value)(_receiver);
}
}
}
// File: contracts/libraries/SafeERC20.sol
pragma solidity 0.4.24;
/**
* @title SafeERC20
* @dev Helper methods for safe token transfers.
* Functions perform additional checks to be sure that token transfer really happened.
*/
library SafeERC20 {
using SafeMath for uint256;
/**
* @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks.
* @param _token address of the token contract
* @param _to address of the receiver
* @param _value amount of tokens to send
*/
function safeTransfer(address _token, address _to, uint256 _value) internal {
LegacyERC20(_token).transfer(_to, _value);
assembly {
if returndatasize {
returndatacopy(0, 0, 32)
if iszero(mload(0)) {
revert(0, 0)
}
}
}
}
/**
* @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks.
* @param _token address of the token contract
* @param _from address of the sender
* @param _value amount of tokens to send
*/
function safeTransferFrom(address _token, address _from, uint256 _value) internal {
LegacyERC20(_token).transferFrom(_from, address(this), _value);
assembly {
if returndatasize {
returndatacopy(0, 0, 32)
if iszero(mload(0)) {
revert(0, 0)
}
}
}
}
}
// File: contracts/upgradeable_contracts/Claimable.sol
pragma solidity 0.4.24;
/**
* @title Claimable
* @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.
*/
contract Claimable {
using SafeERC20 for address;
/**
* Throws if a given address is equal to address(0)
*/
modifier validAddress(address _to) {
require(_to != address(0));
/* solcov ignore next */
_;
}
/**
* @dev Withdraws the erc20 tokens or native coins from this contract.
* Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()).
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimValues(address _token, address _to) internal validAddress(_to) {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
/**
* @dev Internal function for withdrawing all native coins from the contract.
* @param _to address of the coins receiver.
*/
function claimNativeCoins(address _to) internal {
uint256 value = address(this).balance;
Address.safeSendValue(_to, value);
}
/**
* @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract.
* @param _token address of the claimed ERC20 token.
* @param _to address of the tokens receiver.
*/
function claimErc20Tokens(address _token, address _to) internal {
ERC20Basic token = ERC20Basic(_token);
uint256 balance = token.balanceOf(this);
_token.safeTransfer(_to, balance);
}
}
// File: contracts/upgradeable_contracts/VersionableBridge.sol
pragma solidity 0.4.24;
contract VersionableBridge {
function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
return (6, 1, 0);
}
/* solcov ignore next */
function getBridgeMode() external pure returns (bytes4);
}
// File: contracts/upgradeable_contracts/BasicAMBMediator.sol
pragma solidity 0.4.24;
/**
* @title BasicAMBMediator
* @dev Basic storage and methods needed by mediators to interact with AMB bridge.
*/
contract BasicAMBMediator is Ownable {
bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract"))
bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract"))
bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit"))
/**
* @dev Throws if caller on the other side is not an associated mediator.
*/
modifier onlyMediator {
require(msg.sender == address(bridgeContract()));
require(messageSender() == mediatorContractOnOtherSide());
_;
}
/**
* @dev Sets the AMB bridge contract address. Only the owner can call this method.
* @param _bridgeContract the address of the bridge contract.
*/
function setBridgeContract(address _bridgeContract) external onlyOwner {
_setBridgeContract(_bridgeContract);
}
/**
* @dev Sets the mediator contract address from the other network. Only the owner can call this method.
* @param _mediatorContract the address of the mediator contract.
*/
function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner {
_setMediatorContractOnOtherSide(_mediatorContract);
}
/**
* @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network.
* This value can't exceed the parameter maxGasPerTx defined on the AMB bridge.
* Only the owner can call this method.
* @param _requestGasLimit the gas limit for the message execution.
*/
function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner {
_setRequestGasLimit(_requestGasLimit);
}
/**
* @dev Get the AMB interface for the bridge contract address
* @return AMB interface for the bridge contract address
*/
function bridgeContract() public view returns (IAMB) {
return IAMB(addressStorage[BRIDGE_CONTRACT]);
}
/**
* @dev Tells the mediator contract address from the other network.
* @return the address of the mediator contract.
*/
function mediatorContractOnOtherSide() public view returns (address) {
return addressStorage[MEDIATOR_CONTRACT];
}
/**
* @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network.
* @return the gas limit for the message execution.
*/
function requestGasLimit() public view returns (uint256) {
return uintStorage[REQUEST_GAS_LIMIT];
}
/**
* @dev Stores a valid AMB bridge contract address.
* @param _bridgeContract the address of the bridge contract.
*/
function _setBridgeContract(address _bridgeContract) internal {
require(AddressUtils.isContract(_bridgeContract));
addressStorage[BRIDGE_CONTRACT] = _bridgeContract;
}
/**
* @dev Stores the mediator contract address from the other network.
* @param _mediatorContract the address of the mediator contract.
*/
function _setMediatorContractOnOtherSide(address _mediatorContract) internal {
addressStorage[MEDIATOR_CONTRACT] = _mediatorContract;
}
/**
* @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network.
* @param _requestGasLimit the gas limit for the message execution.
*/
function _setRequestGasLimit(uint256 _requestGasLimit) internal {
require(_requestGasLimit <= maxGasPerTx());
uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit;
}
/**
* @dev Tells the address that generated the message on the other network that is currently being executed by
* the AMB bridge.
* @return the address of the message sender.
*/
function messageSender() internal view returns (address) {
return bridgeContract().messageSender();
}
/**
* @dev Tells the id of the message originated on the other network.
* @return the id of the message originated on the other network.
*/
function messageId() internal view returns (bytes32) {
return bridgeContract().messageId();
}
/**
* @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network.
* @return the maximum gas limit value.
*/
function maxGasPerTx() internal view returns (uint256) {
return bridgeContract().maxGasPerTx();
}
}
// File: contracts/upgradeable_contracts/TransferInfoStorage.sol
pragma solidity 0.4.24;
contract TransferInfoStorage is EternalStorage {
/**
* @dev Stores the value of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _value amount of tokens bridged.
*/
function setMessageValue(bytes32 _messageId, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value;
}
/**
* @dev Tells the amount of tokens of a message sent to the AMB bridge.
* @return value representing amount of tokens.
*/
function messageValue(bytes32 _messageId) internal view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))];
}
/**
* @dev Stores the receiver of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _recipient receiver of the tokens bridged.
*/
function setMessageRecipient(bytes32 _messageId, address _recipient) internal {
addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient;
}
/**
* @dev Tells the receiver of a message sent to the AMB bridge.
* @return address of the receiver.
*/
function messageRecipient(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))];
}
/**
* @dev Sets that the message sent to the AMB bridge has been fixed.
* @param _messageId of the message sent to the bridge.
*/
function setMessageFixed(bytes32 _messageId) internal {
boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true;
}
/**
* @dev Tells if a message sent to the AMB bridge has been fixed.
* @return bool indicating the status of the message.
*/
function messageFixed(bytes32 _messageId) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))];
}
}
// File: contracts/upgradeable_contracts/TokenBridgeMediator.sol
pragma solidity 0.4.24;
/**
* @title TokenBridgeMediator
* @dev Common mediator functionality to handle operations related to token bridge messages sent to AMB bridge.
*/
contract TokenBridgeMediator is BasicAMBMediator, BasicTokenBridge, TransferInfoStorage {
event FailedMessageFixed(bytes32 indexed messageId, address recipient, uint256 value);
event TokensBridgingInitiated(address indexed sender, uint256 value, bytes32 indexed messageId);
event TokensBridged(address indexed recipient, uint256 value, bytes32 indexed messageId);
/**
* @dev Call AMB bridge to require the invocation of handleBridgedTokens method of the mediator on the other network.
* Store information related to the bridged tokens in case the message execution fails on the other network
* and the action needs to be fixed/rolled back.
* @param _from address of sender, if bridge operation fails, tokens will be returned to this address
* @param _receiver address of receiver on the other side, will eventually receive bridged tokens
* @param _value bridged amount of tokens
*/
function passMessage(address _from, address _receiver, uint256 _value) internal {
bytes4 methodSelector = this.handleBridgedTokens.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _receiver, _value);
bytes32 _messageId = bridgeContract().requireToPassMessage(
mediatorContractOnOtherSide(),
data,
requestGasLimit()
);
setMessageValue(_messageId, _value);
setMessageRecipient(_messageId, _from);
emit TokensBridgingInitiated(_from, _value, _messageId);
}
/**
* @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method
* to execute the Mint or Unlock accordingly.
* @param _recipient address that will receive the tokens
* @param _value amount of tokens to be received
*/
function handleBridgedTokens(address _recipient, uint256 _value) external onlyMediator {
if (withinExecutionLimit(_value)) {
addTotalExecutedPerDay(getCurrentDay(), _value);
executeActionOnBridgedTokens(_recipient, _value);
} else {
executeActionOnBridgedTokensOutOfLimit(_recipient, _value);
}
}
/**
* @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to
* fix/roll back the transferred assets on the other network.
* @param _messageId id of the message which execution failed.
*/
function requestFailedMessageFix(bytes32 _messageId) external {
require(!bridgeContract().messageCallStatus(_messageId));
require(bridgeContract().failedMessageReceiver(_messageId) == address(this));
require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide());
bytes4 methodSelector = this.fixFailedMessage.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _messageId);
bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit());
}
/**
* @dev Handles the request to fix transferred assets which bridged message execution failed on the other network.
* It uses the information stored by passMessage method when the assets were initially transferred
* @param _messageId id of the message which execution failed on the other network.
*/
function fixFailedMessage(bytes32 _messageId) external onlyMediator {
require(!messageFixed(_messageId));
address recipient = messageRecipient(_messageId);
uint256 value = messageValue(_messageId);
setMessageFixed(_messageId);
executeActionOnFixedTokens(recipient, value);
emit FailedMessageFixed(_messageId, recipient, value);
}
/* solcov ignore next */
function executeActionOnBridgedTokensOutOfLimit(address _recipient, uint256 _value) internal;
/* solcov ignore next */
function executeActionOnBridgedTokens(address _recipient, uint256 _value) internal;
/* solcov ignore next */
function executeActionOnFixedTokens(address _recipient, uint256 _value) internal;
}
// File: contracts/upgradeable_contracts/amb_erc677_to_erc677/BasicAMBErc677ToErc677.sol
pragma solidity 0.4.24;
/**
* @title BasicAMBErc677ToErc677
* @dev Common functionality for erc677-to-erc677 mediator intended to work on top of AMB bridge.
*/
contract BasicAMBErc677ToErc677 is
Initializable,
ReentrancyGuard,
Upgradeable,
Claimable,
VersionableBridge,
BaseOverdrawManagement,
BaseERC677Bridge,
TokenBridgeMediator
{
function initialize(
address _bridgeContract,
address _mediatorContract,
address _erc677token,
uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ]
uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ]
uint256 _requestGasLimit,
int256 _decimalShift,
address _owner
) public onlyRelevantSender returns (bool) {
require(!isInitialized());
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
setErc677token(_erc677token);
_setLimits(_dailyLimitMaxPerTxMinPerTxArray);
_setExecutionLimits(_executionDailyLimitExecutionMaxPerTxArray);
_setRequestGasLimit(_requestGasLimit);
_setDecimalShift(_decimalShift);
_setOwner(_owner);
setInitialize();
return isInitialized();
}
/**
* @dev Public getter for token contract.
* @return address of the used token contract
*/
function erc677token() public view returns (ERC677) {
return _erc677token();
}
function bridgeContractOnOtherSide() internal view returns (address) {
return mediatorContractOnOtherSide();
}
/**
* @dev Initiates the bridge operation that will lock the amount of tokens transferred and mint the tokens on
* the other network. The user should first call Approve method of the ERC677 token.
* @param _receiver address that will receive the minted tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(address _receiver, uint256 _value) external {
// This lock is to prevent calling passMessage twice if a ERC677 token is used.
// When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
// which will call passMessage.
require(!lock());
ERC677 token = erc677token();
address to = address(this);
require(withinLimit(_value));
addTotalSpentPerDay(getCurrentDay(), _value);
setLock(true);
token.transferFrom(msg.sender, to, _value);
setLock(false);
bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver));
}
function onTokenTransfer(address _from, uint256 _value, bytes _data) external returns (bool) {
ERC677 token = erc677token();
require(msg.sender == address(token));
if (!lock()) {
require(withinLimit(_value));
addTotalSpentPerDay(getCurrentDay(), _value);
}
bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data);
return true;
}
function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
return (1, 4, 0);
}
function getBridgeMode() external pure returns (bytes4 _data) {
return 0x76595b56; // bytes4(keccak256(abi.encodePacked("erc-to-erc-amb")))
}
/**
* @dev Execute the action to be performed when the bridge tokens are out of execution limits.
* @param _recipient address intended to receive the tokens
* @param _value amount of tokens to be received
*/
function executeActionOnBridgedTokensOutOfLimit(address _recipient, uint256 _value) internal {
bytes32 _messageId = messageId();
address recipient;
uint256 value;
(recipient, value) = txAboveLimits(_messageId);
require(recipient == address(0) && value == 0);
setOutOfLimitAmount(outOfLimitAmount().add(_value));
setTxAboveLimits(_recipient, _value, _messageId);
emit MediatorAmountLimitExceeded(_recipient, _value, _messageId);
}
/**
* @dev Fixes locked tokens, that were out of execution limits during the call to handleBridgedTokens
* @param messageId reference for bridge operation that was out of execution limits
* @param unlockOnOtherSide true if fixed tokens should be unlocked to the other side of the bridge
* @param valueToUnlock unlocked amount of tokens, should be less than saved txAboveLimitsValue.
* Should be less than maxPerTx(), if tokens need to be unlocked on the other side.
*/
function fixAssetsAboveLimits(bytes32 messageId, bool unlockOnOtherSide, uint256 valueToUnlock)
external
onlyIfUpgradeabilityOwner
{
(address recipient, uint256 value) = txAboveLimits(messageId);
require(recipient != address(0) && value > 0 && value >= valueToUnlock);
setOutOfLimitAmount(outOfLimitAmount().sub(valueToUnlock));
uint256 pendingValue = value.sub(valueToUnlock);
setTxAboveLimitsValue(pendingValue, messageId);
emit AssetAboveLimitsFixed(messageId, valueToUnlock, pendingValue);
if (unlockOnOtherSide) {
require(valueToUnlock <= maxPerTx());
passMessage(recipient, recipient, valueToUnlock);
}
}
}
// File: contracts/upgradeable_contracts/MediatorBalanceStorage.sol
pragma solidity 0.4.24;
/**
* @title MediatorBalanceStorage
* @dev Storage helpers for the mediator balance tracking.
*/
contract MediatorBalanceStorage is EternalStorage {
bytes32 internal constant MEDIATOR_BALANCE = 0x3db340e280667ee926fa8c51e8f9fcf88a0ff221a66d84d63b4778127d97d139; // keccak256(abi.encodePacked("mediatorBalance"))
/**
* @dev Tells the expected mediator balance.
* @return the current expected mediator balance.
*/
function mediatorBalance() public view returns (uint256) {
return uintStorage[MEDIATOR_BALANCE];
}
/**
* @dev Sets the expected mediator balance of the contract.
* @param _balance the new expected mediator balance value.
*/
function _setMediatorBalance(uint256 _balance) internal {
uintStorage[MEDIATOR_BALANCE] = _balance;
}
}
// File: contracts/upgradeable_contracts/amb_erc677_to_erc677/ForeignAMBErc677ToErc677.sol
pragma solidity 0.4.24;
/**
* @title ForeignAMBErc677ToErc677
* @dev Foreign side implementation for erc677-to-erc677 mediator intended to work on top of AMB bridge.
* It is designed to be used as an implementation contract of EternalStorageProxy contract.
*/
contract ForeignAMBErc677ToErc677 is BasicAMBErc677ToErc677, MediatorBalanceStorage {
using SafeERC20 for ERC677;
/**
* @dev Executes action on the request to withdraw tokens relayed from the other network
* @param _recipient address of tokens receiver
* @param _value amount of bridged tokens
*/
function executeActionOnBridgedTokens(address _recipient, uint256 _value) internal {
uint256 value = _unshiftValue(_value);
bytes32 _messageId = messageId();
_setMediatorBalance(mediatorBalance().sub(value));
erc677token().safeTransfer(_recipient, value);
emit TokensBridged(_recipient, value, _messageId);
}
/**
* @dev Initiates the bridge operation that will lock the amount of tokens transferred and mint the tokens on
* the other network. The user should first call Approve method of the ERC677 token.
* @param _receiver address that will receive the minted tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(address _receiver, uint256 _value) external {
// This lock is to prevent calling passMessage twice if a ERC677 token is used.
// When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
// which will call passMessage.
require(!lock());
ERC677 token = erc677token();
require(withinLimit(_value));
addTotalSpentPerDay(getCurrentDay(), _value);
setLock(true);
token.safeTransferFrom(msg.sender, _value);
setLock(false);
bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver));
}
/**
* @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract
* without the invocation of the required methods.
* @param _receiver the address that will receive the tokens on the other network
*/
function fixMediatorBalance(address _receiver) external onlyIfUpgradeabilityOwner validAddress(_receiver) {
uint256 balance = _erc677token().balanceOf(address(this));
uint256 expectedBalance = mediatorBalance();
require(balance > expectedBalance);
uint256 diff = balance - expectedBalance;
uint256 available = maxAvailablePerTx();
require(available > 0);
if (diff > available) {
diff = available;
}
addTotalSpentPerDay(getCurrentDay(), diff);
_setMediatorBalance(expectedBalance.add(diff));
passMessage(_receiver, _receiver, diff);
}
/**
* @dev Executes action on deposit of bridged tokens
* @param _from address of tokens sender
* @param _value requsted amount of bridged tokens
* @param _data alternative receiver, if specified
*/
function bridgeSpecificActionsOnTokenTransfer(
ERC677, /* _token */
address _from,
uint256 _value,
bytes _data
) internal {
if (!lock()) {
_setMediatorBalance(mediatorBalance().add(_value));
passMessage(_from, chooseReceiver(_from, _data), _value);
}
}
/**
* @dev Unlock back the amount of tokens that were bridged to the other network but failed.
* @param _recipient address that will receive the tokens
* @param _value amount of tokens to be received
*/
function executeActionOnFixedTokens(address _recipient, uint256 _value) internal {
_setMediatorBalance(mediatorBalance().sub(_value));
erc677token().safeTransfer(_recipient, _value);
}
/**
* @dev Allows to transfer any locked token on this contract that is not part of the bridge operations.
* @param _token address of the token, if it is not provided, native tokens will be transferred.
* @param _to address that will receive the locked tokens on this contract.
*/
function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner {
require(_token != address(_erc677token()));
claimValues(_token, _to);
}
}
| Converts bytes array to bytes32. Truncates bytes array if its size is more than 32 bytes. NOTE: This function does not perform any checks on the received parameter. Make sure that the _bytes argument has a correct length, not less than 32 bytes. A case when _bytes has length less than 32 will lead to the undefined behaviour, since assembly will read data from memory that is not related to the _bytes argument. _bytes to be converted to bytes32 type return bytes32 type of the firsts 32 bytes array in parameter./ | function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) {
assembly {
result := mload(add(_bytes, 32))
}
}
| 52,094 |
./partial_match/56/0xAb03a46A0e5cd32abF2071349B99Ba66cffCCc78/sources/MarketOracle.sol | See {PriceOracleInterface-getPrice}./ | function getPrice(uint256 id)
external
override
recoveryPhaseCheck
returns (uint256)
{
return _activeOracle().getPrice(id);
}
| 11,078,867 |
pragma solidity ^0.5.17;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Address used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => bool) private authorizedCallers; // Authorized Addresses to access this contract
struct Airline {
address Address;
bool isRegistered;
bool isFunded;
}
uint256 internal totalAirlines = 0; // Number of registered airlines
mapping(address => Airline) private airlines; // Registered airlines
mapping(address => uint256) private airlineBalances; // Balance for each airline
struct Flight {
address airlineAddress;
bytes32 flightNumber;
uint256 flightTime;
uint8 flightStatus;
}
bytes32[] private flightKeys;
mapping(bytes32 => Flight) private flights;
struct Insurance {
address insureeAddress;
uint256 amount;
address airlineAddress;
bytes32 flightNumber;
bool paid;
}
mapping(bytes32 => Insurance[]) private insurances;
mapping(address => uint256) private insureeBalances;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event CallerAuthorized(address callerAddress);
event AirlineRegistered(address airlineAddress);
event AirlineFunded(address airlineAddress, uint256 amount);
event AirlineVoted(address airlineAddress, address voterAddress);
event FlightRegistered(
address airlineAddress,
bytes32 flightNumber,
uint256 flightTime,
uint8 flightStatus
);
event InsurancePurchased(
address insureeAddress,
uint256 amount,
address airlineAddress,
bytes32 flightNumber
);
/**
* @dev Constructor
* The deploying Address becomes contractOwner
*/
constructor(address airlineAddress) public {
contractOwner = msg.sender;
totalAirlines = totalAirlines.add(1);
airlines[airlineAddress] = Airline(airlineAddress, true, false);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" Address to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireCallerAuthorized() {
require(
authorizedCallers[msg.sender] == true,
"Caller is not authorized to call this function"
);
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns (bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external requireContractOwner {
require(operational != mode, "Contract is already in this mode");
operational = mode;
}
function authorizeCaller(address callerAddress)
external
requireIsOperational
requireContractOwner
{
authorizedCallers[callerAddress] = true;
emit CallerAuthorized(callerAddress);
}
// function getBalance()
function isAirlineRegistered(address airlineAddress)
external
view
returns (bool)
{
return airlines[airlineAddress].isRegistered == true;
}
function isAirlineFunded(address airlineAddress)
external
view
returns (bool)
{
return airlines[airlineAddress].isFunded == true;
}
function isAirline(address airlineAddress) external view returns (bool) {
return
this.isAirlineRegistered(airlineAddress) &&
this.isAirlineFunded(airlineAddress);
}
function getNumberOfAirlines()
external
view
requireIsOperational
returns (uint256)
{
return totalAirlines;
}
function getFlightNumbers()
external
view
requireIsOperational
returns (bytes32[] memory)
{
bytes32[] memory fNumbers = new bytes32[](flightKeys.length);
for (uint256 i = 0; i < flightKeys.length; i++) {
fNumbers[i] = flights[flightKeys[i]].flightNumber;
}
return fNumbers;
}
function isInsurable(bytes32 flightNumber, address insureeAddress)
external
view
requireIsOperational
returns (bool)
{
bool retVal = true;
bytes32 flightKey = getFlightKey(flightNumber);
Insurance[] memory insurancesOfFlight = insurances[flightKey];
for (uint256 i = 0; i < insurancesOfFlight.length; i++) {
if (insurancesOfFlight[i].insureeAddress == insureeAddress) {
retVal = false;
break;
}
}
return retVal;
}
function flightExists(bytes32 flightNumber)
external
view
requireIsOperational
returns (bool)
{
bytes32 flightKey = getFlightKey(flightNumber);
Flight memory flight = flights[flightKey];
return flight.airlineAddress != address(0);
}
function getFlight(bytes32 flightNumber)
external
view
returns (
address,
bytes32,
uint256,
uint8
)
{
bytes32 flightKey = getFlightKey(flightNumber);
Flight memory flight = flights[flightKey];
return (
flight.airlineAddress,
flight.flightNumber,
flight.flightTime,
flight.flightStatus
);
}
function getInsureeBalance(address insureeAddress)
external
view
requireCallerAuthorized
returns (uint256)
{
return insureeBalances[insureeAddress];
}
function getAirlineBalances(address airlineAddress)
external
view
requireCallerAuthorized
returns (uint256)
{
return airlineBalances[airlineAddress];
}
function getFlightKey(bytes32 flightNumber) private view returns (bytes32) {
for (uint8 i = 0; i < flightKeys.length; i++) {
if (flights[flightKeys[i]].flightNumber == flightNumber) {
return flightKeys[i];
}
}
}
function setFlightStatus(bytes32 flightKey, uint8 statusCode)
external
requireIsOperational
requireCallerAuthorized
{
flights[flightKey].flightStatus = statusCode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address airlineAddress)
external
requireIsOperational
requireCallerAuthorized
{
totalAirlines = totalAirlines.add(1);
airlines[airlineAddress] = Airline(airlineAddress, true, false);
emit AirlineRegistered(airlineAddress);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fundAirline(address airlineAddress, uint256 amount)
public
payable
requireIsOperational
requireCallerAuthorized
{
airlineBalances[airlineAddress] = airlineBalances[airlineAddress].add(
amount
);
if (airlineBalances[airlineAddress] >= 10) {
airlines[airlineAddress].isFunded = true;
} else {
airlines[airlineAddress].isFunded = false;
}
emit AirlineFunded(airlineAddress, amount);
}
function registerFlight(
address airlineAddress,
bytes32 flightNumber,
uint256 flightTime,
uint8 flightStatus
) external requireIsOperational requireCallerAuthorized {
bytes32 flightKey = getFlightKey(
airlineAddress,
flightNumber,
flightTime
);
flights[flightKey] = Flight(
airlineAddress,
flightNumber,
flightTime,
flightStatus
);
flightKeys.push(flightKey);
emit FlightRegistered(
airlineAddress,
flightNumber,
flightTime,
flightStatus
);
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(
bytes32 flightNumber,
address insureeAddress,
uint256 amount
) external requireIsOperational requireCallerAuthorized {
bytes32 flightKey = getFlightKey(flightNumber);
Flight memory flight = flights[flightKey];
airlineBalances[flight.airlineAddress] = airlineBalances[
flight.airlineAddress
]
.add(amount);
Insurance memory insurance = Insurance(
insureeAddress,
amount,
flight.airlineAddress,
flight.flightNumber,
false
);
insurances[flightKey].push(insurance);
emit InsurancePurchased(
insureeAddress,
amount,
flight.airlineAddress,
flight.flightNumber
);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(bytes32 flightNumber)
external
requireIsOperational
requireCallerAuthorized
{
bytes32 flightKey = getFlightKey(flightNumber);
Insurance[] memory insurancesOfFlight = insurances[flightKey];
for (uint256 i = 0; i < insurancesOfFlight.length; i++) {
Insurance memory insurance = insurancesOfFlight[i];
if (
insurance.flightNumber == flightNumber &&
insurance.paid == false
) {
uint256 amountToCredit = insurance.amount.mul(150).div(100);
insureeBalances[insurance.insureeAddress] = insureeBalances[
insurance.insureeAddress
]
.add(amountToCredit);
insurance.paid = true;
airlineBalances[insurance.airlineAddress] = airlineBalances[
insurance.airlineAddress
]
.sub(amountToCredit);
break;
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address insureeAddress, uint256 amount)
external
requireIsOperational
requireCallerAuthorized
{
require(
insureeBalances[insureeAddress] >= amount,
"Insufficient funds for given insuree"
);
address payable payableInsuree = address(
uint160(address(insureeAddress))
);
uint256 availableAmount = insureeBalances[insureeAddress];
uint256 updatedAmount = availableAmount.sub(amount);
insureeBalances[insureeAddress] = updatedAmount;
payableInsuree.transfer(amount);
}
function getFlightKey(
address airline,
bytes32 flightNumber,
uint256 flightTime
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flightNumber, flightTime));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {}
}
| Buy insurance for a flight/ | function buy(
bytes32 flightNumber,
address insureeAddress,
uint256 amount
) external requireIsOperational requireCallerAuthorized {
bytes32 flightKey = getFlightKey(flightNumber);
Flight memory flight = flights[flightKey];
airlineBalances[flight.airlineAddress] = airlineBalances[
flight.airlineAddress
]
.add(amount);
Insurance memory insurance = Insurance(
insureeAddress,
amount,
flight.airlineAddress,
flight.flightNumber,
false
);
insurances[flightKey].push(insurance);
emit InsurancePurchased(
insureeAddress,
amount,
flight.airlineAddress,
flight.flightNumber
);
}
| 2,551,749 |
./partial_match/1/0x4eAa1Fb174C85A3ef6820E45c5e065AAfE1BAC71/sources/src/UnstakeRequestsManager.sol | @inheritdoc IUnstakeRequestsManagerWrite Handles incoming ether from the staking contract, increasing the allocatedETHForClaims counter by the value of the incoming allocatedETH. | function allocateETH() external payable onlyStakingContract {
allocatedETHForClaims += msg.value;
}
| 4,397,943 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
// File: @openzeppelin/contracts/math/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(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint a, uint b) internal pure returns (uint) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b > 0, errorMessage);
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint a, uint b) internal pure returns (uint) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint private constant _NOT_ENTERED = 1;
uint private constant _ENTERED = 2;
uint private _status;
constructor() internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/token/ERC20/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 (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint);
/**
* @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, uint 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 (uint);
/**
* @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, uint 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,
uint 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, uint 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, uint value);
}
// 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
* ====
*/
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.
uint 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, uint 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,
uint 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,
uint 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint;
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)
);
}
/**
* @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,
uint 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,
uint value
) internal {
uint newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
uint 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/GSN/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: @openzeppelin/contracts/token/ERC20/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 uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint 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 (uint) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint) {
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, uint 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 (uint)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint 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,
uint 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, uint 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, uint 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,
uint 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, uint 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, uint 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,
uint 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,
uint amount
) internal virtual {}
}
// File: contracts/protocol/IStrategy.sol
/*
version 1.2.0
Changes
Changes listed here do not affect interaction with other contracts (Vault and Controller)
- removed function assets(address _token) external view returns (bool);
- remove function deposit(uint), declared in IStrategyERC20
- add function setSlippage(uint _slippage);
- add function setDelta(uint _delta);
*/
interface IStrategy {
function admin() external view returns (address);
function controller() external view returns (address);
function vault() external view returns (address);
/*
@notice Returns address of underlying asset (ETH or ERC20)
@dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy
*/
function underlying() external view returns (address);
/*
@notice Returns total amount of underlying transferred from vault
*/
function totalDebt() external view returns (uint);
function performanceFee() external view returns (uint);
function slippage() external view returns (uint);
/*
@notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN
*/
function delta() external view returns (uint);
function setAdmin(address _admin) external;
function setController(address _controller) external;
function setPerformanceFee(uint _fee) external;
function setSlippage(uint _slippage) external;
function setDelta(uint _delta) external;
/*
@notice Returns amount of underlying asset locked in this contract
@dev Output may vary depending on price of liquidity provider token
where the underlying asset is invested
*/
function totalAssets() external view returns (uint);
/*
@notice Withdraw `_amount` underlying asset
@param amount Amount of underlying asset to withdraw
*/
function withdraw(uint _amount) external;
/*
@notice Withdraw all underlying asset from strategy
*/
function withdrawAll() external;
/*
@notice Sell any staking rewards for underlying and then deposit undelying
*/
function harvest() external;
/*
@notice Increase total debt if profit > 0 and total assets <= max,
otherwise transfers profit to vault.
@dev Guard against manipulation of external price feed by checking that
total assets is below factor of total debt
*/
function skim() external;
/*
@notice Exit from strategy
@dev Must transfer all underlying tokens back to vault
*/
function exit() external;
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
@dev _token must not be equal to underlying token
*/
function sweep(address _token) external;
}
// File: contracts/protocol/IStrategyERC20.sol
interface IStrategyERC20 is IStrategy {
/*
@notice Deposit `amount` underlying ERC20 token
@param amount Amount of underlying ERC20 token to deposit
*/
function deposit(uint _amount) external;
}
// File: contracts/protocol/IVault.sol
/*
version 1.2.0
Changes
- function deposit(uint) declared in IERC20Vault
*/
interface IVault {
function admin() external view returns (address);
function controller() external view returns (address);
function timeLock() external view returns (address);
/*
@notice For EthVault, must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
*/
function token() external view returns (address);
function strategy() external view returns (address);
function strategies(address _strategy) external view returns (bool);
function reserveMin() external view returns (uint);
function withdrawFee() external view returns (uint);
function paused() external view returns (bool);
function whitelist(address _addr) external view returns (bool);
function setWhitelist(address _addr, bool _approve) external;
function setAdmin(address _admin) external;
function setController(address _controller) external;
function setTimeLock(address _timeLock) external;
function setPause(bool _paused) external;
function setReserveMin(uint _reserveMin) external;
function setWithdrawFee(uint _fee) external;
/*
@notice Returns the amount of asset (ETH or ERC20) in the vault
*/
function balanceInVault() external view returns (uint);
/*
@notice Returns the estimate amount of asset in strategy
@dev Output may vary depending on price of liquidity provider token
where the underlying asset is invested
*/
function balanceInStrategy() external view returns (uint);
/*
@notice Returns amount of tokens invested strategy
*/
function totalDebtInStrategy() external view returns (uint);
/*
@notice Returns the total amount of asset in vault + total debt
*/
function totalAssets() external view returns (uint);
/*
@notice Returns minimum amount of tokens that should be kept in vault for
cheap withdraw
@return Reserve amount
*/
function minReserve() external view returns (uint);
/*
@notice Returns the amount of tokens available to be invested
*/
function availableToInvest() external view returns (uint);
/*
@notice Approve strategy
@param _strategy Address of strategy
*/
function approveStrategy(address _strategy) external;
/*
@notice Revoke strategy
@param _strategy Address of strategy
*/
function revokeStrategy(address _strategy) external;
/*
@notice Set strategy
@param _min Minimum undelying asset current strategy must return. Prevents slippage
*/
function setStrategy(address _strategy, uint _min) external;
/*
@notice Transfers asset in vault to strategy
*/
function invest() external;
/*
@notice Calculate amount of asset that can be withdrawn
@param _shares Amount of shares
@return Amount of asset that can be withdrawn
*/
function getExpectedReturn(uint _shares) external view returns (uint);
/*
@notice Withdraw asset
@param _shares Amount of shares to burn
@param _min Minimum amount of asset expected to return
*/
function withdraw(uint _shares, uint _min) external;
/*
@notice Transfer asset in vault to admin
@param _token Address of asset to transfer
@dev _token must not be equal to vault asset
*/
function sweep(address _token) external;
}
// File: contracts/protocol/IERC20Vault.sol
interface IERC20Vault is IVault {
/*
@notice Deposit undelying token into this vault
@param _amount Amount of token to deposit
*/
function deposit(uint _amount) external;
}
// File: contracts/protocol/IController.sol
interface IController {
function ADMIN_ROLE() external view returns (bytes32);
function HARVESTER_ROLE() external view returns (bytes32);
function admin() external view returns (address);
function treasury() external view returns (address);
function setAdmin(address _admin) external;
function setTreasury(address _treasury) external;
function grantRole(bytes32 _role, address _addr) external;
function revokeRole(bytes32 _role, address _addr) external;
/*
@notice Set strategy for vault
@param _vault Address of vault
@param _strategy Address of strategy
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(
address _vault,
address _strategy,
uint _min
) external;
// calls to strategy
/*
@notice Invest token in vault into strategy
@param _vault Address of vault
*/
function invest(address _vault) external;
function harvest(address _strategy) external;
function skim(address _strategy) external;
/*
@notice Withdraw from strategy to vault
@param _strategy Address of strategy
@param _amount Amount of underlying token to withdraw
@param _min Minimum amount of underlying token to withdraw
*/
function withdraw(
address _strategy,
uint _amount,
uint _min
) external;
/*
@notice Withdraw all from strategy to vault
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function withdrawAll(address _strategy, uint _min) external;
/*
@notice Exit from strategy
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function exit(address _strategy, uint _min) external;
}
// File: contracts/ERC20Vault.sol
/*
version 1.2.0
- renamed from Vault to ERC20Vault
- switch interface IVault to IERC20Vault
- switch interface IStrategy to IStrategyERC20
@dev Code logic has not changed since version 1.1.0
*/
contract ERC20Vault is IERC20Vault, ERC20, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint;
event SetStrategy(address strategy);
event ApproveStrategy(address strategy);
event RevokeStrategy(address strategy);
event SetWhitelist(address addr, bool approved);
address public override admin;
address public override controller;
address public override timeLock;
address public immutable override token;
address public override strategy;
// mapping of approved strategies
mapping(address => bool) public override strategies;
// percentange of token reserved in vault for cheap withdraw
uint public override reserveMin = 500;
uint private constant RESERVE_MAX = 10000;
// Denominator used to calculate fees
uint private constant FEE_MAX = 10000;
uint public override withdrawFee;
uint private constant WITHDRAW_FEE_CAP = 500; // upper limit to withdrawFee
bool public override paused;
// whitelisted addresses
// used to prevent flash loah attacks
mapping(address => bool) public override whitelist;
/*
@dev vault decimals must be equal to token decimals
*/
constructor(
address _controller,
address _timeLock,
address _token
)
public
ERC20(
string(abi.encodePacked("unagii_", ERC20(_token).name())),
string(abi.encodePacked("u", ERC20(_token).symbol()))
)
{
require(_controller != address(0), "controller = zero address");
require(_timeLock != address(0), "time lock = zero address");
_setupDecimals(ERC20(_token).decimals());
admin = msg.sender;
controller = _controller;
token = _token;
timeLock = _timeLock;
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier onlyTimeLock() {
require(msg.sender == timeLock, "!time lock");
_;
}
modifier onlyAdminOrController() {
require(msg.sender == admin || msg.sender == controller, "!authorized");
_;
}
modifier whenStrategyDefined() {
require(strategy != address(0), "strategy = zero address");
_;
}
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
/*
@dev modifier to prevent flash loan
@dev caller is restricted to EOA or whitelisted contract
@dev Warning: Users can have their funds stuck if shares is transferred to a contract
*/
modifier guard() {
require((msg.sender == tx.origin) || whitelist[msg.sender], "!whitelist");
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function setController(address _controller) external override onlyAdmin {
require(_controller != address(0), "controller = zero address");
controller = _controller;
}
function setTimeLock(address _timeLock) external override onlyTimeLock {
require(_timeLock != address(0), "time lock = zero address");
timeLock = _timeLock;
}
function setPause(bool _paused) external override onlyAdmin {
paused = _paused;
}
function setWhitelist(address _addr, bool _approve) external override onlyAdmin {
whitelist[_addr] = _approve;
emit SetWhitelist(_addr, _approve);
}
function setReserveMin(uint _reserveMin) external override onlyAdmin {
require(_reserveMin <= RESERVE_MAX, "reserve min > max");
reserveMin = _reserveMin;
}
function setWithdrawFee(uint _fee) external override onlyAdmin {
require(_fee <= WITHDRAW_FEE_CAP, "withdraw fee > cap");
withdrawFee = _fee;
}
function _balanceInVault() private view returns (uint) {
return IERC20(token).balanceOf(address(this));
}
/*
@notice Returns balance of tokens in vault
@return Amount of token in vault
*/
function balanceInVault() external view override returns (uint) {
return _balanceInVault();
}
function _balanceInStrategy() private view returns (uint) {
if (strategy == address(0)) {
return 0;
}
return IStrategyERC20(strategy).totalAssets();
}
/*
@notice Returns the estimate amount of token in strategy
@dev Output may vary depending on price of liquidity provider token
where the underlying token is invested
*/
function balanceInStrategy() external view override returns (uint) {
return _balanceInStrategy();
}
function _totalDebtInStrategy() private view returns (uint) {
if (strategy == address(0)) {
return 0;
}
return IStrategyERC20(strategy).totalDebt();
}
/*
@notice Returns amount of tokens invested strategy
*/
function totalDebtInStrategy() external view override returns (uint) {
return _totalDebtInStrategy();
}
function _totalAssets() private view returns (uint) {
return _balanceInVault().add(_totalDebtInStrategy());
}
/*
@notice Returns the total amount of tokens in vault + total debt
@return Total amount of tokens in vault + total debt
*/
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
function _minReserve() private view returns (uint) {
return _totalAssets().mul(reserveMin) / RESERVE_MAX;
}
/*
@notice Returns minimum amount of tokens that should be kept in vault for
cheap withdraw
@return Reserve amount
*/
function minReserve() external view override returns (uint) {
return _minReserve();
}
function _availableToInvest() private view returns (uint) {
if (strategy == address(0)) {
return 0;
}
uint balInVault = _balanceInVault();
uint reserve = _minReserve();
if (balInVault <= reserve) {
return 0;
}
return balInVault - reserve;
}
/*
@notice Returns amount of token available to be invested into strategy
@return Amount of token available to be invested into strategy
*/
function availableToInvest() external view override returns (uint) {
return _availableToInvest();
}
/*
@notice Approve strategy
@param _strategy Address of strategy to revoke
*/
function approveStrategy(address _strategy) external override onlyTimeLock {
require(_strategy != address(0), "strategy = zero address");
strategies[_strategy] = true;
emit ApproveStrategy(_strategy);
}
/*
@notice Revoke strategy
@param _strategy Address of strategy to revoke
*/
function revokeStrategy(address _strategy) external override onlyAdmin {
require(_strategy != address(0), "strategy = zero address");
strategies[_strategy] = false;
emit RevokeStrategy(_strategy);
}
/*
@notice Set strategy to approved strategy
@param _strategy Address of strategy used
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(address _strategy, uint _min)
external
override
onlyAdminOrController
{
require(strategies[_strategy], "!approved");
require(_strategy != strategy, "new strategy = current strategy");
require(
IStrategyERC20(_strategy).underlying() == token,
"strategy.token != vault.token"
);
require(
IStrategyERC20(_strategy).vault() == address(this),
"strategy.vault != vault"
);
// withdraw from current strategy
if (strategy != address(0)) {
IERC20(token).safeApprove(strategy, 0);
uint balBefore = _balanceInVault();
IStrategyERC20(strategy).exit();
uint balAfter = _balanceInVault();
require(balAfter.sub(balBefore) >= _min, "withdraw < min");
}
strategy = _strategy;
emit SetStrategy(strategy);
}
/*
@notice Invest token from vault into strategy.
Some token are kept in vault for cheap withdraw.
*/
function invest()
external
override
whenStrategyDefined
whenNotPaused
onlyAdminOrController
{
uint amount = _availableToInvest();
require(amount > 0, "available = 0");
IERC20(token).safeApprove(strategy, 0);
IERC20(token).safeApprove(strategy, amount);
IStrategyERC20(strategy).deposit(amount);
IERC20(token).safeApprove(strategy, 0);
}
/*
@notice Deposit token into vault
@param _amount Amount of token to transfer from `msg.sender`
*/
function deposit(uint _amount) external override whenNotPaused nonReentrant guard {
require(_amount > 0, "amount = 0");
uint totalUnderlying = _totalAssets();
uint totalShares = totalSupply();
/*
s = shares to mint
T = total shares before mint
d = deposit amount
A = total assets in vault + strategy before deposit
s / (T + s) = d / (A + d)
s = d / A * T
*/
uint shares;
if (totalShares == 0) {
shares = _amount;
} else {
shares = _amount.mul(totalShares).div(totalUnderlying);
}
_mint(msg.sender, shares);
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
}
function _getExpectedReturn(
uint _shares,
uint _balInVault,
uint _balInStrat
) private view returns (uint) {
/*
s = shares
T = total supply of shares
w = amount of underlying token to withdraw
U = total amount of redeemable underlying token in vault + strategy
s / T = w / U
w = s / T * U
*/
/*
total underlying = bal in vault + min(total debt, bal in strat)
if bal in strat > total debt, redeemable = total debt
else redeemable = bal in strat
*/
uint totalDebt = _totalDebtInStrategy();
uint totalUnderlying;
if (_balInStrat > totalDebt) {
totalUnderlying = _balInVault.add(totalDebt);
} else {
totalUnderlying = _balInVault.add(_balInStrat);
}
uint totalShares = totalSupply();
if (totalShares > 0) {
return _shares.mul(totalUnderlying) / totalShares;
}
return 0;
}
/*
@notice Calculate amount of underlying token that can be withdrawn
@param _shares Amount of shares
@return Amount of underlying token that can be withdrawn
*/
function getExpectedReturn(uint _shares) external view override returns (uint) {
uint balInVault = _balanceInVault();
uint balInStrat = _balanceInStrategy();
return _getExpectedReturn(_shares, balInVault, balInStrat);
}
/*
@notice Withdraw underlying token
@param _shares Amount of shares to burn
@param _min Minimum amount of underlying token to return
@dev Keep `guard` modifier, else attacker can deposit and then use smart
contract to attack from withdraw
*/
function withdraw(uint _shares, uint _min) external override nonReentrant guard {
require(_shares > 0, "shares = 0");
uint balInVault = _balanceInVault();
uint balInStrat = _balanceInStrategy();
uint withdrawAmount = _getExpectedReturn(_shares, balInVault, balInStrat);
// Must burn after calculating withdraw amount
_burn(msg.sender, _shares);
if (balInVault < withdrawAmount) {
// maximize withdraw amount from strategy
uint amountFromStrat = withdrawAmount;
if (balInStrat < withdrawAmount) {
amountFromStrat = balInStrat;
}
IStrategyERC20(strategy).withdraw(amountFromStrat);
uint balAfter = _balanceInVault();
uint diff = balAfter.sub(balInVault);
if (diff < amountFromStrat) {
// withdraw amount - withdraw amount from strat = amount to withdraw from vault
// diff = actual amount returned from strategy
// NOTE: withdrawAmount >= amountFromStrat
withdrawAmount = (withdrawAmount - amountFromStrat).add(diff);
}
// transfer to treasury
uint fee = withdrawAmount.mul(withdrawFee) / FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
withdrawAmount = withdrawAmount - fee;
IERC20(token).safeTransfer(treasury, fee);
}
}
require(withdrawAmount >= _min, "withdraw < min");
IERC20(token).safeTransfer(msg.sender, withdrawAmount);
}
/*
@notice Transfer token != underlying token in vault to admin
@param _token Address of token to transfer
@dev Must transfer token to admin
@dev _token must not be equal to underlying token
@dev Used to transfer token that was accidentally sent to this vault
*/
function sweep(address _token) external override onlyAdmin {
require(_token != token, "token = vault.token");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
} | / Must burn after calculating withdraw amount maximize withdraw amount from strategy withdraw amount - withdraw amount from strat = amount to withdraw from vault diff = actual amount returned from strategy NOTE: withdrawAmount >= amountFromStrat | function withdraw(uint _shares, uint _min) external override nonReentrant guard {
require(_shares > 0, "shares = 0");
uint balInVault = _balanceInVault();
uint balInStrat = _balanceInStrategy();
uint withdrawAmount = _getExpectedReturn(_shares, balInVault, balInStrat);
_burn(msg.sender, _shares);
if (balInVault < withdrawAmount) {
uint amountFromStrat = withdrawAmount;
if (balInStrat < withdrawAmount) {
amountFromStrat = balInStrat;
}
IStrategyERC20(strategy).withdraw(amountFromStrat);
uint balAfter = _balanceInVault();
uint diff = balAfter.sub(balInVault);
if (diff < amountFromStrat) {
withdrawAmount = (withdrawAmount - amountFromStrat).add(diff);
}
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
withdrawAmount = withdrawAmount - fee;
IERC20(token).safeTransfer(treasury, fee);
}
}
require(withdrawAmount >= _min, "withdraw < min");
IERC20(token).safeTransfer(msg.sender, withdrawAmount);
}
@param _token Address of token to transfer
@dev Must transfer token to admin
@dev _token must not be equal to underlying token
@dev Used to transfer token that was accidentally sent to this vault
| 6,140,010 |
pragma solidity ^0.5.16;
import "./CToken.sol";
/**
* @title Compound's CEther Contract
* @notice CToken which wraps Ether
* @author Compound
*/
contract CEther is CToken {
/**
* @notice Construct a new CEther money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
*/
constructor(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set the proper admin now that initialization is done
admin = admin_;
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Reverts upon any failure
*/
function mint() external payable {
(uint err,) = mintInternal(msg.value);
requireNoError(err, "mint failed");
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @dev Reverts upon any failure
*/
function repayBorrow() external payable {
(uint err,) = repayBorrowInternal(msg.value);
requireNoError(err, "repayBorrow failed");
}
/**
* @notice Sender repays a borrow belonging to borrower
* @dev Reverts upon any failure
* @param borrower the account with the debt being payed off
*/
function repayBorrowBehalf(address borrower) external payable {
(uint err,) = repayBorrowBehalfInternal(borrower, msg.value);
requireNoError(err, "repayBorrowBehalf failed");
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @dev Reverts upon any failure
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
*/
function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable {
(uint err,) = liquidateBorrowInternal(borrower, msg.value, cTokenCollateral);
requireNoError(err, "liquidateBorrow failed");
}
/**
* @notice Send Ether to CEther to mint
*/
function () external payable {
(uint err,) = mintInternal(msg.value);
requireNoError(err, "mint failed");
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of Ether, before this message
* @dev This excludes the value of the current message, if any
* @return The quantity of Ether owned by this contract
*/
function getCashPrior() internal view returns (uint) {
(MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value);
require(err == MathError.NO_ERROR);
return startingBalance;
}
/**
* @notice Perform the actual transfer in, which is a no-op
* @param from Address sending the Ether
* @param amount Amount of Ether being sent
* @return The actual amount of Ether transferred
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
// Sanity checks
require(msg.sender == from, "sender mismatch");
require(msg.value == amount, "value mismatch");
return amount;
}
function doTransferOut(address payable to, uint amount) internal {
/* Send the Ether, with minimal gas and revert on failure */
to.transfer(amount);
}
function requireNoError(uint errCode, string memory message) internal pure {
if (errCode == uint(Error.NO_ERROR)) {
return;
}
bytes memory fullMessage = new bytes(bytes(message).length + 5);
uint i;
for (i = 0; i < bytes(message).length; i++) {
fullMessage[i] = bytes(message)[i];
}
fullMessage[i+0] = byte(uint8(32));
fullMessage[i+1] = byte(uint8(40));
fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 )));
fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 )));
fullMessage[i+4] = byte(uint8(41));
require(errCode == uint(Error.NO_ERROR), string(fullMessage));
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
// unused function
// comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
import "./EIP20NonStandardInterface.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
function sweepToken(EIP20NonStandardInterface token) external;
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
| Gets balance of this contract in terms of Ether, before this message This excludes the value of the current message, if any return The quantity of Ether owned by this contract/ | function getCashPrior() internal view returns (uint) {
(MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value);
require(err == MathError.NO_ERROR);
return startingBalance;
}
| 1,636,378 |
pragma solidity ^0.5.0;
import { InterledgerProxy } from "./interfaces/InterledgerProxy.sol";
import { InterledgerReceiverInterface } from "sofie-interledger-contracts/contracts/InterledgerReceiverInterface.sol";
import { InterledgerSenderInterface } from "sofie-interledger-contracts/contracts/InterledgerSenderInterface.sol";
// This contract is owned and deployed by the IL owner (very likely the marketplace owner). PDS smart contracts will need to follow the protocol to interact with it.
contract InterledgerProxyImplementation is InterledgerProxy, InterledgerReceiverInterface, InterledgerSenderInterface {
enum InterledgerEventType {
RequestDecision
}
// InterledgerReceiverInterface compliance
// Forwards the interledger payload to all potential listeners and accepts the interledger event
function interledgerReceive(uint256 nonce, bytes memory data) public {
emit InterledgerDataReceived(data);
emit InterledgerEventAccepted(nonce);
}
// InterledgerSenderInterface compliance
// Can be called by interested parties to trigger an interledger operation with the marketplace
function triggerInterledger(bytes calldata dataPayload) external {
emit InterledgerEventSending(uint(InterledgerEventType.RequestDecision), dataPayload);
}
function interledgerCommit(uint256 id) public {}
function interledgerCommit(uint256 id, bytes memory data) public {}
function interledgerAbort(uint256 id, uint256 reason) public {}
} | Forwards the interledger payload to all potential listeners and accepts the interledger event | function interledgerReceive(uint256 nonce, bytes memory data) public {
emit InterledgerDataReceived(data);
emit InterledgerEventAccepted(nonce);
}
| 14,034,829 |
// SPDX-License-Identifier: MIT
/* solhint-disable var-name-mixedcase */
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./swap/ISwap.sol";
import "./SignataIdentity.sol";
/**
* @title Veriswap
* @notice Forked from AirSwap
*/
contract Veriswap is ISwap, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
bytes32 public constant DOMAIN_TYPEHASH =
keccak256(
abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"uint256 chainId,",
"address verifyingContract",
")"
)
);
bytes32 public constant ORDER_TYPEHASH =
keccak256(
abi.encodePacked(
"Order(",
"uint256 nonce,",
"uint256 expiry,",
"address signerWallet,",
"address signerToken,",
"uint256 signerAmount,",
"uint256 protocolFee,",
"address senderWallet,",
"address senderToken,",
"uint256 senderAmount",
")"
)
);
bytes32 public constant DOMAIN_NAME = keccak256("VERISWAP");
bytes32 public constant DOMAIN_VERSION = keccak256("1");
uint256 public immutable DOMAIN_CHAIN_ID;
bytes32 public immutable DOMAIN_SEPARATOR;
SignataIdentity private signataIdentity;
uint256 internal constant MAX_PERCENTAGE = 100;
uint256 internal constant MAX_SCALE = 77;
uint256 internal constant MAX_ERROR_COUNT = 6;
uint256 public constant FEE_DIVISOR = 10000;
/**
* @notice Double mapping of signers to nonce groups to nonce states
* @dev The nonce group is computed as nonce / 256, so each group of 256 sequential nonces uses the same key
* @dev The nonce states are encoded as 256 bits, for each nonce in the group 0 means available and 1 means used
*/
mapping(address => mapping(uint256 => uint256)) internal _nonceGroups;
mapping(address => address) public override authorized;
uint256 public protocolFee;
uint256 public protocolFeeLight;
address public protocolFeeWallet;
uint256 public rebateScale;
uint256 public rebateMax;
address public stakingToken;
constructor(
uint256 _protocolFee,
uint256 _protocolFeeLight,
address _protocolFeeWallet,
uint256 _rebateScale,
uint256 _rebateMax,
address _stakingToken,
address _signataIdentity
) {
require(_protocolFee < FEE_DIVISOR, "INVALID_FEE");
require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE");
require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET");
require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH");
require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH");
require(_stakingToken != address(0), "INVALID_STAKING_TOKEN");
uint256 currentChainId = getChainId();
DOMAIN_CHAIN_ID = currentChainId;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
DOMAIN_NAME,
DOMAIN_VERSION,
currentChainId,
this
)
);
protocolFee = _protocolFee;
protocolFeeLight = _protocolFeeLight;
protocolFeeWallet = _protocolFeeWallet;
rebateScale = _rebateScale;
rebateMax = _rebateMax;
stakingToken = _stakingToken;
signataIdentity = SignataIdentity(_signataIdentity);
}
/**
* @notice Atomic ERC20 Swap
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param enforceIdentity bool Require the maker to have a registered Signata Identity
* @param checkRisk bool Require the maker to check the Chainlink Risk Oracle
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swap(
address recipient,
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
bool enforceIdentity,
bool checkRisk,
uint8 v,
bytes32 r,
bytes32 s
) external override {
// Ensure the order is valid
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
enforceIdentity,
checkRisk,
v,
r,
s
);
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(signerWallet, recipient, signerAmount);
// Calculate and transfer protocol fee and any rebate
_transferProtocolFee(signerToken, signerWallet, signerAmount);
// Emit a Swap event
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
protocolFee,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Swap Atomic ERC20 Swap (Low Gas Usage)
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param enforceIdentity bool Require the maker to have a registered Signata Identity
* @param checkRisk bool Require the maker to check the Chainlink Risk Oracle
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function light(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
bool enforceIdentity,
bool checkRisk,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED");
// Ensure the expiry is not passed
require(expiry > block.timestamp, "EXPIRY_PASSED");
// Recover the signatory from the hash and signature
address signatory = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
ORDER_TYPEHASH,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
protocolFeeLight,
msg.sender,
senderToken,
senderAmount
)
)
)
),
v,
r,
s
);
// Ensure the signatory is not null
require(signatory != address(0), "SIGNATURE_INVALID");
// Ensure the nonce is not yet used and if not mark it used
require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED");
// Ensure the signatory is authorized by the signer wallet
if (signerWallet != signatory) {
require(authorized[signerWallet] == signatory, "UNAUTHORIZED");
}
if (enforceIdentity) {
signataIdentity.getDelegate(msg.sender);
require(
!signataIdentity.isLocked(msg.sender),
"Veriswap: The sender's identity is locked."
);
}
if (checkRisk) {
// TODO: drop in the chainlink integration here
}
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(
signerWallet,
msg.sender,
signerAmount
);
// Transfer fee from signer to feeWallet
IERC20(signerToken).safeTransferFrom(
signerWallet,
protocolFeeWallet,
signerAmount.mul(protocolFeeLight).div(FEE_DIVISOR)
);
// Emit a Swap event
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
protocolFeeLight,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Sender Buys an NFT (ERC721)
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC721 token transferred from the signer
* @param signerID uint256 Token ID transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param enforceIdentity bool Require the maker to have a registered Signata Identity
* @param checkRisk bool Require the maker to check the Chainlink Risk Oracle
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function buyNFT(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerID,
address senderToken,
uint256 senderAmount,
bool enforceIdentity,
bool checkRisk,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerID,
senderToken,
senderAmount,
enforceIdentity,
checkRisk,
v,
r,
s
);
// Transfer token from sender to signer
IERC20(senderToken).safeTransferFrom(
msg.sender,
signerWallet,
senderAmount
);
// Transfer token from signer to recipient
IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID);
// Calculate and transfer protocol fee and rebate
_transferProtocolFee(senderToken, msg.sender, senderAmount);
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerID,
protocolFee,
msg.sender,
senderToken,
senderAmount
);
}
/**
* @notice Sender Sells an NFT (ERC721)
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC721 token transferred from the sender
* @param senderID uint256 Token ID transferred from the sender
* @param enforceIdentity bool Require the maker to have a registered Signata Identity
* @param checkRisk bool Require the maker to check the Chainlink Risk Oracle
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function sellNFT(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderID,
bool enforceIdentity,
bool checkRisk,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderID,
enforceIdentity,
checkRisk,
v,
r,
s
);
// Transfer token from sender to signer
IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID);
// Transfer token from signer to recipient
IERC20(signerToken).safeTransferFrom(
signerWallet,
msg.sender,
signerAmount
);
// Calculate and transfer protocol fee and rebate
_transferProtocolFee(signerToken, signerWallet, signerAmount);
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerAmount,
protocolFee,
msg.sender,
senderToken,
senderID
);
}
/**
* @notice Signer and sender swap NFTs (ERC721)
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC721 token transferred from the signer
* @param signerID uint256 Token ID transferred from the signer
* @param senderToken address ERC721 token transferred from the sender
* @param senderID uint256 Token ID transferred from the sender
* @param enforceIdentity bool Require the maker to have a registered Signata Identity
* @param checkRisk bool Require the maker to check the Chainlink Risk Oracle
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function swapNFTs(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerID,
address senderToken,
uint256 senderID,
bool enforceIdentity,
bool checkRisk,
uint8 v,
bytes32 r,
bytes32 s
) public override {
_checkValidOrder(
nonce,
expiry,
signerWallet,
signerToken,
signerID,
senderToken,
senderID,
enforceIdentity,
checkRisk,
v,
r,
s
);
// Transfer token from sender to signer
IERC721(senderToken).transferFrom(msg.sender, signerWallet, senderID);
// Transfer token from signer to sender
IERC721(signerToken).transferFrom(signerWallet, msg.sender, signerID);
emit Swap(
nonce,
block.timestamp,
signerWallet,
signerToken,
signerID,
0,
msg.sender,
senderToken,
senderID
);
}
/**
* @notice Set the fee
* @param _protocolFee uint256 Value of the fee in basis points
*/
function setProtocolFee(uint256 _protocolFee) external onlyOwner {
// Ensure the fee is less than divisor
require(_protocolFee < FEE_DIVISOR, "INVALID_FEE");
protocolFee = _protocolFee;
emit SetProtocolFee(_protocolFee);
}
/**
* @notice Set the light fee
* @param _protocolFeeLight uint256 Value of the fee in basis points
*/
function setProtocolFeeLight(uint256 _protocolFeeLight) external onlyOwner {
// Ensure the fee is less than divisor
require(_protocolFeeLight < FEE_DIVISOR, "INVALID_FEE_LIGHT");
protocolFeeLight = _protocolFeeLight;
emit SetProtocolFeeLight(_protocolFeeLight);
}
/**
* @notice Set the fee wallet
* @param _protocolFeeWallet address Wallet to transfer fee to
*/
function setProtocolFeeWallet(address _protocolFeeWallet) external onlyOwner {
// Ensure the new fee wallet is not null
require(_protocolFeeWallet != address(0), "INVALID_FEE_WALLET");
protocolFeeWallet = _protocolFeeWallet;
emit SetProtocolFeeWallet(_protocolFeeWallet);
}
/**
* @notice Set scale
* @dev Only owner
* @param _rebateScale uint256
*/
function setRebateScale(uint256 _rebateScale) external onlyOwner {
require(_rebateScale <= MAX_SCALE, "SCALE_TOO_HIGH");
rebateScale = _rebateScale;
emit SetRebateScale(_rebateScale);
}
/**
* @notice Set max
* @dev Only owner
* @param _rebateMax uint256
*/
function setRebateMax(uint256 _rebateMax) external onlyOwner {
require(_rebateMax <= MAX_PERCENTAGE, "MAX_TOO_HIGH");
rebateMax = _rebateMax;
emit SetRebateMax(_rebateMax);
}
/**
* @notice Set the staking token
* @param newStakingToken address Token to check balances on
*/
function setStakingToken(address newStakingToken) external onlyOwner {
// Ensure the new staking token is not null
require(newStakingToken != address(0), "INVALID_FEE_WALLET");
stakingToken = newStakingToken;
emit SetStakingToken(newStakingToken);
}
/**
* @notice Authorize a signer
* @param signer address Wallet of the signer to authorize
* @dev Emits an Authorize event
*/
function authorize(address signer) external override {
require(signer != address(0), "SIGNER_INVALID");
authorized[msg.sender] = signer;
emit Authorize(signer, msg.sender);
}
/**
* @notice Revoke the signer
* @dev Emits a Revoke event
*/
function revoke() external override {
address tmp = authorized[msg.sender];
delete authorized[msg.sender];
emit Revoke(tmp, msg.sender);
}
/**
* @notice Cancel one or more nonces
* @dev Cancelled nonces are marked as used
* @dev Emits a Cancel event
* @dev Out of gas may occur in arrays of length > 400
* @param nonces uint256[] List of nonces to cancel
*/
function cancel(uint256[] calldata nonces) external override {
for (uint256 i = 0; i < nonces.length; i++) {
uint256 nonce = nonces[i];
if (_markNonceAsUsed(msg.sender, nonce)) {
emit Cancel(nonce, msg.sender);
}
}
}
/**
* @notice Validates Swap Order for any potential errors
* @param senderWallet address Wallet that would send the order
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param enforceIdentity bool Require the maker to have a registered Signata Identity
* @param checkRisk bool Require the maker to check the Chainlink Risk Oracle
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
* @return tuple of error count and bytes32[] memory array of error messages
*/
function check(
address senderWallet,
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
bool enforceIdentity,
bool checkRisk,
address senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) public view returns (uint256, bytes32[] memory) {
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
Order memory order;
uint256 errCount;
order.nonce = nonce;
order.expiry = expiry;
order.signerWallet = signerWallet;
order.signerToken = signerToken;
order.signerAmount = signerAmount;
order.enforceIdentity = enforceIdentity;
order.checkRisk = checkRisk;
order.senderToken = senderToken;
order.senderAmount = senderAmount;
order.v = v;
order.r = r;
order.s = s;
order.senderWallet = senderWallet;
bytes32 hashed = _getOrderHash(
order.nonce,
order.expiry,
order.signerWallet,
order.signerToken,
order.signerAmount,
order.enforceIdentity,
order.checkRisk,
order.senderWallet,
order.senderToken,
order.senderAmount
);
address signatory = _getSignatory(hashed, order.v, order.r, order.s);
if (signatory == address(0)) {
errors[errCount] = "SIGNATURE_INVALID";
errCount++;
}
if (order.expiry < block.timestamp) {
errors[errCount] = "EXPIRY_PASSED";
errCount++;
}
if (
order.signerWallet != signatory &&
authorized[order.signerWallet] != signatory
) {
errors[errCount] = "UNAUTHORIZED";
errCount++;
} else {
if (nonceUsed(signatory, order.nonce)) {
errors[errCount] = "NONCE_ALREADY_USED";
errCount++;
}
}
uint256 signerBalance = IERC20(order.signerToken).balanceOf(
order.signerWallet
);
uint256 signerAllowance = IERC20(order.signerToken).allowance(
order.signerWallet,
address(this)
);
uint256 feeAmount = order.signerAmount.mul(protocolFee).div(FEE_DIVISOR);
if (signerAllowance < order.signerAmount + feeAmount) {
errors[errCount] = "SIGNER_ALLOWANCE_LOW";
errCount++;
}
if (signerBalance < order.signerAmount + feeAmount) {
errors[errCount] = "SIGNER_BALANCE_LOW";
errCount++;
}
return (errCount, errors);
}
/**
* @notice Calculate output amount for an input score
* @param stakingBalance uint256
* @param feeAmount uint256
*/
function calculateDiscount(uint256 stakingBalance, uint256 feeAmount)
public
view
returns (uint256)
{
uint256 divisor = (uint256(10)**rebateScale).add(stakingBalance);
return rebateMax.mul(stakingBalance).mul(feeAmount).div(divisor).div(100);
}
/**
* @notice Calculates and refers fee amount
* @param wallet address
* @param amount uint256
*/
function calculateProtocolFee(address wallet, uint256 amount)
public
view
override
returns (uint256)
{
// Transfer fee from signer to feeWallet
uint256 feeAmount = amount.mul(protocolFee).div(FEE_DIVISOR);
if (feeAmount > 0) {
uint256 discountAmount = calculateDiscount(
IERC20(stakingToken).balanceOf(wallet),
feeAmount
);
return feeAmount - discountAmount;
}
return feeAmount;
}
/**
* @notice Returns true if the nonce has been used
* @param signer address Address of the signer
* @param nonce uint256 Nonce being checked
*/
function nonceUsed(address signer, uint256 nonce)
public
view
override
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
return (_nonceGroups[signer][groupKey] >> indexInGroup) & 1 == 1;
}
/**
* @notice Returns the current chainId using the chainid opcode
* @return id uint256 The chain id
*/
function getChainId() public view returns (uint256 id) {
// no-inline-assembly
assembly {
id := chainid()
}
}
/**
* @notice Marks a nonce as used for the given signer
* @param signer address Address of the signer for which to mark the nonce as used
* @param nonce uint256 Nonce to be marked as used
* @return bool True if the nonce was not marked as used already
*/
function _markNonceAsUsed(address signer, uint256 nonce)
internal
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
uint256 group = _nonceGroups[signer][groupKey];
// If it is already used, return false
if ((group >> indexInGroup) & 1 == 1) {
return false;
}
_nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup);
return true;
}
/**
* @notice Checks Order Expiry, Nonce, Signature
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
function _checkValidOrder(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
bool enforceIdentity,
bool checkRisk,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED");
// Ensure the expiry is not passed
require(expiry > block.timestamp, "EXPIRY_PASSED");
bytes32 hashed = _getOrderHash(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
enforceIdentity,
checkRisk,
msg.sender,
senderToken,
senderAmount
);
// Recover the signatory from the hash and signature
address signatory = _getSignatory(hashed, v, r, s);
// Ensure the signatory is not null
require(signatory != address(0), "SIGNATURE_INVALID");
// Ensure the nonce is not yet used and if not mark it used
require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED");
// Ensure the signatory is authorized by the signer wallet
if (signerWallet != signatory) {
require(authorized[signerWallet] == signatory, "UNAUTHORIZED");
}
if (enforceIdentity) {
// an unregistered address will throw "SignataIdentity: The identity must exist."
signataIdentity.getDelegate(msg.sender);
require(
!signataIdentity.isLocked(msg.sender),
"Veriswap: The sender's identity is locked."
);
}
if (checkRisk) {
// TODO: drop in the chainlink integration here
}
}
/**
* @notice Hash order parameters
* @param nonce uint256
* @param expiry uint256
* @param signerWallet address
* @param signerToken address
* @param signerAmount uint256
* @param senderToken address
* @param senderAmount uint256
* @return bytes32
*/
function _getOrderHash(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
bool enforceIdentity,
bool checkRisk,
address senderWallet,
address senderToken,
uint256 senderAmount
) internal view returns (bytes32) {
return
keccak256(
abi.encode(
ORDER_TYPEHASH,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
enforceIdentity,
checkRisk,
protocolFee,
senderWallet,
senderToken,
senderAmount
)
);
}
/**
* @notice Recover the signatory from a signature
* @param hash bytes32
* @param v uint8
* @param r bytes32
* @param s bytes32
*/
function _getSignatory(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal view returns (address) {
return
ecrecover(
keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)),
v,
r,
s
);
}
/**
* @notice Calculates and transfers protocol fee and rebate
* @param sourceToken address
* @param sourceWallet address
* @param amount uint256
*/
function _transferProtocolFee(
address sourceToken,
address sourceWallet,
uint256 amount
) internal {
// Transfer fee from signer to feeWallet
uint256 feeAmount = amount.mul(protocolFee).div(FEE_DIVISOR);
if (feeAmount > 0) {
uint256 discountAmount = calculateDiscount(
IERC20(stakingToken).balanceOf(msg.sender),
feeAmount
);
if (discountAmount > 0) {
// Transfer fee from signer to sender
IERC20(sourceToken).safeTransferFrom(
sourceWallet,
msg.sender,
discountAmount
);
// Transfer fee from signer to feeWallet
IERC20(sourceToken).safeTransferFrom(
sourceWallet,
protocolFeeWallet,
feeAmount - discountAmount
);
} else {
IERC20(sourceToken).safeTransferFrom(
sourceWallet,
protocolFeeWallet,
feeAmount
);
}
}
}
} | Checks Order Expiry, Nonce, Signature nonce uint256 Unique and should be sequential expiry uint256 Expiry in seconds since 1 January 1970 signerWallet address Wallet of the signer signerToken address ERC20 token transferred from the signer signerAmount uint256 Amount transferred from the signer senderToken address ERC20 token transferred from the sender senderAmount uint256 Amount transferred from the sender v uint8 "v" value of the ECDSA signature r bytes32 "r" value of the ECDSA signature s bytes32 "s" value of the ECDSA signature/ Ensure the expiry is not passed Recover the signatory from the hash and signature Ensure the signatory is not null Ensure the nonce is not yet used and if not mark it used Ensure the signatory is authorized by the signer wallet an unregistered address will throw "SignataIdentity: The identity must exist." TODO: drop in the chainlink integration here | function _checkValidOrder(
uint256 nonce,
uint256 expiry,
address signerWallet,
address signerToken,
uint256 signerAmount,
address senderToken,
uint256 senderAmount,
bool enforceIdentity,
bool checkRisk,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(DOMAIN_CHAIN_ID == getChainId(), "CHAIN_ID_CHANGED");
require(expiry > block.timestamp, "EXPIRY_PASSED");
bytes32 hashed = _getOrderHash(
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
enforceIdentity,
checkRisk,
msg.sender,
senderToken,
senderAmount
);
address signatory = _getSignatory(hashed, v, r, s);
require(signatory != address(0), "SIGNATURE_INVALID");
require(_markNonceAsUsed(signatory, nonce), "NONCE_ALREADY_USED");
if (signerWallet != signatory) {
require(authorized[signerWallet] == signatory, "UNAUTHORIZED");
}
if (enforceIdentity) {
signataIdentity.getDelegate(msg.sender);
require(
!signataIdentity.isLocked(msg.sender),
"Veriswap: The sender's identity is locked."
);
}
if (checkRisk) {
}
}
| 5,389,387 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.