file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
./full_match/288/0x676971096aF637B196f6501818ae8d9c14EBa56b/sources/contracts/liquidate/SwapCenterBoba.sol
|
Swap the tokens with pre-defined routes. tokenIn Address of the input token. tokenOut Address of the output token. amountIn Amount of the input token. minAmountOut The minimum amount of the output token expected to receive. If the output amount is smaller than this value, the transaction will be reverted. address swapContract = swapImplementation[exchangeId] ISwapImplementation(swapContract).swap(curSellPath);
|
function swapExactTokenIn(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut) external override payable nonReentrant returns (uint256) {
if(isETH(tokenIn)){
require(msg.value == amountIn, "Amount of Ether sent doesn't match amountIn argument");
require(msg.value == 0, "Shouldn't receive Ether when the tokenIn is not Ether");
IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);
}
Route memory curRoute = routes[tokenIn][tokenOut];
uint256 exchangeLen = curRoute.exchangeOrder.length;
require(exchangeLen > 0, "Undefined pair");
for(uint256 i = 0; i < exchangeLen; i++) {
address[] memory curSellPath = curRoute.path[i];
uint256 exchangeId = curRoute.exchangeOrder[i];
if(exchangeId == OOLONGSWAP_ID) {
_swapExactTokenIn_uniswapType(0x17C83E2B96ACfb5190d63F5E46d93c107eC0b514, curSellPath);
_swapExactTokenIn_uniswapType(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506, curSellPath);
_swapRemoveCurveLiquidity(curSellPath);
_swapAddCurveLiquidity(curSellPath);
_swapRmLiq_uniswapType(0x17C83E2B96ACfb5190d63F5E46d93c107eC0b514, curSellPath);
_swapRmLiq_uniswapType(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506, curSellPath);
_swapDepositVault(curSellPath);
_swapWETH(curSellPath);
revert("exchange id not supported");
}
}
uint256 lastAmountOut;
if(tokenOut == ETH_ADDRESS) {
lastAmountOut = address(this).balance;
require(lastAmountOut >= minAmountOut, "acquired too few Ether");
require(success, "failed to send ETH to msg.sender");
lastAmountOut = IERC20(tokenOut).balanceOf(address(this));
require(lastAmountOut >= minAmountOut, "acquired too few output tokens");
IERC20(tokenOut).safeTransfer(msg.sender, lastAmountOut);
}
return lastAmountOut;
}
| 7,106,294
|
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY886() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF698(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER57(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE343(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE196(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM951(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER641(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL12(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER192() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function TOTALSUPPLY886() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF698(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER57(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER194(_MSGSENDER192(), recipient, amount);
return true;
}
function ALLOWANCE343(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE196(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE501(_MSGSENDER192(), spender, amount);
return true;
}
function TRANSFERFROM951(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER194(sender, recipient, amount);
_APPROVE501(sender, _MSGSENDER192(), _allowances[sender][_MSGSENDER192()].SUB39(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE73(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].ADD377(addedValue));
return true;
}
function DECREASEALLOWANCE445(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].SUB39(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER194(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB39(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD377(amount);
emit TRANSFER641(sender, recipient, amount);
}
function _MINT845(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD377(amount);
_balances[account] = _balances[account].ADD377(amount);
emit TRANSFER641(address(0), account, amount);
}
function _BURN745(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB39(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB39(amount);
emit TRANSFER641(account, address(0), amount);
}
function _APPROVE501(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL12(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private TokenmaxSupply = 2500*10**18;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME395() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS28() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function MAXSUPPLY198() public view returns (uint256) { //inject NONSTANDARD NAMING
return TokenmaxSupply;
}
}
library SafeMath {
function ADD377(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB39(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB39(a, b, "SafeMath: subtraction overflow");
}
function SUB39(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL593(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV750(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV750(a, b, "SafeMath: division by zero");
}
function DIV750(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function ISCONTRACT755(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function SAFETRANSFER74(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFER57.selector, to, value));
}
function SAFETRANSFERFROM551(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFERFROM951.selector, from, to, value));
}
function SAFEAPPROVE429(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE343(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.APPROVE196.selector, spender, value));
}
function CALLOPTIONALRETURN536(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT755(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract YFIG is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
mapping (address => bool) public minters;
constructor () public ERC20Detailed("yfipaprika.finance", "YFIG", 18) {
governance = tx.origin;
}
function MINT662(address account, uint256 amount) public { //inject NONSTANDARD NAMING
require(TOTALSUPPLY886() + amount <= MAXSUPPLY198(), "Supply Max Reached");
require(minters[msg.sender], "!minter");
_MINT845(account, amount);
}
function BURN585(uint256 amount) external { //inject NONSTANDARD NAMING
require(amount != 0, "you cannot burn zero amount");
_BURN745(msg.sender, amount);
}
function SETGOVERNANCE8(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function ADDMINTER497(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = true;
}
function REMOVEMINTER463(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = false;
}
}
|
inject NONSTANDARD NAMING
|
function _MINT845(address account, uint amount) internal {
| 7,321,030
|
pragma solidity ^0.4.18;
contract FullERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
uint256 public totalSupply;
uint8 public decimals;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
}
contract RewardDistributable {
event TokensRewarded(address indexed player, address rewardToken, uint rewards, address requester, uint gameId, uint block);
event ReferralRewarded(address indexed referrer, address indexed player, address rewardToken, uint rewards, uint gameId, uint block);
event ReferralRegistered(address indexed player, address indexed referrer);
/// @dev Calculates and transfers the rewards to the player.
function transferRewards(address player, uint entryAmount, uint gameId) public;
/// @dev Returns the total number of tokens, across all approvals.
function getTotalTokens(address tokenAddress) public constant returns(uint);
/// @dev Returns the total number of supported reward token contracts.
function getRewardTokenCount() public constant returns(uint);
/// @dev Gets the total number of approvers.
function getTotalApprovers() public constant returns(uint);
/// @dev Gets the reward rate inclusive of referral bonus.
function getRewardRate(address player, address tokenAddress) public constant returns(uint);
/// @dev Adds a requester to the whitelist.
/// @param requester The address of a contract which will request reward transfers
function addRequester(address requester) public;
/// @dev Removes a requester from the whitelist.
/// @param requester The address of a contract which will request reward transfers
function removeRequester(address requester) public;
/// @dev Adds a approver address. Approval happens with the token contract.
/// @param approver The approver address to add to the pool.
function addApprover(address approver) public;
/// @dev Removes an approver address.
/// @param approver The approver address to remove from the pool.
function removeApprover(address approver) public;
/// @dev Updates the reward rate
function updateRewardRate(address tokenAddress, uint newRewardRate) public;
/// @dev Updates the token address of the payment type.
function addRewardToken(address tokenAddress, uint newRewardRate) public;
/// @dev Updates the token address of the payment type.
function removeRewardToken(address tokenAddress) public;
/// @dev Updates the referral bonus rate
function updateReferralBonusRate(uint newReferralBonusRate) public;
/// @dev Registers the player with the given referral code
/// @param player The address of the player
/// @param referrer The address of the referrer
function registerReferral(address player, address referrer) public;
/// @dev Transfers any tokens to the owner
function destroyRewards() public;
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract 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;
}
}
contract RewardDistributor is RewardDistributable, Ownable {
using SafeMath for uint256;
struct RewardSource {
address rewardTokenAddress;
uint96 rewardRate; // 1 token for every reward rate (in wei)
}
RewardSource[] public rewardSources;
mapping(address => bool) public approvedRewardSources;
mapping(address => bool) public requesters; // distribution requesters
address[] public approvers; // distribution approvers
mapping(address => address) public referrers; // player -> referrer
uint public referralBonusRate;
modifier onlyRequesters() {
require(requesters[msg.sender] || (msg.sender == owner));
_;
}
modifier validRewardSource(address tokenAddress) {
require(approvedRewardSources[tokenAddress]);
_;
}
function RewardDistributor(uint256 rewardRate, address tokenAddress) public {
referralBonusRate = 10;
addRewardToken(tokenAddress, rewardRate);
}
/// @dev Calculates and transfers the rewards to the player.
function transferRewards(address player, uint entryAmount, uint gameId) public onlyRequesters {
// loop through all reward tokens, since we never really expect more than 2, this should be ok wrt gas
for (uint i = 0; i < rewardSources.length; i++) {
transferRewardsInternal(player, entryAmount, gameId, rewardSources[i]);
}
}
/// @dev Returns the total number of tokens, across all approvals.
function getTotalTokens(address tokenAddress) public constant validRewardSource(tokenAddress) returns(uint) {
for (uint j = 0; j < rewardSources.length; j++) {
if (rewardSources[j].rewardTokenAddress == tokenAddress) {
FullERC20 rewardToken = FullERC20(rewardSources[j].rewardTokenAddress);
uint total = rewardToken.balanceOf(this);
for (uint i = 0; i < approvers.length; i++) {
address approver = approvers[i];
uint allowance = rewardToken.allowance(approver, this);
total = total.add(allowance);
}
return total;
}
}
return 0;
}
/// @dev Get reward token count
function getRewardTokenCount() public constant returns(uint) {
return rewardSources.length;
}
/// @dev Gets the total number of approvers.
function getTotalApprovers() public constant returns(uint) {
return approvers.length;
}
/// @dev Gets the reward rate inclusive of bonus.
/// This is meant to be used by dividing the total purchase amount in wei by this amount.
function getRewardRate(address player, address tokenAddress) public constant validRewardSource(tokenAddress) returns(uint) {
for (uint j = 0; j < rewardSources.length; j++) {
if (rewardSources[j].rewardTokenAddress == tokenAddress) {
RewardSource storage rewardSource = rewardSources[j];
uint256 rewardRate = rewardSource.rewardRate;
uint bonusRate = referrers[player] == address(0) ? 0 : referralBonusRate;
return rewardRate.mul(100).div(100 + bonusRate);
}
}
return 0;
}
/// @dev Adds a requester to the whitelist.
/// @param requester The address of a contract which will request reward transfers
function addRequester(address requester) public onlyOwner {
require(!requesters[requester]);
requesters[requester] = true;
}
/// @dev Removes a requester from the whitelist.
/// @param requester The address of a contract which will request reward transfers
function removeRequester(address requester) public onlyOwner {
require(requesters[requester]);
requesters[requester] = false;
}
/// @dev Adds a approver address. Approval happens with the token contract.
/// @param approver The approver address to add to the pool.
function addApprover(address approver) public onlyOwner {
approvers.push(approver);
}
/// @dev Removes an approver address.
/// @param approver The approver address to remove from the pool.
function removeApprover(address approver) public onlyOwner {
uint good = 0;
for (uint i = 0; i < approvers.length; i = i.add(1)) {
bool isValid = approvers[i] != approver;
if (isValid) {
if (good != i) {
approvers[good] = approvers[i];
}
good = good.add(1);
}
}
// TODO Delete the previous entries.
approvers.length = good;
}
/// @dev Updates the reward rate
function updateRewardRate(address tokenAddress, uint newRewardRate) public onlyOwner {
require(newRewardRate > 0);
require(tokenAddress != address(0));
for (uint i = 0; i < rewardSources.length; i++) {
if (rewardSources[i].rewardTokenAddress == tokenAddress) {
rewardSources[i].rewardRate = uint96(newRewardRate);
return;
}
}
}
/// @dev Adds the token address of the payment type.
function addRewardToken(address tokenAddress, uint newRewardRate) public onlyOwner {
require(tokenAddress != address(0));
require(!approvedRewardSources[tokenAddress]);
rewardSources.push(RewardSource(tokenAddress, uint96(newRewardRate)));
approvedRewardSources[tokenAddress] = true;
}
/// @dev Removes the given token address from the approved sources.
/// @param tokenAddress the address of the token
function removeRewardToken(address tokenAddress) public onlyOwner {
require(tokenAddress != address(0));
require(approvedRewardSources[tokenAddress]);
approvedRewardSources[tokenAddress] = false;
// Shifting costs significant gas with every write.
// UI should update the reward sources after this function call.
for (uint i = 0; i < rewardSources.length; i++) {
if (rewardSources[i].rewardTokenAddress == tokenAddress) {
rewardSources[i] = rewardSources[rewardSources.length - 1];
delete rewardSources[rewardSources.length - 1];
rewardSources.length--;
return;
}
}
}
/// @dev Transfers any tokens to the owner
function destroyRewards() public onlyOwner {
for (uint i = 0; i < rewardSources.length; i++) {
FullERC20 rewardToken = FullERC20(rewardSources[i].rewardTokenAddress);
uint tokenBalance = rewardToken.balanceOf(this);
assert(rewardToken.transfer(owner, tokenBalance));
approvedRewardSources[rewardSources[i].rewardTokenAddress] = false;
}
rewardSources.length = 0;
}
/// @dev Updates the referral bonus percentage
function updateReferralBonusRate(uint newReferralBonusRate) public onlyOwner {
require(newReferralBonusRate < 100);
referralBonusRate = newReferralBonusRate;
}
/// @dev Registers the player with the given referral code
/// @param player The address of the player
/// @param referrer The address of the referrer
function registerReferral(address player, address referrer) public onlyRequesters {
if (referrer != address(0) && player != referrer) {
referrers[player] = referrer;
ReferralRegistered(player, referrer);
}
}
/// @dev Transfers the rewards to the player for the provided reward source
function transferRewardsInternal(address player, uint entryAmount, uint gameId, RewardSource storage rewardSource) internal {
if (rewardSource.rewardTokenAddress == address(0)) {
return;
}
FullERC20 rewardToken = FullERC20(rewardSource.rewardTokenAddress);
uint rewards = entryAmount.div(rewardSource.rewardRate).mul(10**uint256(rewardToken.decimals()));
if (rewards == 0) {
return;
}
address referrer = referrers[player];
uint referralBonus = referrer == address(0) ? 0 : rewards.mul(referralBonusRate).div(100);
uint totalRewards = referralBonus.mul(2).add(rewards);
uint playerRewards = rewards.add(referralBonus);
// First check if the contract itself has enough tokens to reward.
if (rewardToken.balanceOf(this) >= totalRewards) {
assert(rewardToken.transfer(player, playerRewards));
TokensRewarded(player, rewardToken, playerRewards, msg.sender, gameId, block.number);
if (referralBonus > 0) {
assert(rewardToken.transfer(referrer, referralBonus));
ReferralRewarded(referrer, rewardToken, player, referralBonus, gameId, block.number);
}
return;
}
// Iterate through the approvers to find first with enough rewards and successful transfer
for (uint i = 0; i < approvers.length; i++) {
address approver = approvers[i];
uint allowance = rewardToken.allowance(approver, this);
if (allowance >= totalRewards) {
assert(rewardToken.transferFrom(approver, player, playerRewards));
TokensRewarded(player, rewardToken, playerRewards, msg.sender, gameId, block.number);
if (referralBonus > 0) {
assert(rewardToken.transfer(referrer, referralBonus));
ReferralRewarded(referrer, rewardToken, player, referralBonus, gameId, block.number);
}
return;
}
}
}
}
|
Removes the given token address from the approved sources. tokenAddress the address of the token Shifting costs significant gas with every write. UI should update the reward sources after this function call.
|
function removeRewardToken(address tokenAddress) public onlyOwner {
require(tokenAddress != address(0));
require(approvedRewardSources[tokenAddress]);
approvedRewardSources[tokenAddress] = false;
for (uint i = 0; i < rewardSources.length; i++) {
if (rewardSources[i].rewardTokenAddress == tokenAddress) {
rewardSources[i] = rewardSources[rewardSources.length - 1];
delete rewardSources[rewardSources.length - 1];
rewardSources.length--;
return;
}
}
}
| 971,676
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.3;
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
import "@openzeppelin/contracts/utils/Arrays.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
/**
* @title ProofOfHumanity Interface
* @dev See https://github.com/Proof-Of-Humanity/Proof-Of-Humanity.
*/
interface IProofOfHumanity {
function isRegistered(address _submissionID)
external
view
returns (
bool registered
);
function submissionCounter() external view returns (uint count);
}
/**
* @title Vote
* A proxy contract for ProofOfHumanity that implements a token interface to interact with other dapps.
*/
contract Vote is ERC20Snapshot {
/* Storage */
address public deployer = msg.sender;
uint256 private MAX_INT = 10 ** 18;
/// @dev The Proof Of Humanity registry to reference.
IProofOfHumanity public proofOfHumanity;
/* Modifiers */
/// @dev Verifies that the sender has ability to modify governed parameters.
modifier onlyDeployer() {
require(deployer == msg.sender, "The caller must be the deployer");
_;
}
/* Constructor */
/** @dev Constructor.
* @param _proofOfHumanity The address of the related ProofOfHumanity contract.
*/
constructor(string memory name_, string memory symbol_, IProofOfHumanity _proofOfHumanity) ERC20(name_, symbol_) {
proofOfHumanity = _proofOfHumanity;
}
/* External */
/** @dev Changes the address of the the related ProofOfHumanity contract.
* @param _proofOfHumanity The address of the new contract.
*/
function changeProofOfHumanity(IProofOfHumanity _proofOfHumanity) external onlyDeployer {
proofOfHumanity = _proofOfHumanity;
}
/** @dev Returns true if the submission is registered and not expired.
* @param _submission The address of the submission.
* @return Whether the submission is registered or not.
*/
function isHuman(address _submission) public view returns (bool) {
bool registered = proofOfHumanity.isRegistered(_submission);
return registered;
}
/* Snapshot */
/** @dev External function for Snapshot event emitter only accessible by deployer. */
function snapshot() external onlyDeployer returns (uint256) {
return _snapshot();
}
/** @dev Takes a Snapshot of the balance based on the ProofOfHumanity status. */
function register(address _submission) external {
_mint(_submission, balanceOf(_submission));
}
/* ERC20 */
/** @dev Returns the balance of a particular submission of the ProofOfHumanity contract.
* Note that this function takes the expiration date into account.
* @param _submission The address of the submission.
* @return The balance of the submission.
*/
function balanceOf(address _submission) public view override returns (uint256) {
return isHuman(_submission) ? MAX_INT : 0;
}
/** @dev Returns the count of all submissions that made a registration request at some point, including those that were added manually.
* Note that with the current implementation of ProofOfHumanity it'd be very costly to count only the submissions that are currently registered.
* @return The total count of submissions.
*/
function totalSupply() public view override returns (uint256) {
return proofOfHumanity.submissionCounter();
}
function transfer(address _recipient, uint256 _amount) public pure override returns (bool) { return false; }
function allowance(address _owner, address _spender) public override view returns (uint256) {}
function approve(address _spender, uint256 _amount) public pure override returns (bool) { return false; }
function transferFrom(address _sender, address _recipient, uint256 _amount) public pure override returns (bool) { return false; }
}
|
ProofOfHumanity Interface/
|
interface IProofOfHumanity {
function isRegistered(address _submissionID)
external
view
returns (
bool registered
);
function submissionCounter() external view returns (uint count);
pragma solidity 0.7.3;
}
| 12,670,152
|
pragma solidity ^0.5.3;
import "testeth/Log.sol";
import "testeth/Assert.sol";
import "testeth/Account.sol";
contract Factory {
event Deployed(address addr, uint256 salt);
function deploy1SignerWallet(uint256 threshold, address signatory) public returns (address payable addr) {
assembly {
// Multisig Wallet Code Below
mstore(1000, 0x38610137600039600051305560605b60405160200260600181101561002f5780)
mstore(1032, 0x518151555b60208101905061000e565b5060f780610040600039806000f350fe)
mstore(1064, 0x361560f65760003681610424376104a8516103e87f4a0a6d86122c7bd7083e83)
mstore(1096, 0x912c312adabf207e986f1ac10a35dfeb610d28d0b68152600180300180546104)
mstore(1128, 0x088181526104c8915085822061046852601987538384537fb0609d81c5f719d8)
mstore(1160, 0xa516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f260025260a0852060)
mstore(1192, 0x225260428720945086875b305481101560d05761042860608202610488510101)
mstore(1224, 0x87815261012c6020816080848e8c610bb8f1508381515411151560c0578a8bfd)
mstore(1256, 0x5b8051935050505b8581019050608a565b505080518401835550858686836104)
mstore(1288, 0x285161044851f4151560ef578586fd5b5050505050505b000000000000000000) // only 23 bytes -- 9 bytes shifted
mstore(1311, threshold) // start where code leaves off
mstore(1343, 0x0000000000000000000000000000000000000000000000000000000000000040)
mstore(1375, 0x0000000000000000000000000000000000000000000000000000000000000001) // 1 arr element
mstore(1407, signatory)
addr := create(0, 1000, 439)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return addr;
}
function deploy2SignerWallet(uint256 threshold, address signatory1, address signatory2) public returns (address payable addr) {
assembly {
// Multisig Wallet Code Below
mstore(1000, 0x38610137600039600051305560605b60405160200260600181101561002f5780)
mstore(1032, 0x518151555b60208101905061000e565b5060f780610040600039806000f350fe)
mstore(1064, 0x361560f65760003681610424376104a8516103e87f4a0a6d86122c7bd7083e83)
mstore(1096, 0x912c312adabf207e986f1ac10a35dfeb610d28d0b68152600180300180546104)
mstore(1128, 0x088181526104c8915085822061046852601987538384537fb0609d81c5f719d8)
mstore(1160, 0xa516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f260025260a0852060)
mstore(1192, 0x225260428720945086875b305481101560d05761042860608202610488510101)
mstore(1224, 0x87815261012c6020816080848e8c610bb8f1508381515411151560c0578a8bfd)
mstore(1256, 0x5b8051935050505b8581019050608a565b505080518401835550858686836104)
mstore(1288, 0x285161044851f4151560ef578586fd5b5050505050505b000000000000000000) // only 23 bytes -- 9 bytes shifted
mstore(1311, threshold) // start where code leaves off
mstore(1343, 0x0000000000000000000000000000000000000000000000000000000000000060) // 60 end pos
mstore(1375, 0x0000000000000000000000000000000000000000000000000000000000000002) // 2 arr element
mstore(1407, signatory1)
mstore(1439, signatory2)
addr := create(0, 1000, 471)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return addr;
}
}
contract MultisigWallet {
function execute(address destination, uint256 gasLimit, bytes calldata data, bytes32[] calldata signatures) external;
function () payable external;
function invalidMethod() external;
}
contract Recorder {
bytes data;
function () external {
data = msg.data;
}
function dataLen() external view returns (uint256) {
return data.length;
}
}
contract Teller {
function callit(address target, bytes calldata data) external {
target.call(data);
}
}
// test interest mechanism
contract test_Basics {
Factory factory = new Factory();
MultisigWallet wallet;
Recorder recorder = new Recorder();
Teller teller = new Teller();
function check_a1_construction_useAccount1() public {
wallet = MultisigWallet(factory.deploy1SignerWallet(1, msg.sender));
Log.data(address(wallet));
}
function check_a2_canAcceptEther_method_useValue4500() public payable {
address payable addr = address(wallet);
Assert.equal(addr.balance, 0);
addr.transfer(4500);
Assert.equal(addr.balance, 4500);
}
bytes recordData = "\x19\x01";
bytes data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
uint256 gasLimit = 600000;
uint256 nonce = 0;
address destination = address(teller);
bytes32 hash;
function check_a3_buildHash_useAccount1() public {
// EIP712 Transaction Hash
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
}
bytes32[] arr;
function check_a4_signature_useAccount1(uint8 v, bytes32 r, bytes32 s) public {
arr.push(bytes32(uint256(v)));
arr.push(r);
arr.push(s);
Assert.equal(recorder.dataLen(), 0);
wallet.execute(destination, gasLimit, data, arr);
Assert.equal(recorder.dataLen(), 2);
}
function check_a5_buildHash_inceaseNonce_useAccount1() public {
// EIP712 Transaction Hash
nonce += 1;
recordData = "\x19\x01\x01";
data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
}
bytes32[] arr2;
function check_a6_inceaseNonce_useAccount1(uint8 v, bytes32 r, bytes32 s) public {
arr2.push(bytes32(uint256(v)));
arr2.push(r);
arr2.push(s);
Assert.equal(recorder.dataLen(), 2);
wallet.execute(destination, gasLimit, data, arr2);
Assert.equal(recorder.dataLen(), 3);
}
function check_a7_buildHash_testInvalidNonce_useAccount1() public {
// EIP712 Transaction Hash
nonce = 1; // THIS IS AN INVALID NONCE
recordData = "\x19\x01\x01";
data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
}
bytes32[] sig3;
function check_a8_testInvalidNonce_useAccount1_shouldThrow(uint8 v, bytes32 r, bytes32 s) public {
sig3.push(bytes32(uint256(v)));
sig3.push(r);
sig3.push(s);
wallet.execute(destination, gasLimit, data, sig3);
}
function check_b1_buildHash_testSameWithValidNonce_useAccount1() public {
// EIP712 Transaction Hash
nonce = 2; // THIS IS AN INVALID NONCE
recordData = "\x19\x01\x01";
data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
}
bytes32[] sig4;
function check_b2_testSameWithValidNonce_useAccount1(uint8 v, bytes32 r, bytes32 s) public {
sig4.push(bytes32(uint256(v)));
sig4.push(r);
sig4.push(s);
wallet.execute(destination, gasLimit, data, sig4);
Assert.equal(recorder.dataLen(), 3);
}
function check_b3_buildHash_testInvalidSigningAccount_useAccount1() public {
// EIP712 Transaction Hash
nonce = 3; // THIS IS AN INVALID NONCE
recordData = "\x19\x01\x01";
data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(2, hash);
}
bytes32[] sig5;
function check_b4_testSameWithValidNonce_useAccount1_shouldThrow(uint8 v, bytes32 r, bytes32 s) public {
sig5.push(bytes32(uint256(v)));
sig5.push(r);
sig5.push(s);
wallet.execute(destination, gasLimit, data, sig5);
}
function check_b5_randomCall() public {
address(wallet).call("0x1234");
}
function check_b6_invalidMethod_shouldThrow() public {
wallet.invalidMethod();
}
}
// test interest mechanism
contract test_Basics_2Signatories {
Factory factory = new Factory();
MultisigWallet wallet;
Recorder recorder = new Recorder();
Teller teller = new Teller();
address signer1;
address signer2;
function check_a1_construction_useAccount2() public {
signer2 = msg.sender;
}
function check_a2_construction_useAccount1() public {
signer1 = msg.sender;
wallet = MultisigWallet(factory.deploy2SignerWallet(2, signer1, signer2));
Log.data(address(wallet));
}
function check_a3_canAcceptEther_method_useValue4500() public payable {
address payable addr = address(wallet);
Assert.equal(addr.balance, 0);
addr.transfer(4500);
Assert.equal(addr.balance, 4500);
}
bytes recordData = "\x19\x01";
bytes data = abi.encodeWithSelector(bytes4(0x7214ae99), address(recorder), recordData);
uint256 gasLimit = 600000;
uint256 nonce = 0;
address destination = address(teller);
bytes32 hash;
function check_a4_buildHash_useAccount1() public {
// EIP712 Transaction Hash
hash = keccak256(abi.encodePacked(
"\x19\x01",
bytes32(0xb0609d81c5f719d8a516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f2),
keccak256(abi.encode(
bytes32(0x4a0a6d86122c7bd7083e83912c312adabf207e986f1ac10a35dfeb610d28d0b6),
nonce,
destination,
gasLimit,
keccak256(data)
))
));
Account.sign(1, hash);
Account.sign(2, hash);
}
bytes32[] sig1;
function check_a5_signature_useAccount1(uint8 s1v, bytes32 s1r, bytes32 s1s, uint8 s2v, bytes32 s2r, bytes32 s2s) public {
if (signer1 > signer2) {
sig1.push(bytes32(uint256(s2v)));
sig1.push(s2r);
sig1.push(s2s);
sig1.push(bytes32(uint256(s1v)));
sig1.push(s1r);
sig1.push(s1s);
} else {
sig1.push(bytes32(uint256(s1v)));
sig1.push(s1r);
sig1.push(s1s);
sig1.push(bytes32(uint256(s2v)));
sig1.push(s2r);
sig1.push(s2s);
}
Assert.equal(recorder.dataLen(), 0);
wallet.execute(destination, gasLimit, data, sig1);
Assert.equal(recorder.dataLen(), 2);
}
}
|
Multisig Wallet Code Below
|
function deploy2SignerWallet(uint256 threshold, address signatory1, address signatory2) public returns (address payable addr) {
assembly {
mstore(1000, 0x38610137600039600051305560605b60405160200260600181101561002f5780)
mstore(1032, 0x518151555b60208101905061000e565b5060f780610040600039806000f350fe)
mstore(1064, 0x361560f65760003681610424376104a8516103e87f4a0a6d86122c7bd7083e83)
mstore(1096, 0x912c312adabf207e986f1ac10a35dfeb610d28d0b68152600180300180546104)
mstore(1128, 0x088181526104c8915085822061046852601987538384537fb0609d81c5f719d8)
mstore(1160, 0xa516ae2f25079b20fb63da3e07590e23fbf0028e6745e5f260025260a0852060)
mstore(1192, 0x225260428720945086875b305481101560d05761042860608202610488510101)
mstore(1224, 0x87815261012c6020816080848e8c610bb8f1508381515411151560c0578a8bfd)
mstore(1256, 0x5b8051935050505b8581019050608a565b505080518401835550858686836104)
mstore(1407, signatory1)
mstore(1439, signatory2)
addr := create(0, 1000, 471)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return addr;
}
| 6,460,288
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
pragma experimental ABIEncoderV2;
// Interfaces.
import '../interfaces/IERC20.sol';
import '../interfaces/IAssetHandler.sol';
import '../interfaces/IAddressResolver.sol';
import '../interfaces/Mobius/ISwap.sol';
import '../interfaces/Mobius/IMasterMind.sol';
import '../interfaces/IUbeswapAdapter.sol';
// Inheritance.
import '../interfaces/IMobiusAdapter.sol';
// OpenZeppelin.
import '../openzeppelin-solidity/contracts/SafeMath.sol';
import '../openzeppelin-solidity/contracts/Ownable.sol';
contract MobiusAdapter is IMobiusAdapter, Ownable {
using SafeMath for uint;
struct MobiusAsset {
address stakingToken;
address denominationAsset;
address swapAddress;
uint pid;
}
IAddressResolver public immutable ADDRESS_RESOLVER;
// (address of Mobius asset => Mobius asset info).
mapping (address => MobiusAsset) public mobiusAssets;
// Denomination asset => similar asset on Ubeswap.
// Ex) USDC => cUSD.
// This mapping is used for calculating the price of an asset on Mobius.
mapping (address => address) public equivalentUbeswapAsset;
// (asset, asset) LP pair => address of Swap contract.
mapping (address => mapping(address => address)) public swapAddresses;
constructor(address _addressResolver) Ownable() {
ADDRESS_RESOLVER = IAddressResolver(_addressResolver);
}
/* ========== VIEWS ========== */
/**
* @notice Returns the address of the LP token's Swap contract.
* @param _pair Address of the liquidity pair.
* @return address Address of the LP token's Swap contract.
*/
function getSwapAddress(address _pair) external view override returns (address) {
require(_pair != address(0), "MobiusAdapter: invalid pair address.");
return mobiusAssets[_pair].swapAddress;
}
/**
* @notice Given an input asset address, returns the price of the asset in USD.
* @param _currencyKey Address of the asset.
* @return price Price of the asset.
*/
function getPrice(address _currencyKey) external view override returns(uint price) {
require(_currencyKey != address(0), "MobiusAdapter: Invalid currency key.");
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address ubeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("UbeswapAdapter");
require(IAssetHandler(assetHandlerAddress).isValidAsset(_currencyKey), "MobiusAdapter: Currency is not available.");
// Get the price of the denomination asset on Ubeswap.
// This assumes that the denomination asset is pegged to the equivalent Ubeswap asset.
price = IUbeswapAdapter(ubeswapAdapterAddress).getPrice(equivalentUbeswapAsset[mobiusAssets[_currencyKey].denominationAsset]);
// Get the (asset/denomination) price on Mobius and divide by
// the price of the denomination asset.
if (mobiusAssets[_currencyKey].denominationAsset != _currencyKey) {
uint mobiusPrice = ISwap(mobiusAssets[_currencyKey].swapAddress).getVirtualPrice();
price = price.mul(mobiusPrice).div(10 ** 18);
}
}
/**
* @notice Returns the staking token address for each available farm on Mobius.
* @return (address[], uint[]) The staking token address and farm ID for each available farm.
*/
function getAvailableMobiusFarms() external view override returns (address[] memory, uint[] memory) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address[] memory assetAddresses = IAssetHandler(assetHandlerAddress).getAvailableAssetsForType(3);
address[] memory stakingTokenAddresses = new address[](assetAddresses.length);
uint[] memory farmIDs = new uint[](assetAddresses.length);
//Get farm IDs.
for (uint i = 0; i < assetAddresses.length; i++)
{
stakingTokenAddresses[i] = mobiusAssets[assetAddresses[i]].stakingToken;
farmIDs[i] = mobiusAssets[assetAddresses[i]].pid;
}
return (stakingTokenAddresses, farmIDs);
}
/**
* @notice Checks whether the given liquidity pair has a farm on Mobius.
* @param _pair Address of the liquidity pair.
* @return bool Whether the pair has a farm.
*/
function checkIfLPTokenHasFarm(address _pair) external view override returns (bool) {
require(_pair != address(0), "MobiusAdapter: invalid pair address.");
return (mobiusAssets[_pair].stakingToken != address(0));
}
/**
* @notice Returns the address of a token pair.
* @param _tokenA First token in pair.
* @param _tokenB Second token in pair.
* @return address The pair's address.
*/
function getPair(address _tokenA, address _tokenB) public view override returns (address) {
require(_tokenA != address(0), "MobiusAdapter: invalid address for tokenA.");
require(_tokenB != address(0), "MobiusAdapter: invalid address for tokenB.");
address swapAddress = swapAddresses[_tokenA][_tokenB];
require(swapAddress != address(0), "MobiusAdapter: Swap address for token pair not found.");
return ISwap(swapAddress).getLpToken();
}
/**
* @notice Returns the amount of MOBI rewards available for the pool in the given farm.
* @param _poolAddress Address of the pool.
* @param _pid ID of the farm on Mobius.
* @return uint Amount of MOBI available.
*/
function getAvailableRewards(address _poolAddress, uint _pid) external view override returns (uint) {
require(_poolAddress != address(0), "MobiusAdapter: invalid pool address.");
require(_pid >= 0, "MobiusAdapter: pid must be positive.");
address masterMindAddress = ADDRESS_RESOLVER.getContractAddress("MobiusMasterMind");
return IMasterMind(masterMindAddress).pendingNerve(_pid, _poolAddress);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice Adds support for a new Mobius asset to the platform.
* @dev Only the contract owner can call this function.
* @param _asset Address of the asset.
* @param _stakingToken Address of the asset's LP token.
* @param _denominationAsset Address of the asset the Mobius asset is priced in.
* @param _swapAddress Address of the Mobius Swap contract for the given asset.
* @param _pid The pool ID assigned to the given asset.
*/
function addMobiusAsset(address _asset, address _stakingToken, address _denominationAsset, address _swapAddress, uint _pid) external onlyOwner {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
require(_asset != address(0), "MobiusAdapter: invalid asset address.");
require(_stakingToken != address(0), "MobiusAdapter: invalid staking token address.");
require(_denominationAsset != address(0), "MobiusAdapter: invalid denomination asset address.");
require(_swapAddress != address(0), "MobiusAdapter: invalid swap address.");
require(_pid >= 0, "MobiusAdapter: pid must be positive.");
require(mobiusAssets[_asset].stakingToken == address(0), "MobiusAdapter: asset already exists.");
require(IAssetHandler(assetHandlerAddress).isValidAsset(_denominationAsset), "MobiusAdapter: denomination asset is not available.");
require(IAssetHandler(assetHandlerAddress).isValidAsset(_asset), "MobiusAdapter: asset is not available.");
mobiusAssets[_asset] = MobiusAsset(_stakingToken, _denominationAsset, _swapAddress, _pid);
swapAddresses[_denominationAsset][_asset] = _swapAddress;
swapAddresses[_asset][_denominationAsset] = _swapAddress;
emit AddedMobiusAsset(_asset, _stakingToken, _denominationAsset, _swapAddress, _pid);
}
/**
* @notice Sets the equivalent Ubeswap asset for the given asset.
* @dev Using an equivalent asset helps to calculate the price of the Mobius asset
* by assuming the denomination asset is pegged to the Ubeswap asset.
* @dev Only the contract owner can call this function.
* @param _denominationAsset Address of the asset the Mobius asset is priced in.
* @param _ubeswapAsset Address of a similar asset on Ubeswap.
* Ex) Ubeswap asset for USDC would be cUSD.
*/
function setEquivalentUbeswapAsset(address _denominationAsset, address _ubeswapAsset) external onlyOwner {
require(_denominationAsset != address(0), "MobiusAdapter: invalid denomination asset address.");
require(_ubeswapAsset != address(0), "MobiusAdapter: invalid Ubeswap asset address.");
equivalentUbeswapAsset[_denominationAsset] = _ubeswapAsset;
emit SetEquivalentUbeswapAsset(_denominationAsset, _ubeswapAsset);
}
/* ========== EVENTS ========== */
event AddedMobiusAsset(address asset, address stakingToken, address denominationAsset, address swapAddress, uint pid);
event SetEquivalentUbeswapAsset(address denominationAsset, address ubeswapAsset);
}
|
Returns the address of a token pair. _tokenA First token in pair. _tokenB Second token in pair. return address The pair's address./
|
function getPair(address _tokenA, address _tokenB) public view override returns (address) {
require(_tokenA != address(0), "MobiusAdapter: invalid address for tokenA.");
require(_tokenB != address(0), "MobiusAdapter: invalid address for tokenB.");
address swapAddress = swapAddresses[_tokenA][_tokenB];
require(swapAddress != address(0), "MobiusAdapter: Swap address for token pair not found.");
return ISwap(swapAddress).getLpToken();
}
| 12,726,998
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
import "./LionShare.sol";
contract LionShareSale {
address payable admin;
LionShare public tokenContract;
uint256 public tokenPrice;
uint256 public tokensSold;
event Sell(address _buyer, uint256 _amount);
constructor(LionShare _tokenContract, uint256 _tokenPrice) {
admin = payable(msg.sender);
tokenContract = _tokenContract;
tokenPrice = _tokenPrice;
}
function multiply(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function buyTokens(uint256 _numberOfTokens) public payable {
require(msg.value == multiply(_numberOfTokens, tokenPrice),"value of tokens not exact");
require(tokenContract.balanceOf(address(this)) >= _numberOfTokens,"balanceOf less than tokens");
require(tokenContract.transfer(msg.sender, _numberOfTokens),"transfer faild");
tokensSold += _numberOfTokens;
emit Sell(msg.sender, _numberOfTokens);
}
function endSale() public {
require(msg.sender == admin);
require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));
//uint all_funds = address(this).balance;
//admin.transfer(all_funds);
//require(address(this).balance == 0);
//Contracts can be deleted from the blockchain by calling selfdestruct.
//selfdestruct sends all remaining Ether stored in the contract to an designated address.
selfdestruct(admin);
}
}
|
uint all_funds = address(this).balance;admin.transfer(all_funds);require(address(this).balance == 0);Contracts can be deleted from the blockchain by calling selfdestruct.selfdestruct sends all remaining Ether stored in the contract to an designated address.
|
function endSale() public {
require(msg.sender == admin);
require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));
selfdestruct(admin);
}
| 2,531,473
|
./partial_match/1/0xFbC3661021539b2a2102Bd2476E7F2371Cb8d763/sources/AlphaMutants.sol
|
Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
|
function tokenOfOwnerByIndex(address owner, uint256 index) internal view returns (uint256) {
uint256 numMintedSoFar = _currentIndex;
uint256 tokenIdsIdx;
address currOwnershipAddr;
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
}
| 4,180,735
|
./full_match/4/0x011F0DA68ce3F80b2C8DCd6D94B2f36280ff3b6f/sources/contracts/ico.sol
|
returning the balance of treasury
|
function getTreasury() public view returns(uint){
return address(treasuryAddress).balance;
}
| 740,471
|
pragma solidity 0.8.6;
//SPDX-License-Identifier: MIT
import "./IERC20.sol";
import "./IERC20Metadata.sol";
import "./Ownable.sol";
import "./Pausable.sol";
/**
* @dev {CitizenChatToken} token, including:
*
* - Preminted initial supply
* - Pausable
* - VestedTokens
*
*/
contract CitizenChatToken is Pausable, Ownable, IERC20, IERC20Metadata {
struct VestedRecord {
bool isVested;
uint256 lockedUpto;
uint256 amount;
}
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => VestedRecord) private vestedRecords;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Emitted when `value` tokens are vested from owner (`from`) to
* another (`to`).
*
*/
event VestedTransfer(
address indexed from,
address indexed to,
uint256 value
);
/**
* @dev Emitted when `value` tokens are Withdrawn from vested record to
* another (`beneficiary`).
*
*/
event VestedWithdraw(address beneficiary, uint256 value);
/**
*
* @dev Sets the values for {name} and {symbol}. Mints `initialSupply` amount of token and transfers them to `owner`
*
* 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_,
uint256 initialSupply,
address ownerAddress
) {
_name = name_;
_symbol = symbol_;
_mint(ownerAddress, initialSupply * 10**18);
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account] + vestedBalanceOf(account);
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer();
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);
}
/** @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();
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer();
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);
}
/**
* @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 onlyOwner can pause the token transfer
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev onlyOwner can unpause the token transfer
*/
function unpause() public onlyOwner {
_unpause();
}
/**
* @dev hook function for before any token transfer.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer() internal view {
require(!paused(), "ERC20Pausable: token transfer while paused");
}
/**
* @dev Send tokens to bulk address
*
* Requirements:
*
* - onlyOwner can do bulk transfer
* - `recipients` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function bulkTransfer(
address[] calldata recipients,
uint256[] calldata amounts
) external onlyOwner returns (bool) {
require(
recipients.length == amounts.length,
"CCT: Equal length arrays must"
);
for (uint8 i = 0; i < recipients.length; i++) {
_transfer(_msgSender(), recipients[i], amounts[i]);
}
return true;
}
/**
* @dev Vesting Transfer
*
* Requirements:
*
* - onlyOwner can do Vesting transfer
* - `beneficiary` cannot be the zero address.
* - `lockedUpto` a certain period
* - the caller must have a balance of at least `amount`.
*/
function vestingTransfer(
address beneficiary,
uint256 lockedUpto,
uint256 amount
) public onlyOwner returns (bool) {
require(
beneficiary != address(0),
"ERC20: transfer to the zero address"
);
VestedRecord memory vestRecord = vestedRecords[beneficiary];
require(vestRecord.isVested == false, "CCT: Tokens already vested");
uint256 senderBalance = _balances[_msgSender()];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[_msgSender()] = senderBalance - amount;
}
vestedRecords[beneficiary] = VestedRecord(true, lockedUpto, amount);
emit VestedTransfer(_msgSender(), beneficiary, amount);
return true;
}
/**
* @dev Withdraw Vesting Tokens
*
* Requirements:
*
* - `beneficiary` cannot be the zero address.
*/
function WithdrawVestedTokens(address beneficiary) public returns (bool) {
VestedRecord memory vestRecord = vestedRecords[beneficiary];
require(vestRecord.isVested == true, "CCT: No Vested tokens");
require(block.timestamp > vestRecord.lockedUpto, "CCT: Locked Tokens");
_balances[beneficiary] = _balances[beneficiary] + vestRecord.amount;
emit VestedWithdraw(beneficiary, vestRecord.amount);
delete vestedRecords[beneficiary];
return true;
}
/**
* @dev Vested Balance
*
* Requirements:
* - `beneficiary` cannot be the zero address.
*/
function vestedBalanceOf(address beneficiary)
public
view
returns (uint256)
{
VestedRecord memory vestRecord = vestedRecords[beneficiary];
return vestRecord.amount;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual onlyOwner {
_burn(_msgSender(), amount);
}
}
|
hook function for before any token transfer. Requirements: - the contract must not be paused./
|
function _beforeTokenTransfer() internal view {
require(!paused(), "ERC20Pausable: token transfer while paused");
}
| 12,201,837
|
./partial_match/3/0xD12d4bFa2f7cd3b427cAc417680950A33b2A356A/sources/OnePoolRewardPool.sol
|
If it is a normal user and not smart contract, then the requirement will pass If it is a smart contract, then make sure that it is not on our greyList.
|
function getReward() public updateReward(msg.sender) {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
if (tx.origin == msg.sender || !IController(controller()).greyList(msg.sender)) {
rewardToken.safeTransfer(msg.sender, reward, "get reward");
emit RewardPaid(msg.sender, reward);
emit RewardDenied(msg.sender, reward);
}
}
}
| 5,053,978
|
pragma solidity ^0.4.21;
import "openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol";
import "openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol";
import "openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol";
import "openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol";
import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "./Vault.sol";
contract QiibeeToken {
function mintVestedTokens(address _to,
uint256 _value,
uint64 _start,
uint64 _cliff,
uint64 _vesting,
bool _revokable,
bool _burnsOnRevoke,
address _wallet
) returns (bool);
function mint(address _to, uint256 _amount) returns (bool);
function transferOwnership(address _wallet);
function pause();
function unpause();
function finishMinting() returns (bool);
function totalSupply() returns (uint256);
}
/**
@title Crowdsale for the QBX Token Generation Event
*/
contract QiibeeCrowdsale is TimedCrowdsale, CappedCrowdsale, FinalizableCrowdsale, Pausable {
using SafeMath for uint256;
QiibeeToken public token; // token being sold
uint256 public tokensSold; // qbx minted (and sold)
mapping (address => uint256) public balances; // balance of wei invested per contributor
// spam prevention
uint256 public maxGasPrice; // max gas price per transaction
// bonus
uint256 public bonusEndtime; // date where bonus is over
mapping (address => bool) public bonus; // contributors who are entitled to the bonus
mapping (address => bool) public existsBonus;
// limits
uint256 public minContrib; // minimum invest in wei an address can do
uint256 public maxCumulativeContrib; // maximum cumulative invest an address can do
Vault public vault; // vault used to hold funds while crowdsale is running
// mapping (address => uint256) public deposited; //Money deposited per contributor
mapping (address => bool) public rejected; // contributors that have been reject KYC
mapping (address => bool) public accepted; // contributors that have been accepted KYC
/*
* @dev event for change wallet logging
* @param wallet new wallet address
*/
event WalletChange(address wallet);
/* TODO: modify text
* @dev event for contribution received
* @param beneficiary contributor address
* @param beneficiary amoount invested
*/
event Released(address beneficiary, uint256 weiAmount);
/*
* @dev event for contribution refunded
* @param beneficiary contributor address
* @param beneficiary amoount invested
*/
event PartialRefund(address beneficiary, uint256 amount);
/*
* @dev event for contribution whitelist
* @param beneficiary contributor address
*/
event Whitelisted(address beneficiary);
/*
* @dev event for contribution blacklist
* @param beneficiary contributor address
*/
event Blacklisted(address beneficiary);
/*
* @dev Constructor. Creates the token in a paused state
* @param _openingTime see `openingTime`
* @param _closingTime see `closingTime`
* @param _rate see `rate` on Crowdsale.sol
* @param _cap see `see cap`
* @param _minContrib see `see minContrib`
* @param _maxCumulativeContrib see `see maxCumulativeContrib`
* @param _maxGasPrice see `see maxGasPrice`
* @param _token see `token`
* @param _wallet see `wallet`
*/
function QiibeeCrowdsale (
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _cap,
uint256 _minContrib,
uint256 _maxCumulativeContrib,
uint256 _maxGasPrice,
address _token,
address _wallet
) public
Crowdsale(_rate, _wallet, ERC20(_token))
TimedCrowdsale(_openingTime, _closingTime)
CappedCrowdsale(_cap)
{
require(_minContrib > 0);
require(_minContrib < cap);
require(_minContrib <= _maxCumulativeContrib);
require(_maxGasPrice > 0);
bonusEndtime = _openingTime.add(7 days);
minContrib = _minContrib;
maxCumulativeContrib = _maxCumulativeContrib;
maxGasPrice = _maxGasPrice;
token = QiibeeToken(_token);
vault = new Vault(wallet);
}
/**
* @dev Throws if cap has been reached.
*/
modifier capNotReached() {
require(weiRaised < cap);
_;
}
/**
* @dev Throws if crowdsale has started.
*/
modifier beforeOpen() {
require(block.timestamp < openingTime);
_;
}
/**
* @dev need to have this despite inheritance because `buyTokens` in `Crowdsale.sol`
* takes an argument. So the (inherited) fallback function in `Crowdsale.sol` calls it with the argument.
*/
function () external payable {
buyTokens();
}
/*
* @dev Whenever buyTokens function is called there are 3 use cases that can take place:
* 1). if contributor has already passed KYC (this means that accepted[msg.sender] is true),
* a normal purchase is done (funds go to qiibee wallet and tokens are minted (see _mintTokens
* function)
* 2). if contributor has been REJECTED from KYC (this means that rejected[msg.sender] is true),
* funds are immediately refunded to the user and NO minting is performed.
* 3). if contributor has never gone through the KYC process (this means that both
* accepted[msg.sender] and rejected[msg.sender] are false) the funds are deposited in a vault
* until the contract knows whether the contributor has passed the KYC or not.
*/
function buyTokens() public payable whenNotPaused capNotReached onlyWhileOpen {
_preValidatePurchase(msg.sender, msg.value);
if (accepted[msg.sender]) { // contributor has been accepted in the KYC process
_mintTokens(msg.sender, msg.value);
} else {
if (rejected[msg.sender]) { // contributor has been rejected in the KYC process
revert();
// beneficiary.transfer(msg.value); // refund money to contributor
// Refunded(beneficiary, msg.value);
} else { // contributor has not gone through the KYC process yet
bonus[msg.sender] = _checkBonus();
vault.deposit.value(msg.value)(msg.sender);
}
}
}
/*
* @dev this function is triggered by the owner to validate a contributor's purchase. There are 2 use cases
* that can take place:
* 1). if contributor has previously tried contributing (so he has his funds in the vault), we add
* him/her to the accepted array and call _mintTokens() function.
* 2). if contributor has never tried contributing yet (so he has no funds in the vault), we just add
* him/her to the accepted array.
* @param beneficiary address where tokens are sent to
*/
function validatePurchase(address beneficiary) onlyOwner external whenNotPaused {
require(beneficiary != address(0));
uint256 deposited = vault.deposited(beneficiary); // wei deposited by contributor
accepted[beneficiary] = true; // Add contributor to KYC array so if he reinvests he automatically gets the tokens. //TODO: beneficiary or sender?
rejected[beneficiary] = false; // Add contributor to KYC array so if he reinvests he automatically gets the tokens. //TODO: beneficiary or sender?
if (deposited > 0) {
_mintTokens(beneficiary, deposited);
}
Whitelisted(beneficiary);
}
/*
* @dev this function is triggered by the owner to reject a contributor's purchase. There are 2 use cases
* that can take place:
* 1). if contributor has previously tried contributing (so he has his funds in the vault), we add
* him/her to the rejected array and refund him/her.
* 2). if contributor has never tried contributing yet (so he has no funds in the vault), we just add
* him/her to the rejected array.
* @param beneficiary address where tokens are sent to
*/
function rejectPurchase(address beneficiary) onlyOwner external whenNotPaused {
require(beneficiary != address(0));
uint256 deposited = vault.deposited(beneficiary); // wei deposited by contributor
rejected[beneficiary] = true; // Add contributor to KYC array so if he reinvests he automatically gets the tokens. //TODO: beneficiary or sender?
accepted[beneficiary] = false;
if (deposited > 0) {
vault.refund(beneficiary);
}
Blacklisted(beneficiary);
}
/**
@dev Finalizes the crowdsale, calls finalization method (see `finalization()`),
unpauses the token and transfers the token ownership to the foundation.
This function can only be called once the crowdsale has ended.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
Finalized();
isFinalized = true;
QiibeeToken(token).unpause();
QiibeeToken(token).transferOwnership(wallet);
}
/**
@dev changes the token owner
@param tokenAddress address address of the token contract
*/
function setToken(address tokenAddress) onlyOwner beforeOpen external {
require(tokenAddress != address(0));
token = QiibeeToken(tokenAddress);
}
/*
* @dev Changes the current wallet for a new one. Only the owner can call this function.
* @param _wallet new wallet
*/
function setWallet(address _wallet) onlyOwner external {
require(_wallet != address(0));
wallet = _wallet;
WalletChange(_wallet);
}
/*
* @dev Contributors can claim their contribution after crowdsale has been finalized.
* This is a safe method in case refundAll() didn't work so each contributor can
* still claim their funds stored in the vault.
*/
function claimVaultFunds() whenNotPaused external {
require(isFinalized);
vault.refund(msg.sender);
}
/*
* @dev Allows owner to refund all the contributors that have a reamining balance
* on the vault. This call is only allowed after crowdsale is finished
*/
function refundAll(uint[] indexes) whenNotPaused onlyOwner external {
require(isFinalized);
vault.refundAll(indexes);
}
/*
* @dev Pre validates a purchase. Note that the sender must be the beneficiary,
* this means that nobody can purchase on behalf of another one.
* @param _beneficiary beneficiary
* @param _weiAmount amount in wei
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_weiAmount != 0);
uint256 deposited = vault.deposited(_beneficiary); // wei deposited by contributor
uint256 newBalance = msg.value.add(deposited);
_checkLimits(_beneficiary, newBalance);
}
/*
* @dev checks whether corresponds to receive a bonus or not.
*/
function _checkBonus() internal returns (bool) {
return now <= bonusEndtime;
}
/*
* @dev If user has passed KYC, release funds and mint QBX. Otherwise, send back money.
* @param beneficiary address where tokens are sent to
* @param acceptance whether the user has passed KYC or not
*/
function _mintTokens(address beneficiary, uint256 weiAmount) internal {
_checkLimits(beneficiary, weiAmount);
uint256 overflow = _computeOverflow(weiAmount);
weiAmount = weiAmount.sub(overflow);
assert(weiAmount > 0);
uint256 tokens = _computeTokens(beneficiary, weiAmount);
assert(QiibeeToken(token).mint(beneficiary, tokens));
balances[beneficiary] = balances[beneficiary].add(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
_processDeposit(beneficiary, weiAmount, overflow);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
}
function _computeOverflow(uint256 weiAmount) internal returns (uint256) {
uint256 newBalance = weiRaised.add(weiAmount);
uint256 overflow;
if (newBalance > cap) {
overflow = newBalance.sub(cap);
}
return overflow;
}
function _computeTokens(address beneficiary, uint256 weiAmount) internal returns (uint256) {
uint256 tokens = weiAmount.mul(rate);
if (_checkBonus() || bonus[beneficiary]) {
tokens = tokens.mul(105).div(100); // adds 5% on top
bonus[beneficiary] = false; // reset bonus
}
return tokens;
}
function _processDeposit(address beneficiary, uint256 weiAmount, uint256 overflow) internal returns (uint256) {
uint256 deposited = vault.deposited(beneficiary); // wei deposited by contributor
if (deposited > 0) { // if contributor has his funds in the vault, release them to qiibee
vault.release(beneficiary, overflow);
} else {
wallet.transfer(weiAmount); // forward funds to qiibee wallet
Released(beneficiary, weiAmount);
}
}
/*
* Checks if the contribution made is within the allowed limits
*/
function _checkLimits(address beneficiary, uint256 weiAmount) internal {
uint256 newBalance = balances[beneficiary].add(weiAmount);
require(newBalance <= maxCumulativeContrib && weiAmount >= minContrib);
require(tx.gasprice <= maxGasPrice);
}
/*
* @dev Overrides Crowdsale#finalization() and is in charge of minting 49% percent of
* the tokens to the qiibee foundation wallet
*/
function finalization() internal {
uint256 totalSupply = QiibeeToken(token).totalSupply(); // 51%
uint256 foundationSupply = totalSupply.mul(49).div(51); // 49%
QiibeeToken(token).mint(wallet, foundationSupply);
assert(QiibeeToken(token).totalSupply() == totalSupply.add(foundationSupply));
super.finalization();
}
}
|
If user has passed KYC, release funds and mint QBX. Otherwise, send back money. beneficiary address where tokens are sent to acceptance whether the user has passed KYC or not/
|
function _mintTokens(address beneficiary, uint256 weiAmount) internal {
_checkLimits(beneficiary, weiAmount);
uint256 overflow = _computeOverflow(weiAmount);
weiAmount = weiAmount.sub(overflow);
assert(weiAmount > 0);
uint256 tokens = _computeTokens(beneficiary, weiAmount);
assert(QiibeeToken(token).mint(beneficiary, tokens));
balances[beneficiary] = balances[beneficiary].add(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
_processDeposit(beneficiary, weiAmount, overflow);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
}
| 12,957,598
|
./partial_match/1/0xf2b56659D3c89710ECE21463A914DD834bD6e6F8/sources/YNGBT.sol
|
YOU CAN SET HERE THE BUY FEES YOU CAN SET HERE THE SELL FEES
|
constructor(uint256 _startMFee, uint256 _startLFee) ERC20("Yangbot", "YANGBOT") {
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 = _startMFee;
uint256 _buyLiquidityFee = _startLFee;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = _startMFee;
uint256 _sellLiquidityFee = _startLFee;
uint256 _sellDevFee = 0;
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);
| 16,130,721
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.6;
import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol";
import "@yield-protocol/utils-v2/contracts/token/SafeERC20Namer.sol";
import "@yield-protocol/utils-v2/contracts/token/MinimalTransferHelper.sol";
import "@yield-protocol/utils-v2/contracts/token/IERC20.sol";
import "@yield-protocol/utils-v2/contracts/token/ERC20Rewards.sol";
import "@yield-protocol/utils-v2/contracts/cast/CastU256I128.sol";
import "@yield-protocol/utils-v2/contracts/cast/CastU128I128.sol";
import "@yield-protocol/vault-interfaces/DataTypes.sol";
import "@yield-protocol/vault-interfaces/ICauldron.sol";
import "@yield-protocol/vault-interfaces/ILadle.sol";
import "@yield-protocol/yieldspace-interfaces/IPool.sol";
import "@yield-protocol/yieldspace-v2/contracts/extensions/YieldMathExtensions.sol";
library DivUp {
function divUp(uint256 a, uint256 b) internal pure returns(uint256 c) {
a % b == 0 ? c = a / b : c = a / b + 1;
}
}
/// @dev The Pool contract exchanges base for fyToken at a price defined by a specific formula.
contract Strategy is AccessControl, ERC20Rewards {
using DivUp for uint256;
using MinimalTransferHelper for IERC20;
using YieldMathExtensions for IPool;
using CastU256U128 for uint256; // Inherited from ERC20Rewards
using CastU256I128 for uint256;
using CastU128I128 for uint128;
event YieldSet(ILadle ladle, ICauldron cauldron);
event TokenJoinReset(address join);
event TokenIdSet(bytes6 id);
event NextPoolSet(IPool indexed pool, bytes6 indexed seriesId);
event PoolEnded(address pool);
event PoolStarted(address pool);
IERC20 public immutable base; // Base token for this strategy
bytes6 public baseId; // Identifier for the base token in Yieldv2
address public baseJoin; // Yield v2 Join to deposit token when borrowing
ILadle public ladle; // Gateway to the Yield v2 Collateralized Debt Engine
ICauldron public cauldron; // Accounts in the Yield v2 Collateralized Debt Engine
IPool public pool; // Current pool that this strategy invests in
bytes6 public seriesId; // SeriesId for the current pool in Yield v2
IFYToken public fyToken; // Current fyToken for this strategy
IPool public nextPool; // Next pool that this strategy will invest in
bytes6 public nextSeriesId; // SeriesId for the next pool in Yield v2
uint256 public cached; // LP tokens owned by the strategy after the last operation
mapping (address => uint128) public invariants; // Value of pool invariant at start time
constructor(string memory name, string memory symbol, ILadle ladle_, IERC20 base_, bytes6 baseId_)
ERC20Rewards(name, symbol, SafeERC20Namer.tokenDecimals(address(base_)))
{ // The strategy asset inherits the decimals of its base, that matches the decimals of the fyToken and pool
require(
ladle_.cauldron().assets(baseId_) == address(base_),
"Mismatched baseId"
);
base = base_;
baseId = baseId_;
baseJoin = address(ladle_.joins(baseId_));
ladle = ladle_;
cauldron = ladle_.cauldron();
}
modifier poolSelected() {
require (
pool != IPool(address(0)),
"Pool not selected"
);
_;
}
modifier poolNotSelected() {
require (
pool == IPool(address(0)),
"Pool selected"
);
_;
}
modifier afterMaturity() {
require (
uint32(block.timestamp) >= fyToken.maturity(),
"Only after maturity"
);
_;
}
/// @dev Set a new Ladle and Cauldron
/// @notice Use with extreme caution, only for Ladle replacements
function setYield(ILadle ladle_)
external
poolNotSelected
auth
{
ladle = ladle_;
ICauldron cauldron_ = ladle_.cauldron();
cauldron = cauldron_;
emit YieldSet(ladle_, cauldron_);
}
/// @dev Set a new base token id
/// @notice Use with extreme caution, only for token reconfigurations in Cauldron
function setTokenId(bytes6 baseId_)
external
poolNotSelected
auth
{
require(
ladle.cauldron().assets(baseId_) == address(base),
"Mismatched baseId"
);
baseId = baseId_;
emit TokenIdSet(baseId_);
}
/// @dev Reset the base token join
/// @notice Use with extreme caution, only for Join replacements
function resetTokenJoin()
external
poolNotSelected
auth
{
baseJoin = address(ladle.joins(baseId));
emit TokenJoinReset(baseJoin);
}
/// @dev Set the next pool to invest in
function setNextPool(IPool pool_, bytes6 seriesId_)
external
auth
{
require(
base == pool_.base(),
"Mismatched base"
);
DataTypes.Series memory series = cauldron.series(seriesId_);
require(
series.fyToken == pool_.fyToken(),
"Mismatched seriesId"
);
nextPool = pool_;
nextSeriesId = seriesId_;
emit NextPoolSet(pool_, seriesId_);
}
/// @dev Start the strategy investments in the next pool
/// @param minRatio Minimum allowed ratio between the reserves of the next pool, as a fixed point number with 18 decimals (base/fyToken)
/// @param maxRatio Maximum allowed ratio between the reserves of the next pool, as a fixed point number with 18 decimals (base/fyToken)
/// @notice When calling this function for the first pool, some underlying needs to be transferred to the strategy first, using a batchable router.
function startPool(uint256 minRatio, uint256 maxRatio)
external
auth
poolNotSelected
{
IPool nextPool_ = nextPool;
require(nextPool_ != IPool(address(0)), "Next pool not set");
// Caching
IPool pool_ = nextPool_;
IFYToken fyToken_ = pool_.fyToken();
bytes6 seriesId_ = nextSeriesId;
pool = pool_;
fyToken = fyToken_;
seriesId = seriesId_;
delete nextPool;
delete nextSeriesId;
// Find pool proportion p = tokenReserves/(tokenReserves + fyTokenReserves)
// Deposit (investment * p) base to borrow (investment * p) fyToken
// (investment * p) fyToken + (investment * (1 - p)) base = investment
// (investment * p) / ((investment * p) + (investment * (1 - p))) = p
// (investment * (1 - p)) / ((investment * p) + (investment * (1 - p))) = 1 - p
uint256 baseBalance = base.balanceOf(address(this));
require(baseBalance > 0, "No funds to start with");
// The Pool mints based on cached values, not actual ones. Consider bundling a `pool.sync`
// call if they differ. A griefing attack exists by donating one fyToken wei to the pool
// before `startPool`, solved the same way.
uint256 baseInPool = base.balanceOf(address(pool_));
uint256 fyTokenInPool = fyToken_.balanceOf(address(pool_));
uint256 baseToPool = (baseBalance * baseInPool).divUp(baseInPool + fyTokenInPool); // Rounds up
uint256 fyTokenToPool = baseBalance - baseToPool; // fyTokenToPool is rounded down
// Mint fyToken with underlying
base.safeTransfer(baseJoin, fyTokenToPool);
fyToken.mintWithUnderlying(address(pool_), fyTokenToPool);
// Mint LP tokens with (investment * p) fyToken and (investment * (1 - p)) base
base.safeTransfer(address(pool_), baseToPool);
(,, cached) = pool_.mint(address(this), address(this), minRatio, maxRatio);
if (_totalSupply == 0) _mint(msg.sender, cached); // Initialize the strategy if needed
invariants[address(pool_)] = pool_.invariant(); // Cache the invariant to help the frontend calculate profits
emit PoolStarted(address(pool_));
}
/// @dev Divest out of a pool once it has matured
function endPool()
external
afterMaturity
{
// Caching
IPool pool_ = pool;
IFYToken fyToken_ = fyToken;
uint256 toDivest = pool_.balanceOf(address(this));
// Burn lpTokens
IERC20(address(pool_)).safeTransfer(address(pool_), toDivest);
(,, uint256 fyTokenDivested) = pool_.burn(address(this), address(this), 0, type(uint256).max); // We don't care about slippage, because the strategy holds to maturity
// Redeem any fyToken
IERC20(address(fyToken_)).safeTransfer(address(fyToken_), fyTokenDivested);
fyToken_.redeem(address(this), fyTokenDivested);
emit PoolEnded(address(pool_));
// Clear up
delete pool;
delete fyToken;
delete seriesId;
delete cached;
}
/// @dev Mint strategy tokens.
/// @notice The lp tokens that the user contributes need to have been transferred previously, using a batchable router.
function mint(address to)
external
poolSelected
returns (uint256 minted)
{
// minted = supply * value(deposit) / value(strategy)
uint256 cached_ = cached;
uint256 deposit = pool.balanceOf(address(this)) - cached_;
minted = _totalSupply * deposit / cached_;
cached = cached_ + deposit;
_mint(to, minted);
}
/// @dev Burn strategy tokens to withdraw lp tokens. The lp tokens obtained won't be of the same pool that the investor deposited,
/// if the strategy has swapped to another pool.
/// @notice The strategy tokens that the user burns need to have been transferred previously, using a batchable router.
function burn(address to)
external
poolSelected
returns (uint256 withdrawal)
{
// strategy * burnt/supply = withdrawal
uint256 cached_ = cached;
uint256 burnt = _balanceOf[address(this)];
withdrawal = cached_ * burnt / _totalSupply;
cached = cached_ - withdrawal;
_burn(address(this), burnt);
IERC20(address(pool)).safeTransfer(to, withdrawal);
}
/// @dev Burn strategy tokens to withdraw base tokens. It can be called only when a pool is not selected.
/// @notice The strategy tokens that the user burns need to have been transferred previously, using a batchable router.
function burnForBase(address to)
external
poolNotSelected
returns (uint256 withdrawal)
{
// strategy * burnt/supply = withdrawal
uint256 burnt = _balanceOf[address(this)];
withdrawal = base.balanceOf(address(this)) * burnt / _totalSupply;
_burn(address(this), burnt);
base.safeTransfer(to, withdrawal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "hardhat/console.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes4` identifier. These are expected to be the
* signatures for all the functions in the contract. Special roles should be exposed
* in the external API and be unique:
*
* ```
* bytes4 public constant ROOT = 0x00000000;
* ```
*
* Roles represent restricted access to a function call. For that purpose, use {auth}:
*
* ```
* function foo() public auth {
* ...
* }
* ```
*
* 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 `ROOT`, 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 `ROOT` 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.
*/
contract AccessControl {
struct RoleData {
mapping (address => bool) members;
bytes4 adminRole;
}
mapping (bytes4 => RoleData) private _roles;
bytes4 public constant ROOT = 0x00000000;
bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833()
bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function
bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368()
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role
*
* `ROOT` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call.
*/
event RoleGranted(bytes4 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(bytes4 indexed role, address indexed account, address indexed sender);
/**
* @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members.
* Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore.
*/
constructor () {
_grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender
_setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree
}
/**
* @dev Each function in the contract has its own role, identified by their msg.sig signature.
* ROOT can give and remove access to each function, lock any further access being granted to
* a specific action, or even create other roles to delegate admin control over a function.
*/
modifier auth() {
require (_hasRole(msg.sig, msg.sender), "Access denied");
_;
}
/**
* @dev Allow only if the caller has been granted the admin role of `role`.
*/
modifier admin(bytes4 role) {
require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin");
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes4 role, address account) external view returns (bool) {
return _hasRole(role, account);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes4 role) external view returns (bytes4) {
return _getRoleAdmin(role);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
* If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) {
_setRoleAdmin(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(bytes4 role, address account) external virtual admin(role) {
_grantRole(role, account);
}
/**
* @dev Grants all of `role` in `roles` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - For each `role` in `roles`, the caller must have ``role``'s admin role.
*/
function grantRoles(bytes4[] memory roles, address account) external virtual {
for (uint256 i = 0; i < roles.length; i++) {
require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin");
_grantRole(roles[i], account);
}
}
/**
* @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``.
* Emits a {RoleAdminChanged} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function lockRole(bytes4 role) external virtual admin(role) {
_setRoleAdmin(role, LOCK);
}
/**
* @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(bytes4 role, address account) external virtual admin(role) {
_revokeRole(role, account);
}
/**
* @dev Revokes all of `role` in `roles` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - For each `role` in `roles`, the caller must have ``role``'s admin role.
*/
function revokeRoles(bytes4[] memory roles, address account) external virtual {
for (uint256 i = 0; i < roles.length; i++) {
require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin");
_revokeRole(roles[i], account);
}
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes4 role, address account) external virtual {
require(account == msg.sender, "Renounce only for self");
_revokeRole(role, account);
}
function _hasRole(bytes4 role, address account) internal view returns (bool) {
return _roles[role].members[account];
}
function _getRoleAdmin(bytes4 role) internal view returns (bytes4) {
return _roles[role].adminRole;
}
function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual {
if (_getRoleAdmin(role) != adminRole) {
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, adminRole);
}
}
function _grantRole(bytes4 role, address account) internal {
if (!_hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
function _revokeRole(bytes4 role, address account) internal {
if (_hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "../token/IERC20Metadata.sol";
import "../utils/AddressStringUtil.sol";
// produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32
// this library will always produce a string symbol to represent the token
library SafeERC20Namer {
function bytes32ToString(bytes32 x) private pure returns (string memory) {
bytes memory bytesString = new bytes(32);
uint256 charCount = 0;
for (uint256 j = 0; j < 32; j++) {
bytes1 char = x[j];
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint256 j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
// assumes the data is in position 2
function parseStringData(bytes memory b) private pure returns (string memory) {
uint256 charCount = 0;
// first parse the charCount out of the data
for (uint256 i = 32; i < 64; i++) {
charCount <<= 8;
charCount += uint8(b[i]);
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint256 i = 0; i < charCount; i++) {
bytesStringTrimmed[i] = b[i + 64];
}
return string(bytesStringTrimmed);
}
// uses a heuristic to produce a token name from the address
// the heuristic returns the full hex of the address string in upper case
function addressToName(address token) private pure returns (string memory) {
return AddressStringUtil.toAsciiString(token, 40);
}
// uses a heuristic to produce a token symbol from the address
// the heuristic returns the first 6 hex of the address string in upper case
function addressToSymbol(address token) private pure returns (string memory) {
return AddressStringUtil.toAsciiString(token, 6);
}
// calls an external view token contract method that returns a symbol or name, and parses the output into a string
function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) {
(bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector));
// if not implemented, or returns empty data, return empty string
if (!success || data.length == 0) {
return "";
}
// bytes32 data always has length 32
if (data.length == 32) {
bytes32 decoded = abi.decode(data, (bytes32));
return bytes32ToString(decoded);
} else if (data.length > 64) {
return abi.decode(data, (string));
}
return "";
}
// attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address
function tokenSymbol(address token) public view returns (string memory) {
string memory symbol = callAndParseStringReturn(token, IERC20Metadata.symbol.selector);
if (bytes(symbol).length == 0) {
// fallback to 6 uppercase hex of address
return addressToSymbol(token);
}
return symbol;
}
// attempts to extract the token name. if it does not implement name, returns a name derived from the address
function tokenName(address token) public view returns (string memory) {
string memory name = callAndParseStringReturn(token, IERC20Metadata.name.selector);
if (bytes(name).length == 0) {
// fallback to full hex of address
return addressToName(token);
}
return name;
}
/// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
/// @param token The address of the ERC-20 token contract.
/// @return (uint8) Token decimals.
function tokenDecimals(address token) public view returns (uint8) {
(bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(IERC20Metadata.decimals.selector));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
import "./IERC20.sol";
import "../utils/RevertMsgExtractor.sol";
// helper methods for transferring ERC20 tokens that do not consistently return true/false
library MinimalTransferHelper {
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with the underlying revert message if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
if (!(success && (data.length == 0 || abi.decode(data, (bool))))) revert(RevertMsgExtractor.getRevertMsg(data));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./ERC20Permit.sol";
import "../access/AccessControl.sol";
import "../utils/RevertMsgExtractor.sol";
import "../token/MinimalTransferHelper.sol";
import "../cast/CastU256U128.sol";
import "../cast/CastU256U32.sol";
/// @dev A token inheriting from ERC20Rewards will reward token holders with a rewards token.
/// The rewarded amount will be a fixed wei per second, distributed proportionally to token holders
/// by the size of their holdings.
contract ERC20Rewards is AccessControl, ERC20Permit {
using MinimalTransferHelper for IERC20;
using CastU256U32 for uint256;
using CastU256U128 for uint256;
event RewardsTokenSet(IERC20 token);
event RewardsSet(uint32 start, uint32 end, uint256 rate);
event RewardsPerTokenUpdated(uint256 accumulated);
event UserRewardsUpdated(address user, uint256 userRewards, uint256 paidRewardPerToken);
event Claimed(address receiver, uint256 claimed);
struct RewardsPeriod {
uint32 start; // Start time for the current rewardsToken schedule
uint32 end; // End time for the current rewardsToken schedule
}
struct RewardsPerToken {
uint128 accumulated; // Accumulated rewards per token for the period, scaled up by 1e18
uint32 lastUpdated; // Last time the rewards per token accumulator was updated
uint96 rate; // Wei rewarded per second among all token holders
}
struct UserRewards {
uint128 accumulated; // Accumulated rewards for the user until the checkpoint
uint128 checkpoint; // RewardsPerToken the last time the user rewards were updated
}
IERC20 public rewardsToken; // Token used as rewards
RewardsPeriod public rewardsPeriod; // Period in which rewards are accumulated by users
RewardsPerToken public rewardsPerToken; // Accumulator to track rewards per token
mapping (address => UserRewards) public rewards; // Rewards accumulated by users
constructor(string memory name, string memory symbol, uint8 decimals)
ERC20Permit(name, symbol, decimals)
{ }
/// @dev Return the earliest of two timestamps
function earliest(uint32 x, uint32 y) internal pure returns (uint32 z) {
z = (x < y) ? x : y;
}
/// @dev Set a rewards token.
/// @notice Careful, this can only be done once.
function setRewardsToken(IERC20 rewardsToken_)
external
auth
{
require(rewardsToken == IERC20(address(0)), "Rewards token already set");
rewardsToken = rewardsToken_;
emit RewardsTokenSet(rewardsToken_);
}
/// @dev Set a rewards schedule
function setRewards(uint32 start, uint32 end, uint96 rate)
external
auth
{
require(
start <= end,
"Incorrect input"
);
require(
rewardsToken != IERC20(address(0)),
"Rewards token not set"
);
// A new rewards program can be set if one is not running
require(
block.timestamp.u32() < rewardsPeriod.start || block.timestamp.u32() > rewardsPeriod.end,
"Ongoing rewards"
);
rewardsPeriod.start = start;
rewardsPeriod.end = end;
// If setting up a new rewards program, the rewardsPerToken.accumulated is used and built upon
// New rewards start accumulating from the new rewards program start
// Any unaccounted rewards from last program can still be added to the user rewards
// Any unclaimed rewards can still be claimed
rewardsPerToken.lastUpdated = start;
rewardsPerToken.rate = rate;
emit RewardsSet(start, end, rate);
}
/// @dev Update the rewards per token accumulator.
/// @notice Needs to be called on each liquidity event
function _updateRewardsPerToken() internal {
RewardsPerToken memory rewardsPerToken_ = rewardsPerToken;
RewardsPeriod memory rewardsPeriod_ = rewardsPeriod;
uint256 totalSupply_ = _totalSupply;
// We skip the update if the program hasn't started
if (block.timestamp.u32() < rewardsPeriod_.start) return;
// Find out the unaccounted time
uint32 end = earliest(block.timestamp.u32(), rewardsPeriod_.end);
uint256 unaccountedTime = end - rewardsPerToken_.lastUpdated; // Cast to uint256 to avoid overflows later on
if (unaccountedTime == 0) return; // We skip the storage changes if already updated in the same block
// Calculate and update the new value of the accumulator. unaccountedTime casts it into uint256, which is desired.
// If the first mint happens mid-program, we don't update the accumulator, no one gets the rewards for that period.
if (totalSupply_ != 0) rewardsPerToken_.accumulated = (rewardsPerToken_.accumulated + 1e18 * unaccountedTime * rewardsPerToken_.rate / totalSupply_).u128(); // The rewards per token are scaled up for precision
rewardsPerToken_.lastUpdated = end;
rewardsPerToken = rewardsPerToken_;
emit RewardsPerTokenUpdated(rewardsPerToken_.accumulated);
}
/// @dev Accumulate rewards for an user.
/// @notice Needs to be called on each liquidity event, or when user balances change.
function _updateUserRewards(address user) internal returns (uint128) {
UserRewards memory userRewards_ = rewards[user];
RewardsPerToken memory rewardsPerToken_ = rewardsPerToken;
// Calculate and update the new value user reserves. _balanceOf[user] casts it into uint256, which is desired.
userRewards_.accumulated = (userRewards_.accumulated + _balanceOf[user] * (rewardsPerToken_.accumulated - userRewards_.checkpoint) / 1e18).u128(); // We must scale down the rewards by the precision factor
userRewards_.checkpoint = rewardsPerToken_.accumulated;
rewards[user] = userRewards_;
emit UserRewardsUpdated(user, userRewards_.accumulated, userRewards_.checkpoint);
return userRewards_.accumulated;
}
/// @dev Mint tokens, after accumulating rewards for an user and update the rewards per token accumulator.
function _mint(address dst, uint256 wad)
internal virtual override
returns (bool)
{
_updateRewardsPerToken();
_updateUserRewards(dst);
return super._mint(dst, wad);
}
/// @dev Burn tokens, after accumulating rewards for an user and update the rewards per token accumulator.
function _burn(address src, uint256 wad)
internal virtual override
returns (bool)
{
_updateRewardsPerToken();
_updateUserRewards(src);
return super._burn(src, wad);
}
/// @dev Transfer tokens, after updating rewards for source and destination.
function _transfer(address src, address dst, uint wad) internal virtual override returns (bool) {
_updateRewardsPerToken();
_updateUserRewards(src);
_updateUserRewards(dst);
return super._transfer(src, dst, wad);
}
/// @dev Claim all rewards from caller into a given address
function claim(address to)
external
returns (uint256 claiming)
{
_updateRewardsPerToken();
claiming = _updateUserRewards(msg.sender);
rewards[msg.sender].accumulated = 0; // A Claimed event implies the rewards were set to zero
rewardsToken.safeTransfer(to, claiming);
emit Claimed(to, claiming);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
library CastU256I128 {
/// @dev Safe casting from uint256 to int256
function i128(uint256 x) internal pure returns(int128) {
require(x <= uint256(int256(type(int128).max)), "Cast overflow");
return int128(int256(x));
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
library CastU128I128 {
/// @dev Safely cast an uint128 to an int128
function i128(uint128 x) internal pure returns (int128 y) {
require (x <= uint128(type(int128).max), "Cast overflow");
y = int128(x);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IFYToken.sol";
import "./IOracle.sol";
library DataTypes {
struct Series {
IFYToken fyToken; // Redeemable token for the series.
bytes6 baseId; // Asset received on redemption.
uint32 maturity; // Unix time at which redemption becomes possible.
// bytes2 free
}
struct Debt {
uint96 max; // Maximum debt accepted for a given underlying, across all series
uint24 min; // Minimum debt accepted for a given underlying, across all series
uint8 dec; // Multiplying factor (10**dec) for max and min
uint128 sum; // Current debt for a given underlying, across all series
}
struct SpotOracle {
IOracle oracle; // Address for the spot price oracle
uint32 ratio; // Collateralization ratio to multiply the price for
// bytes8 free
}
struct Vault {
address owner;
bytes6 seriesId; // Each vault is related to only one series, which also determines the underlying.
bytes6 ilkId; // Asset accepted as collateral
}
struct Balances {
uint128 art; // Debt amount
uint128 ink; // Collateral amount
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IFYToken.sol";
import "./IOracle.sol";
import "./DataTypes.sol";
interface ICauldron {
/// @dev Variable rate lending oracle for an underlying
function lendingOracles(bytes6 baseId) external view returns (IOracle);
/// @dev An user can own one or more Vaults, with each vault being able to borrow from a single series.
function vaults(bytes12 vault) external view returns (DataTypes.Vault memory);
/// @dev Series available in Cauldron.
function series(bytes6 seriesId) external view returns (DataTypes.Series memory);
/// @dev Assets available in Cauldron.
function assets(bytes6 assetsId) external view returns (address);
/// @dev Each vault records debt and collateral balances_.
function balances(bytes12 vault) external view returns (DataTypes.Balances memory);
/// @dev Max, min and sum of debt per underlying and collateral.
function debt(bytes6 baseId, bytes6 ilkId) external view returns (DataTypes.Debt memory);
/// @dev Create a new vault, linked to a series (and therefore underlying) and up to 5 collateral types
function build(address owner, bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external returns (DataTypes.Vault memory);
/// @dev Destroy an empty vault. Used to recover gas costs.
function destroy(bytes12 vault) external;
/// @dev Change a vault series and/or collateral types.
function tweak(bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external returns (DataTypes.Vault memory);
/// @dev Give a vault to another user.
function give(bytes12 vaultId, address receiver) external returns (DataTypes.Vault memory);
/// @dev Move collateral and debt between vaults.
function stir(bytes12 from, bytes12 to, uint128 ink, uint128 art) external returns (DataTypes.Balances memory, DataTypes.Balances memory);
/// @dev Manipulate a vault debt and collateral.
function pour(bytes12 vaultId, int128 ink, int128 art) external returns (DataTypes.Balances memory);
/// @dev Change series and debt of a vault.
/// The module calling this function also needs to buy underlying in the pool for the new series, and sell it in pool for the old series.
function roll(bytes12 vaultId, bytes6 seriesId, int128 art) external returns (DataTypes.Vault memory, DataTypes.Balances memory);
/// @dev Reduce debt and collateral from a vault, ignoring collateralization checks.
function slurp(bytes12 vaultId, uint128 ink, uint128 art) external returns (DataTypes.Balances memory);
// ==== Helpers ====
/// @dev Convert a debt amount for a series from base to fyToken terms.
/// @notice Think about rounding if using, since we are dividing.
function debtFromBase(bytes6 seriesId, uint128 base) external returns (uint128 art);
/// @dev Convert a debt amount for a series from fyToken to base terms
function debtToBase(bytes6 seriesId, uint128 art) external returns (uint128 base);
// ==== Accounting ====
/// @dev Record the borrowing rate at maturity for a series
function mature(bytes6 seriesId) external;
/// @dev Retrieve the rate accrual since maturity, maturing if necessary.
function accrual(bytes6 seriesId) external returns (uint256);
/// @dev Return the collateralization level of a vault. It will be negative if undercollateralized.
function level(bytes12 vaultId) external returns (int256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IJoin.sol";
import "./ICauldron.sol";
interface ILadle {
function joins(bytes6) external view returns (IJoin);
function cauldron() external view returns (ICauldron);
function build(bytes6 seriesId, bytes6 ilkId, uint8 salt) external returns (bytes12 vaultId, DataTypes.Vault memory vault);
function destroy(bytes12 vaultId) external;
function pour(bytes12 vaultId, address to, int128 ink, int128 art) external;
function close(bytes12 vaultId, address to, int128 ink, int128 art) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.0;
import "@yield-protocol/utils-v2/contracts/token/IERC20.sol";
import "@yield-protocol/utils-v2/contracts/token/IERC2612.sol";
import "@yield-protocol/vault-interfaces/IFYToken.sol";
interface IPool is IERC20, IERC2612 {
function ts() external view returns(int128);
function g1() external view returns(int128);
function g2() external view returns(int128);
function maturity() external view returns(uint32);
function scaleFactor() external view returns(uint96);
function getCache() external view returns (uint112, uint112, uint32);
function base() external view returns(IERC20);
function fyToken() external view returns(IFYToken);
function getBaseBalance() external view returns(uint112);
function getFYTokenBalance() external view returns(uint112);
function retrieveBase(address to) external returns(uint128 retrieved);
function retrieveFYToken(address to) external returns(uint128 retrieved);
function sellBase(address to, uint128 min) external returns(uint128);
function buyBase(address to, uint128 baseOut, uint128 max) external returns(uint128);
function sellFYToken(address to, uint128 min) external returns(uint128);
function buyFYToken(address to, uint128 fyTokenOut, uint128 max) external returns(uint128);
function sellBasePreview(uint128 baseIn) external view returns(uint128);
function buyBasePreview(uint128 baseOut) external view returns(uint128);
function sellFYTokenPreview(uint128 fyTokenIn) external view returns(uint128);
function buyFYTokenPreview(uint128 fyTokenOut) external view returns(uint128);
function mint(address to, address remainder, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256);
function mintWithBase(address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256);
function burn(address baseTo, address fyTokenTo, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256);
function burnForBase(address to, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.6;
import "@yield-protocol/yieldspace-interfaces/IPool.sol";
import "../YieldMath.sol";
library YieldMathExtensions {
/// @dev Calculate the invariant for this pool
function invariant(IPool pool) external view returns (uint128) {
uint32 maturity = pool.maturity();
uint32 timeToMaturity = (maturity > uint32(block.timestamp)) ? maturity - uint32(block.timestamp) : 0;
return YieldMath.invariant(
pool.getBaseBalance(),
pool.getFYTokenBalance(),
pool.totalSupply(),
timeToMaturity,
pool.ts()
);
}
/// @dev max amount of fyTokens that can be bought from the pool
function maxFYTokenOut(IPool pool) external view returns (uint128) {
(uint112 _baseCached, uint112 _fyTokenCached,) = pool.getCache();
uint96 scaleFactor = pool.scaleFactor();
return YieldMath.maxFYTokenOut(
_baseCached * scaleFactor,
_fyTokenCached * scaleFactor,
pool.maturity() - uint32(block.timestamp),
pool.ts(),
pool.g1()
) / scaleFactor;
}
/// @dev max amount of fyTokens that can be sold into the pool
function maxFYTokenIn(IPool pool) external view returns (uint128) {
(uint112 _baseCached, uint112 _fyTokenCached,) = pool.getCache();
uint96 scaleFactor = pool.scaleFactor();
return YieldMath.maxFYTokenIn(
_baseCached * scaleFactor,
_fyTokenCached * scaleFactor,
pool.maturity() - uint32(block.timestamp),
pool.ts(),
pool.g2()
) / scaleFactor;
}
/// @dev max amount of Base that can be sold to the pool
function maxBaseIn(IPool pool) external view returns (uint128) {
(uint112 _baseCached, uint112 _fyTokenCached,) = pool.getCache();
uint96 scaleFactor = pool.scaleFactor();
return YieldMath.maxBaseIn(
_baseCached * scaleFactor,
_fyTokenCached * scaleFactor,
pool.maturity() - uint32(block.timestamp),
pool.ts(),
pool.g1()
) / scaleFactor;
}
/// @dev max amount of Base that can be bought from the pool
function maxBaseOut(IPool pool) external view returns (uint128) {
(uint112 _baseCached, uint112 _fyTokenCached,) = pool.getCache();
uint96 scaleFactor = pool.scaleFactor();
return YieldMath.maxBaseOut(
_baseCached * scaleFactor,
_fyTokenCached * scaleFactor,
pool.maturity() - uint32(block.timestamp),
pool.ts(),
pool.g2()
) / scaleFactor;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.0;
import "./IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
library AddressStringUtil {
// converts an address to the uppercase hex string, extracting only len bytes (up to 20, multiple of 2)
function toAsciiString(address addr, uint256 len) internal pure returns (string memory) {
require(len % 2 == 0 && len > 0 && len <= 40, "AddressStringUtil: INVALID_LEN");
bytes memory s = new bytes(len);
uint256 addrNum = uint256(uint160(addr));
for (uint256 ii = 0; ii < len ; ii +=2) {
uint8 b = uint8(addrNum >> (4 * (38 - ii)));
s[ii] = char(b >> 4);
s[ii + 1] = char(b & 0x0f);
}
return string(s);
}
// hi and lo are only 4 bits and between 0 and 16
// this method converts those values to the unicode/ascii code point for the hex representation
// uses upper case for the characters
function char(uint8 b) private pure returns (bytes1 c) {
if (b < 10) {
return bytes1(b + 0x30);
} else {
return bytes1(b + 0x37);
}
}
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/sushiswap/BoringSolidity/blob/441e51c0544cf2451e6116fe00515e71d7c42e2c/contracts/BoringBatchable.sol
pragma solidity >=0.6.0;
library RevertMsgExtractor {
/// @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
}
}
// SPDX-License-Identifier: MIT
// Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/53516bc555a454862470e7860a9b5254db4d00f5/contracts/token/ERC20/ERC20Permit.sol
pragma solidity ^0.8.0;
import "./ERC20.sol";
import "./IERC2612.sol";
/**
* @dev Extension of {ERC20} that allows token holders to use their tokens
* without sending any transactions by setting {IERC20-allowance} with a
* signature using the {permit} method, and then spend them via
* {IERC20-transferFrom}.
*
* The {permit} signature mechanism conforms to the {IERC2612} interface.
*/
abstract contract ERC20Permit is ERC20, IERC2612 {
mapping (address => uint256) public override nonces;
bytes32 public immutable PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private immutable _DOMAIN_SEPARATOR;
uint256 public immutable deploymentChainId;
constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_, decimals_) {
deploymentChainId = block.chainid;
_DOMAIN_SEPARATOR = _calculateDomainSeparator(block.chainid);
}
/// @dev Calculate the DOMAIN_SEPARATOR.
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256(bytes(version())),
chainId,
address(this)
)
);
}
/// @dev Return the DOMAIN_SEPARATOR.
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return block.chainid == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(block.chainid);
}
/// @dev Setting the version as a function so that it can be overriden
function version() public pure virtual returns(string memory) { return "1"; }
/**
* @dev See {IERC2612-permit}.
*
* In cases where the free option is not a concern, deadline can simply be
* set to uint(-1), so it should be seen as an optional parameter
*/
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external virtual override {
require(deadline >= block.timestamp, "ERC20Permit: expired deadline");
bytes32 hashStruct = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
amount,
nonces[owner]++,
deadline
)
);
bytes32 hash = keccak256(
abi.encodePacked(
"\x19\x01",
block.chainid == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(block.chainid),
hashStruct
)
);
address signer = ecrecover(hash, v, r, s);
require(
signer != address(0) && signer == owner,
"ERC20Permit: invalid signature"
);
_setAllowance(owner, spender, amount);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
library CastU256U128 {
/// @dev Safely cast an uint256 to an uint128
function u128(uint256 x) internal pure returns (uint128 y) {
require (x <= type(uint128).max, "Cast overflow");
y = uint128(x);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
library CastU256U32 {
/// @dev Safely cast an uint256 to an u32
function u32(uint256 x) internal pure returns (uint32 y) {
require (x <= type(uint32).max, "Cast overflow");
y = uint32(x);
}
}
// SPDX-License-Identifier: MIT
// Inspired on token.sol from DappHub. Natspec adpated from OpenZeppelin.
pragma solidity ^0.8.0;
import "./IERC20Metadata.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}.
*
* 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.
*
* Calls to {transferFrom} do not check for allowance if the caller is the owner
* of the funds. This allows to reduce the number of approvals that are necessary.
*
* Finally, {transferFrom} does not decrease the allowance if it is set to
* type(uint256).max. This reduces the gas costs without any likely impact.
*/
contract ERC20 is IERC20Metadata {
uint256 internal _totalSupply;
mapping (address => uint256) internal _balanceOf;
mapping (address => mapping (address => uint256)) internal _allowance;
string public override name = "???";
string public override symbol = "???";
uint8 public override decimals = 18;
/**
* @dev Sets the values for {name}, {symbol} and {decimals}.
*/
constructor(string memory name_, string memory symbol_, uint8 decimals_) {
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() external view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address guy) external view virtual override returns (uint256) {
return _balanceOf[guy];
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) external view virtual override returns (uint256) {
return _allowance[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*/
function approve(address spender, uint wad) external virtual override returns (bool) {
return _setAllowance(msg.sender, spender, wad);
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - the caller must have a balance of at least `wad`.
*/
function transfer(address dst, uint wad) external virtual override returns (bool) {
return _transfer(msg.sender, dst, wad);
}
/**
* @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:
*
* - `src` must have a balance of at least `wad`.
* - the caller is not `src`, it must have allowance for ``src``'s tokens of at least
* `wad`.
*/
/// if_succeeds {:msg "TransferFrom - decrease allowance"} msg.sender != src ==> old(_allowance[src][msg.sender]) >= wad;
function transferFrom(address src, address dst, uint wad) external virtual override returns (bool) {
_decreaseAllowance(src, wad);
return _transfer(src, dst, wad);
}
/**
* @dev Moves tokens `wad` from `src` to `dst`.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `src` must have a balance of at least `amount`.
*/
/// if_succeeds {:msg "Transfer - src decrease"} old(_balanceOf[src]) >= _balanceOf[src];
/// if_succeeds {:msg "Transfer - dst increase"} _balanceOf[dst] >= old(_balanceOf[dst]);
/// if_succeeds {:msg "Transfer - supply"} old(_balanceOf[src]) + old(_balanceOf[dst]) == _balanceOf[src] + _balanceOf[dst];
function _transfer(address src, address dst, uint wad) internal virtual returns (bool) {
require(_balanceOf[src] >= wad, "ERC20: Insufficient balance");
unchecked { _balanceOf[src] = _balanceOf[src] - wad; }
_balanceOf[dst] = _balanceOf[dst] + wad;
emit Transfer(src, dst, wad);
return true;
}
/**
* @dev Sets the allowance granted to `spender` by `owner`.
*
* Emits an {Approval} event indicating the updated allowance.
*/
function _setAllowance(address owner, address spender, uint wad) internal virtual returns (bool) {
_allowance[owner][spender] = wad;
emit Approval(owner, spender, wad);
return true;
}
/**
* @dev Decreases the allowance granted to the caller by `src`, unless src == msg.sender or _allowance[src][msg.sender] == MAX
*
* Emits an {Approval} event indicating the updated allowance, if the allowance is updated.
*
* Requirements:
*
* - `spender` must have allowance for the caller of at least
* `wad`, unless src == msg.sender
*/
/// if_succeeds {:msg "Decrease allowance - underflow"} old(_allowance[src][msg.sender]) <= _allowance[src][msg.sender];
function _decreaseAllowance(address src, uint wad) internal virtual returns (bool) {
if (src != msg.sender) {
uint256 allowed = _allowance[src][msg.sender];
if (allowed != type(uint).max) {
require(allowed >= wad, "ERC20: Insufficient approval");
unchecked { _setAllowance(src, msg.sender, allowed - wad); }
}
}
return true;
}
/** @dev Creates `wad` tokens and assigns them to `dst`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*/
/// if_succeeds {:msg "Mint - balance overflow"} old(_balanceOf[dst]) >= _balanceOf[dst];
/// if_succeeds {:msg "Mint - supply overflow"} old(_totalSupply) >= _totalSupply;
function _mint(address dst, uint wad) internal virtual returns (bool) {
_balanceOf[dst] = _balanceOf[dst] + wad;
_totalSupply = _totalSupply + wad;
emit Transfer(address(0), dst, wad);
return true;
}
/**
* @dev Destroys `wad` tokens from `src`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `src` must have at least `wad` tokens.
*/
/// if_succeeds {:msg "Burn - balance underflow"} old(_balanceOf[src]) <= _balanceOf[src];
/// if_succeeds {:msg "Burn - supply underflow"} old(_totalSupply) <= _totalSupply;
function _burn(address src, uint wad) internal virtual returns (bool) {
unchecked {
require(_balanceOf[src] >= wad, "ERC20: Insufficient balance");
_balanceOf[src] = _balanceOf[src] - wad;
_totalSupply = _totalSupply - wad;
emit Transfer(src, address(0), wad);
}
return true;
}
}
// SPDX-License-Identifier: MIT
// Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*/
interface IERC2612 {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@yield-protocol/utils-v2/contracts/token/IERC20.sol";
interface IFYToken is IERC20 {
/// @dev Asset that is returned on redemption.
function underlying() external view returns (address);
/// @dev Unix time at which redemption of fyToken for underlying are possible
function maturity() external view returns (uint256);
/// @dev Record price data at maturity
function mature() external;
/// @dev Mint fyToken providing an equal amount of underlying to the protocol
function mintWithUnderlying(address to, uint256 amount) external;
/// @dev Burn fyToken after maturity for an amount of underlying.
function redeem(address to, uint256 amount) external returns (uint256);
/// @dev Mint fyToken.
/// This function can only be called by other Yield contracts, not users directly.
/// @param to Wallet to mint the fyToken in.
/// @param fyTokenAmount Amount of fyToken to mint.
function mint(address to, uint256 fyTokenAmount) external;
/// @dev Burn fyToken.
/// This function can only be called by other Yield contracts, not users directly.
/// @param from Wallet to burn the fyToken from.
/// @param fyTokenAmount Amount of fyToken to burn.
function burn(address from, uint256 fyTokenAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOracle {
/**
* @notice Doesn't refresh the price, but returns the latest value available without doing any transactional operations:
* @return value in wei
*/
function peek(bytes32 base, bytes32 quote, uint256 amount) external view returns (uint256 value, uint256 updateTime);
/**
* @notice Does whatever work or queries will yield the most up-to-date price, and returns it.
* @return value in wei
*/
function get(bytes32 base, bytes32 quote, uint256 amount) external returns (uint256 value, uint256 updateTime);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@yield-protocol/utils-v2/contracts/token/IERC20.sol";
interface IJoin {
/// @dev asset managed by this contract
function asset() external view returns (address);
/// @dev Add tokens to this contract.
function join(address user, uint128 wad) external returns (uint128);
/// @dev Remove tokens to this contract.
function exit(address user, uint128 wad) external returns (uint128);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.6;
import "./Math64x64.sol";
library Exp64x64 {
/**
* Raise given number x into power specified as a simple fraction y/z and then
* multiply the result by the normalization factor 2^(128 * (1 - y/z)).
* Revert if z is zero, or if both x and y are zeros.
*
* @param x number to raise into given power y/z
* @param y numerator of the power to raise x into
* @param z denominator of the power to raise x into
* @return x raised into power y/z and then multiplied by 2^(128 * (1 - y/z))
*/
function pow(uint128 x, uint128 y, uint128 z)
internal pure returns(uint128) {
unchecked {
require(z != 0);
if(x == 0) {
require(y != 0);
return 0;
} else {
uint256 l =
uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - log_2(x)) * y / z;
if(l > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return 0;
else return pow_2(uint128(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - l));
}
}
}
/**
* Calculate base 2 logarithm of an unsigned 128-bit integer number. Revert
* in case x is zero.
*
* @param x number to calculate base 2 logarithm of
* @return base 2 logarithm of x, multiplied by 2^121
*/
function log_2(uint128 x)
internal pure returns(uint128) {
unchecked {
require(x != 0);
uint b = x;
uint l = 0xFE000000000000000000000000000000;
if(b < 0x10000000000000000) {l -= 0x80000000000000000000000000000000; b <<= 64;}
if(b < 0x1000000000000000000000000) {l -= 0x40000000000000000000000000000000; b <<= 32;}
if(b < 0x10000000000000000000000000000) {l -= 0x20000000000000000000000000000000; b <<= 16;}
if(b < 0x1000000000000000000000000000000) {l -= 0x10000000000000000000000000000000; b <<= 8;}
if(b < 0x10000000000000000000000000000000) {l -= 0x8000000000000000000000000000000; b <<= 4;}
if(b < 0x40000000000000000000000000000000) {l -= 0x4000000000000000000000000000000; b <<= 2;}
if(b < 0x80000000000000000000000000000000) {l -= 0x2000000000000000000000000000000; b <<= 1;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000;} /*
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2;}
b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) l |= 0x1; */
return uint128(l);
}
}
/**
* Calculate 2 raised into given power.
*
* @param x power to raise 2 into, multiplied by 2^121
* @return 2 raised into given power
*/
function pow_2(uint128 x)
internal pure returns(uint128) {
unchecked {
uint r = 0x80000000000000000000000000000000;
if(x & 0x1000000000000000000000000000000 > 0) r = r * 0xb504f333f9de6484597d89b3754abe9f >> 127;
if(x & 0x800000000000000000000000000000 > 0) r = r * 0x9837f0518db8a96f46ad23182e42f6f6 >> 127;
if(x & 0x400000000000000000000000000000 > 0) r = r * 0x8b95c1e3ea8bd6e6fbe4628758a53c90 >> 127;
if(x & 0x200000000000000000000000000000 > 0) r = r * 0x85aac367cc487b14c5c95b8c2154c1b2 >> 127;
if(x & 0x100000000000000000000000000000 > 0) r = r * 0x82cd8698ac2ba1d73e2a475b46520bff >> 127;
if(x & 0x80000000000000000000000000000 > 0) r = r * 0x8164d1f3bc0307737be56527bd14def4 >> 127;
if(x & 0x40000000000000000000000000000 > 0) r = r * 0x80b1ed4fd999ab6c25335719b6e6fd20 >> 127;
if(x & 0x20000000000000000000000000000 > 0) r = r * 0x8058d7d2d5e5f6b094d589f608ee4aa2 >> 127;
if(x & 0x10000000000000000000000000000 > 0) r = r * 0x802c6436d0e04f50ff8ce94a6797b3ce >> 127;
if(x & 0x8000000000000000000000000000 > 0) r = r * 0x8016302f174676283690dfe44d11d008 >> 127;
if(x & 0x4000000000000000000000000000 > 0) r = r * 0x800b179c82028fd0945e54e2ae18f2f0 >> 127;
if(x & 0x2000000000000000000000000000 > 0) r = r * 0x80058baf7fee3b5d1c718b38e549cb93 >> 127;
if(x & 0x1000000000000000000000000000 > 0) r = r * 0x8002c5d00fdcfcb6b6566a58c048be1f >> 127;
if(x & 0x800000000000000000000000000 > 0) r = r * 0x800162e61bed4a48e84c2e1a463473d9 >> 127;
if(x & 0x400000000000000000000000000 > 0) r = r * 0x8000b17292f702a3aa22beacca949013 >> 127;
if(x & 0x200000000000000000000000000 > 0) r = r * 0x800058b92abbae02030c5fa5256f41fe >> 127;
if(x & 0x100000000000000000000000000 > 0) r = r * 0x80002c5c8dade4d71776c0f4dbea67d6 >> 127;
if(x & 0x80000000000000000000000000 > 0) r = r * 0x8000162e44eaf636526be456600bdbe4 >> 127;
if(x & 0x40000000000000000000000000 > 0) r = r * 0x80000b1721fa7c188307016c1cd4e8b6 >> 127;
if(x & 0x20000000000000000000000000 > 0) r = r * 0x8000058b90de7e4cecfc487503488bb1 >> 127;
if(x & 0x10000000000000000000000000 > 0) r = r * 0x800002c5c8678f36cbfce50a6de60b14 >> 127;
if(x & 0x8000000000000000000000000 > 0) r = r * 0x80000162e431db9f80b2347b5d62e516 >> 127;
if(x & 0x4000000000000000000000000 > 0) r = r * 0x800000b1721872d0c7b08cf1e0114152 >> 127;
if(x & 0x2000000000000000000000000 > 0) r = r * 0x80000058b90c1aa8a5c3736cb77e8dff >> 127;
if(x & 0x1000000000000000000000000 > 0) r = r * 0x8000002c5c8605a4635f2efc2362d978 >> 127;
if(x & 0x800000000000000000000000 > 0) r = r * 0x800000162e4300e635cf4a109e3939bd >> 127;
if(x & 0x400000000000000000000000 > 0) r = r * 0x8000000b17217ff81bef9c551590cf83 >> 127;
if(x & 0x200000000000000000000000 > 0) r = r * 0x800000058b90bfdd4e39cd52c0cfa27c >> 127;
if(x & 0x100000000000000000000000 > 0) r = r * 0x80000002c5c85fe6f72d669e0e76e411 >> 127;
if(x & 0x80000000000000000000000 > 0) r = r * 0x8000000162e42ff18f9ad35186d0df28 >> 127;
if(x & 0x40000000000000000000000 > 0) r = r * 0x80000000b17217f84cce71aa0dcfffe7 >> 127;
if(x & 0x20000000000000000000000 > 0) r = r * 0x8000000058b90bfc07a77ad56ed22aaa >> 127;
if(x & 0x10000000000000000000000 > 0) r = r * 0x800000002c5c85fdfc23cdead40da8d6 >> 127;
if(x & 0x8000000000000000000000 > 0) r = r * 0x80000000162e42fefc25eb1571853a66 >> 127;
if(x & 0x4000000000000000000000 > 0) r = r * 0x800000000b17217f7d97f692baacded5 >> 127;
if(x & 0x2000000000000000000000 > 0) r = r * 0x80000000058b90bfbead3b8b5dd254d7 >> 127;
if(x & 0x1000000000000000000000 > 0) r = r * 0x8000000002c5c85fdf4eedd62f084e67 >> 127;
if(x & 0x800000000000000000000 > 0) r = r * 0x800000000162e42fefa58aef378bf586 >> 127;
if(x & 0x400000000000000000000 > 0) r = r * 0x8000000000b17217f7d24a78a3c7ef02 >> 127;
if(x & 0x200000000000000000000 > 0) r = r * 0x800000000058b90bfbe9067c93e474a6 >> 127;
if(x & 0x100000000000000000000 > 0) r = r * 0x80000000002c5c85fdf47b8e5a72599f >> 127;
if(x & 0x80000000000000000000 > 0) r = r * 0x8000000000162e42fefa3bdb315934a2 >> 127;
if(x & 0x40000000000000000000 > 0) r = r * 0x80000000000b17217f7d1d7299b49c46 >> 127;
if(x & 0x20000000000000000000 > 0) r = r * 0x8000000000058b90bfbe8e9a8d1c4ea0 >> 127;
if(x & 0x10000000000000000000 > 0) r = r * 0x800000000002c5c85fdf4745969ea76f >> 127;
if(x & 0x8000000000000000000 > 0) r = r * 0x80000000000162e42fefa3a0df5373bf >> 127;
if(x & 0x4000000000000000000 > 0) r = r * 0x800000000000b17217f7d1cff4aac1e1 >> 127;
if(x & 0x2000000000000000000 > 0) r = r * 0x80000000000058b90bfbe8e7db95a2f1 >> 127;
if(x & 0x1000000000000000000 > 0) r = r * 0x8000000000002c5c85fdf473e61ae1f8 >> 127;
if(x & 0x800000000000000000 > 0) r = r * 0x800000000000162e42fefa39f121751c >> 127;
if(x & 0x400000000000000000 > 0) r = r * 0x8000000000000b17217f7d1cf815bb96 >> 127;
if(x & 0x200000000000000000 > 0) r = r * 0x800000000000058b90bfbe8e7bec1e0d >> 127;
if(x & 0x100000000000000000 > 0) r = r * 0x80000000000002c5c85fdf473dee5f17 >> 127;
if(x & 0x80000000000000000 > 0) r = r * 0x8000000000000162e42fefa39ef5438f >> 127;
if(x & 0x40000000000000000 > 0) r = r * 0x80000000000000b17217f7d1cf7a26c8 >> 127;
if(x & 0x20000000000000000 > 0) r = r * 0x8000000000000058b90bfbe8e7bcf4a4 >> 127;
if(x & 0x10000000000000000 > 0) r = r * 0x800000000000002c5c85fdf473de72a2 >> 127; /*
if(x & 0x8000000000000000 > 0) r = r * 0x80000000000000162e42fefa39ef3765 >> 127;
if(x & 0x4000000000000000 > 0) r = r * 0x800000000000000b17217f7d1cf79b37 >> 127;
if(x & 0x2000000000000000 > 0) r = r * 0x80000000000000058b90bfbe8e7bcd7d >> 127;
if(x & 0x1000000000000000 > 0) r = r * 0x8000000000000002c5c85fdf473de6b6 >> 127;
if(x & 0x800000000000000 > 0) r = r * 0x800000000000000162e42fefa39ef359 >> 127;
if(x & 0x400000000000000 > 0) r = r * 0x8000000000000000b17217f7d1cf79ac >> 127;
if(x & 0x200000000000000 > 0) r = r * 0x800000000000000058b90bfbe8e7bcd6 >> 127;
if(x & 0x100000000000000 > 0) r = r * 0x80000000000000002c5c85fdf473de6a >> 127;
if(x & 0x80000000000000 > 0) r = r * 0x8000000000000000162e42fefa39ef35 >> 127;
if(x & 0x40000000000000 > 0) r = r * 0x80000000000000000b17217f7d1cf79a >> 127;
if(x & 0x20000000000000 > 0) r = r * 0x8000000000000000058b90bfbe8e7bcd >> 127;
if(x & 0x10000000000000 > 0) r = r * 0x800000000000000002c5c85fdf473de6 >> 127;
if(x & 0x8000000000000 > 0) r = r * 0x80000000000000000162e42fefa39ef3 >> 127;
if(x & 0x4000000000000 > 0) r = r * 0x800000000000000000b17217f7d1cf79 >> 127;
if(x & 0x2000000000000 > 0) r = r * 0x80000000000000000058b90bfbe8e7bc >> 127;
if(x & 0x1000000000000 > 0) r = r * 0x8000000000000000002c5c85fdf473de >> 127;
if(x & 0x800000000000 > 0) r = r * 0x800000000000000000162e42fefa39ef >> 127;
if(x & 0x400000000000 > 0) r = r * 0x8000000000000000000b17217f7d1cf7 >> 127;
if(x & 0x200000000000 > 0) r = r * 0x800000000000000000058b90bfbe8e7b >> 127;
if(x & 0x100000000000 > 0) r = r * 0x80000000000000000002c5c85fdf473d >> 127;
if(x & 0x80000000000 > 0) r = r * 0x8000000000000000000162e42fefa39e >> 127;
if(x & 0x40000000000 > 0) r = r * 0x80000000000000000000b17217f7d1cf >> 127;
if(x & 0x20000000000 > 0) r = r * 0x8000000000000000000058b90bfbe8e7 >> 127;
if(x & 0x10000000000 > 0) r = r * 0x800000000000000000002c5c85fdf473 >> 127;
if(x & 0x8000000000 > 0) r = r * 0x80000000000000000000162e42fefa39 >> 127;
if(x & 0x4000000000 > 0) r = r * 0x800000000000000000000b17217f7d1c >> 127;
if(x & 0x2000000000 > 0) r = r * 0x80000000000000000000058b90bfbe8e >> 127;
if(x & 0x1000000000 > 0) r = r * 0x8000000000000000000002c5c85fdf47 >> 127;
if(x & 0x800000000 > 0) r = r * 0x800000000000000000000162e42fefa3 >> 127;
if(x & 0x400000000 > 0) r = r * 0x8000000000000000000000b17217f7d1 >> 127;
if(x & 0x200000000 > 0) r = r * 0x800000000000000000000058b90bfbe8 >> 127;
if(x & 0x100000000 > 0) r = r * 0x80000000000000000000002c5c85fdf4 >> 127;
if(x & 0x80000000 > 0) r = r * 0x8000000000000000000000162e42fefa >> 127;
if(x & 0x40000000 > 0) r = r * 0x80000000000000000000000b17217f7d >> 127;
if(x & 0x20000000 > 0) r = r * 0x8000000000000000000000058b90bfbe >> 127;
if(x & 0x10000000 > 0) r = r * 0x800000000000000000000002c5c85fdf >> 127;
if(x & 0x8000000 > 0) r = r * 0x80000000000000000000000162e42fef >> 127;
if(x & 0x4000000 > 0) r = r * 0x800000000000000000000000b17217f7 >> 127;
if(x & 0x2000000 > 0) r = r * 0x80000000000000000000000058b90bfb >> 127;
if(x & 0x1000000 > 0) r = r * 0x8000000000000000000000002c5c85fd >> 127;
if(x & 0x800000 > 0) r = r * 0x800000000000000000000000162e42fe >> 127;
if(x & 0x400000 > 0) r = r * 0x8000000000000000000000000b17217f >> 127;
if(x & 0x200000 > 0) r = r * 0x800000000000000000000000058b90bf >> 127;
if(x & 0x100000 > 0) r = r * 0x80000000000000000000000002c5c85f >> 127;
if(x & 0x80000 > 0) r = r * 0x8000000000000000000000000162e42f >> 127;
if(x & 0x40000 > 0) r = r * 0x80000000000000000000000000b17217 >> 127;
if(x & 0x20000 > 0) r = r * 0x8000000000000000000000000058b90b >> 127;
if(x & 0x10000 > 0) r = r * 0x800000000000000000000000002c5c85 >> 127;
if(x & 0x8000 > 0) r = r * 0x80000000000000000000000000162e42 >> 127;
if(x & 0x4000 > 0) r = r * 0x800000000000000000000000000b1721 >> 127;
if(x & 0x2000 > 0) r = r * 0x80000000000000000000000000058b90 >> 127;
if(x & 0x1000 > 0) r = r * 0x8000000000000000000000000002c5c8 >> 127;
if(x & 0x800 > 0) r = r * 0x800000000000000000000000000162e4 >> 127;
if(x & 0x400 > 0) r = r * 0x8000000000000000000000000000b172 >> 127;
if(x & 0x200 > 0) r = r * 0x800000000000000000000000000058b9 >> 127;
if(x & 0x100 > 0) r = r * 0x80000000000000000000000000002c5c >> 127;
if(x & 0x80 > 0) r = r * 0x8000000000000000000000000000162e >> 127;
if(x & 0x40 > 0) r = r * 0x80000000000000000000000000000b17 >> 127;
if(x & 0x20 > 0) r = r * 0x8000000000000000000000000000058b >> 127;
if(x & 0x10 > 0) r = r * 0x800000000000000000000000000002c5 >> 127;
if(x & 0x8 > 0) r = r * 0x80000000000000000000000000000162 >> 127;
if(x & 0x4 > 0) r = r * 0x800000000000000000000000000000b1 >> 127;
if(x & 0x2 > 0) r = r * 0x80000000000000000000000000000058 >> 127;
if(x & 0x1 > 0) r = r * 0x8000000000000000000000000000002c >> 127; */
r >>= 127 -(x >> 121);
return uint128(r);
}
}
}
/**
* Ethereum smart contract library implementing Yield Math model.
*/
library YieldMath {
using Math64x64 for int128;
using Math64x64 for uint128;
using Math64x64 for int256;
using Math64x64 for uint256;
using Exp64x64 for uint128;
uint128 public constant ONE = 0x10000000000000000; // In 64.64
uint128 public constant TWO = 0x20000000000000000; // In 64.64
uint256 public constant MAX = type(uint128).max; // Used for overflow checks
uint256 public constant VAR = 1e12; // The logarithm math used is not precise to the wei, but can deviate up to 1e12 from the real value.
/**
* Calculate a YieldSpace pool invariant according to the whitepaper
*/
function invariant(uint128 baseReserves, uint128 fyTokenReserves, uint256 totalSupply, uint128 timeTillMaturity, int128 ts)
public pure returns(uint128)
{
if (totalSupply == 0) return 0;
unchecked {
// a = (1 - ts * timeTillMaturity)
int128 a = int128(ONE).sub(ts.mul(timeTillMaturity.fromUInt()));
require (a > 0, "YieldMath: Too far from maturity");
uint256 sum =
uint256(baseReserves.pow(uint128 (a), ONE)) +
uint256(fyTokenReserves.pow(uint128 (a), ONE)) >> 1;
require(sum < MAX, "YieldMath: Sum overflow");
uint256 result = uint256(uint128(sum).pow(ONE, uint128(a))) / totalSupply;
require (result < MAX, "YieldMath: Result overflow");
return uint128(result);
}
}
/**
* Calculate the amount of fyToken a user would get for given amount of Base.
* https://www.desmos.com/calculator/5nf2xuy6yb
* @param baseReserves base reserves amount
* @param fyTokenReserves fyToken reserves amount
* @param baseAmount base amount to be traded
* @param timeTillMaturity time till maturity in seconds
* @param ts time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return the amount of fyToken a user would get for given amount of Base
*/
function fyTokenOutForBaseIn(
uint128 baseReserves, uint128 fyTokenReserves, uint128 baseAmount,
uint128 timeTillMaturity, int128 ts, int128 g)
public pure returns(uint128) {
unchecked {
uint128 a = _computeA(timeTillMaturity, ts, g);
// za = baseReserves ** a
uint256 za = baseReserves.pow(a, ONE);
// ya = fyTokenReserves ** a
uint256 ya = fyTokenReserves.pow(a, ONE);
// zx = baseReserves + baseAmount
uint256 zx = uint256(baseReserves) + uint256(baseAmount);
require(zx <= MAX, "YieldMath: Too much base in");
// zxa = zx ** a
uint256 zxa = uint128(zx).pow(a, ONE);
// sum = za + ya - zxa
uint256 sum = za + ya - zxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow.
require(sum <= MAX, "YieldMath: Insufficient fyToken reserves");
// result = fyTokenReserves - (sum ** (1/a))
uint256 result = uint256(fyTokenReserves) - uint256(uint128(sum).pow(ONE, a));
require(result <= MAX, "YieldMath: Rounding induced error");
result = result > VAR ? result - VAR : 0; // Subtract error guard, flooring the result at zero
return uint128(result);
}
}
/**
* Calculate the amount of base a user would get for certain amount of fyToken.
* https://www.desmos.com/calculator/6jlrre7ybt
* @param baseReserves base reserves amount
* @param fyTokenReserves fyToken reserves amount
* @param fyTokenAmount fyToken amount to be traded
* @param timeTillMaturity time till maturity in seconds
* @param ts time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return the amount of Base a user would get for given amount of fyToken
*/
function baseOutForFYTokenIn(
uint128 baseReserves, uint128 fyTokenReserves, uint128 fyTokenAmount,
uint128 timeTillMaturity, int128 ts, int128 g)
public pure returns(uint128) {
unchecked {
uint128 a = _computeA(timeTillMaturity, ts, g);
// za = baseReserves ** a
uint256 za = baseReserves.pow(a, ONE);
// ya = fyTokenReserves ** a
uint256 ya = fyTokenReserves.pow(a, ONE);
// yx = fyDayReserves + fyTokenAmount
uint256 yx = uint256(fyTokenReserves) + uint256(fyTokenAmount);
require(yx <= MAX, "YieldMath: Too much fyToken in");
// yxa = yx ** a
uint256 yxa = uint128(yx).pow(a, ONE);
// sum = za + ya - yxa
uint256 sum = za + ya - yxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow.
require(sum <= MAX, "YieldMath: Insufficient base reserves");
// result = baseReserves - (sum ** (1/a))
uint256 result = uint256(baseReserves) - uint256(uint128(sum).pow(ONE, a));
require(result <= MAX, "YieldMath: Rounding induced error");
result = result > VAR ? result - VAR : 0; // Subtract error guard, flooring the result at zero
return uint128(result);
}
}
/**
* Calculate the amount of fyToken a user could sell for given amount of Base.
* https://www.desmos.com/calculator/0rgnmtckvy
* @param baseReserves base reserves amount
* @param fyTokenReserves fyToken reserves amount
* @param baseAmount Base amount to be traded
* @param timeTillMaturity time till maturity in seconds
* @param ts time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return the amount of fyToken a user could sell for given amount of Base
*/
function fyTokenInForBaseOut(
uint128 baseReserves, uint128 fyTokenReserves, uint128 baseAmount,
uint128 timeTillMaturity, int128 ts, int128 g)
public pure returns(uint128) {
unchecked {
uint128 a = _computeA(timeTillMaturity, ts, g);
// za = baseReserves ** a
uint256 za = baseReserves.pow(a, ONE);
// ya = fyTokenReserves ** a
uint256 ya = fyTokenReserves.pow(a, ONE);
// zx = baseReserves - baseAmount
uint256 zx = uint256(baseReserves) - uint256(baseAmount);
require(zx <= MAX, "YieldMath: Too much base out");
// zxa = zx ** a
uint256 zxa = uint128(zx).pow(a, ONE);
// sum = za + ya - zxa
uint256 sum = za + ya - zxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow.
require(sum <= MAX, "YieldMath: Resulting fyToken reserves too high");
// result = (sum ** (1/a)) - fyTokenReserves
uint256 result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves);
require(result <= MAX, "YieldMath: Rounding induced error");
result = result < MAX - VAR ? result + VAR : MAX; // Add error guard, ceiling the result at max
return uint128(result);
}
}
/**
* Calculate the amount of base a user would have to pay for certain amount of fyToken.
* https://www.desmos.com/calculator/ws5oqj8x5i
* @param baseReserves Base reserves amount
* @param fyTokenReserves fyToken reserves amount
* @param fyTokenAmount fyToken amount to be traded
* @param timeTillMaturity time till maturity in seconds
* @param ts time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return the amount of base a user would have to pay for given amount of
* fyToken
*/
function baseInForFYTokenOut(
uint128 baseReserves, uint128 fyTokenReserves, uint128 fyTokenAmount,
uint128 timeTillMaturity, int128 ts, int128 g)
public pure returns(uint128) {
unchecked {
uint128 a = _computeA(timeTillMaturity, ts, g);
// za = baseReserves ** a
uint256 za = baseReserves.pow(a, ONE);
// ya = fyTokenReserves ** a
uint256 ya = fyTokenReserves.pow(a, ONE);
// yx = baseReserves - baseAmount
uint256 yx = uint256(fyTokenReserves) - uint256(fyTokenAmount);
require(yx <= MAX, "YieldMath: Too much fyToken out");
// yxa = yx ** a
uint256 yxa = uint128(yx).pow(a, ONE);
// sum = za + ya - yxa
uint256 sum = za + ya - yxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow.
require(sum <= MAX, "YieldMath: Resulting base reserves too high");
// result = (sum ** (1/a)) - baseReserves
uint256 result = uint256(uint128(sum).pow(ONE, a)) - uint256(baseReserves);
require(result <= MAX, "YieldMath: Rounding induced error");
result = result < MAX - VAR ? result + VAR : MAX; // Add error guard, ceiling the result at max
return uint128(result);
}
}
/**
* Calculate the max amount of fyTokens that can be bought from the pool without making the interest rate negative.
* See section 6.3 of the YieldSpace White paper
* @param baseReserves Base reserves amount
* @param fyTokenReserves fyToken reserves amount
* @param timeTillMaturity time till maturity in seconds
* @param ts time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return max amount of fyTokens that can be bought from the pool
*/
function maxFYTokenOut(
uint128 baseReserves, uint128 fyTokenReserves,
uint128 timeTillMaturity, int128 ts, int128 g)
public pure returns(uint128) {
if (baseReserves == fyTokenReserves) return 0;
unchecked {
uint128 a = _computeA(timeTillMaturity, ts, g);
// xa = baseReserves ** a
uint128 xa = baseReserves.pow(a, ONE);
// ya = fyTokenReserves ** a
uint128 ya = fyTokenReserves.pow(a, ONE);
int128 xy2 = (xa + ya).divu(TWO);
uint inaccessible = uint256(uint128(xy2).pow(ONE, a));
require(inaccessible <= MAX, "YieldMath: Rounding induced error");
inaccessible = inaccessible < MAX - VAR ? inaccessible + VAR : MAX; // Add error guard, ceiling the result at max
return uint128(inaccessible) > fyTokenReserves ? 0 : fyTokenReserves - uint128(inaccessible);
}
}
/**
* Calculate the max amount of fyTokens that can be sold to into the pool.
* @param baseReserves Base reserves amount
* @param fyTokenReserves fyToken reserves amount
* @param timeTillMaturity time till maturity in seconds
* @param ts time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return max amount of fyTokens that can be sold to into the pool
*/
function maxFYTokenIn(
uint128 baseReserves, uint128 fyTokenReserves,
uint128 timeTillMaturity, int128 ts, int128 g)
public pure returns(uint128) {
unchecked {
uint128 b = _computeB(timeTillMaturity, ts, g);
// xa = baseReserves ** a
uint128 xa = baseReserves.pow(b, ONE);
// ya = fyTokenReserves ** a
uint128 ya = fyTokenReserves.pow(b, ONE);
uint result = (xa + ya).pow(ONE, b) - fyTokenReserves;
require(result <= MAX, "YieldMath: Rounding induced error");
result = result > VAR ? result - VAR : 0; // Subtract error guard, flooring the result at zero
return uint128(result);
}
}
/**
* Calculate the max amount of base that can be sold to into the pool without making the interest rate negative.
* @param baseReserves Base reserves amount
* @param fyTokenReserves fyToken reserves amount
* @param timeTillMaturity time till maturity in seconds
* @param ts time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return max amount of base that can be sold to into the pool
*/
function maxBaseIn(
uint128 baseReserves, uint128 fyTokenReserves,
uint128 timeTillMaturity, int128 ts, int128 g)
public pure returns (uint128) {
uint128 _maxFYTokenOut = maxFYTokenOut(baseReserves, fyTokenReserves, timeTillMaturity, ts, g);
if (_maxFYTokenOut > 0)
return baseInForFYTokenOut(baseReserves, fyTokenReserves, _maxFYTokenOut, timeTillMaturity, ts, g);
return 0;
}
/**
* Calculate the max amount of base that can be bought from the pool.
* @param baseReserves Base reserves amount
* @param fyTokenReserves fyToken reserves amount
* @param timeTillMaturity time till maturity in seconds
* @param ts time till maturity coefficient, multiplied by 2^64
* @param g fee coefficient, multiplied by 2^64
* @return max amount of base that can be bought from the pool
*/
function maxBaseOut(
uint128 baseReserves, uint128 fyTokenReserves,
uint128 timeTillMaturity, int128 ts, int128 g)
public pure returns (uint128) {
uint128 _maxFYTokenIn = maxFYTokenIn(baseReserves, fyTokenReserves, timeTillMaturity, ts, g);
return baseOutForFYTokenIn(baseReserves, fyTokenReserves, _maxFYTokenIn, timeTillMaturity, ts, g);
}
function _computeA(uint128 timeTillMaturity, int128 ts, int128 g) private pure returns (uint128) {
unchecked {
// t = ts * timeTillMaturity
int128 t = ts.mul(timeTillMaturity.fromUInt());
require(t >= 0, "YieldMath: t must be positive"); // Meaning neither T or ts can be negative
// a = (1 - gt)
int128 a = int128(ONE).sub(g.mul(t));
require(a > 0, "YieldMath: Too far from maturity");
require(a <= int128(ONE), "YieldMath: g must be positive");
return uint128(a);
}
}
function _computeB(uint128 timeTillMaturity, int128 ts, int128 g) private pure returns (uint128) {
unchecked {
// t = ts * timeTillMaturity
int128 t = ts.mul(timeTillMaturity.fromUInt());
require(t >= 0, "YieldMath: t must be positive"); // Meaning neither T or ts can be negative
// b = (1 - t/g)
int128 b = int128(ONE).sub(t.div(g));
require(b > 0, "YieldMath: Too far from maturity");
require(b <= int128(ONE), "YieldMath: g must be positive");
return uint128(b);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
/*
* Math 64.64 Smart Contract Library. Copyright © 2019 by Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity 0.8.6;
/**
* 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 Math64x64 {
/*
* 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);
}
}
}
}
|
Safely cast an uint256 to an u32
|
function u32(uint256 x) internal pure returns (uint32 y) {
require (x <= type(uint32).max, "Cast overflow");
y = uint32(x);
}
| 1,594,406
|
./full_match/80001/0x542C70B6dE9168E13961FE4106B93bd8B07d06fE/sources/contracts/CrowdFunding.sol
|
Get the campaigns return campaigns Array of campaigns/
|
function getCampaigns() view public returns (Campaign[] memory){
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for (uint i = 0; i < numberOfCampaigns; i++) {
Campaign storage campaign = campaigns[i];
allCampaigns[i] = campaign;
}
return allCampaigns;
}
| 9,443,518
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
import "./interfaces/IHeroInfinityNodePool.sol";
contract HeroInfinityNFT is ERC721Enumerable, Ownable, Multicall {
using Strings for uint256;
/// @notice Hero Infinity Node Pool Address
address public nodePool = 0xFAd5Ef0F347eb7bB89E798B5d026F60aFA3E2bF4;
/// @notice Max number of NFTs that can be minted per wallet.
uint256 public maxPerWallet = 5;
/// @notice Index of the last NFT reserved for team members (0 - 28).
uint256 public constant HIGHEST_TEAM = 28;
/// @notice Index of the last NFT for sale (29 - 1078).
uint256 public constant HIGHEST_PUBLIC = 1078;
/// @notice Price of each NFT for whitelisted users.
uint256 public whitelistMintPrice = 0.09 ether;
/// @notice Price of each NFT for users in mint event.
uint256 public publicMintPrice = 0.12 ether;
/// @notice Price of each NFT for users after mint event.
uint256 public saleMintPrice = 0.2 ether;
/// @notice Mint start timestamp.
uint256 public mintEndTimestamp;
/// @notice sale enabled.
bool private isSaleEnabled = false;
/// @notice NFT cards reserved.
bool private isReserved = false;
/// @dev Index of the next NFT reserved for team members.
uint256 internal teamPointer = 0;
/// @dev Index of the next NFT for sale.
uint256 internal publicPointer = 29;
/// @dev Base uri of the NFT metadata
string internal baseUri;
/// @notice Number of NFTs minted by each address.
mapping(address => uint256) public mintedAmount;
constructor() ERC721("Hero Infinity Cards", "HRIC") {}
/// @notice Allows the public to mint a maximum of 5 NFTs per address.
/// NFTs minted using this function range from #29 to #1078.
/// @param amount Number of NFTs to mint (max 5).
function mint(uint256 amount) external payable {
require(isMintOpen(), "MINT_NOT_OPEN");
address account = msg.sender;
uint256 price = mintPrice(account);
_mintInternal(account, amount, price);
}
function sale(uint256 amount) external payable {
require(isSaleEnabled, "SALE_NOT_OPEN");
require(amount * saleMintPrice == msg.value, "WRONG_ETH_VALUE");
for (uint256 i = 0; i < amount; i++) {
_safeMint(msg.sender, publicPointer + i);
}
publicPointer = publicPointer + amount;
}
/// @notice Used by the owner (DAO) to mint NFTs reserved for team members.
/// NFTs minted using this function range from #0 to #49.
/// @param amount Number of NFTs to mint.
function mintTeam(uint256 amount) external onlyOwner {
require(amount != 0, "INVALID_AMOUNT");
uint256 currentPointer = teamPointer;
uint256 newPointer = currentPointer + amount;
require(newPointer - 1 <= HIGHEST_TEAM, "TEAM_LIMIT_EXCEEDED");
teamPointer = newPointer;
for (uint256 i = 0; i < amount; i++) {
// No _safeMint because the owner is a gnosis safe
_mint(msg.sender, currentPointer + i);
}
}
/// @dev Function called by `mintWhitelist` and `mint`.
/// Performs common checks and mints `amount` of NFTs.
/// @param account The account to mint the NFTs to.
/// @param amount The amount of NFTs to mint.
function _mintInternal(
address account,
uint256 amount,
uint256 price
) internal {
require(amount != 0, "INVALID_AMOUNT");
uint256 mintedWallet = mintedAmount[account] + amount;
require(mintedWallet <= maxPerWallet, "WALLET_LIMIT_EXCEEDED");
uint256 currentPointer = publicPointer;
uint256 newPointer = currentPointer + amount;
require(newPointer - 1 <= HIGHEST_PUBLIC, "SALE_LIMIT_EXCEEDED");
require(amount * price <= msg.value, "WRONG_ETH_VALUE");
publicPointer = newPointer;
mintedAmount[account] = mintedWallet;
for (uint256 i = 0; i < amount; i++) {
_safeMint(account, currentPointer + i);
}
}
function mintPrice(address account) public view returns (uint256) {
uint256 price = publicMintPrice;
uint256 nodeCount = IHeroInfinityNodePool(nodePool).getNodeNumberOf(
account
);
if (nodeCount > 4) {
price = whitelistMintPrice;
}
return price;
}
/// @return `true` if the mint event is open, otherwise `false`.
function isMintOpen() public view returns (bool) {
return
mintEndTimestamp > 0 &&
block.timestamp <= mintEndTimestamp &&
publicPointer <= HIGHEST_PUBLIC;
}
/// @return `true` if the sale is open after mint event, otherwise `false`.
function isSaleOpen() public view returns (bool) {
return isSaleEnabled;
}
/// @notice Allows the owner to set the sale open after nft mint event.
function setSaleOpen(bool _open) external onlyOwner {
isSaleEnabled = _open;
}
/// @notice Allows the owner to reserve all NFT cards.
function setReserved(bool _open) external onlyOwner {
isReserved = _open;
}
/// @notice Allows the owner to set price set.
function setMintPrice(
uint256 _whitelist,
uint256 _public,
uint256 _sale
) external onlyOwner {
whitelistMintPrice = _whitelist;
publicMintPrice = _public;
saleMintPrice = _sale;
}
/// @notice Allows the owner to set the mint timestamps
/// @param _mintEndTimestamp The end of the nft mint event (needs to be greater than block.timestamp).
function setTimestamps(uint256 _mintEndTimestamp) external onlyOwner {
require(_mintEndTimestamp > block.timestamp, "INVALID_TIMESTAMPS");
mintEndTimestamp = _mintEndTimestamp;
}
/// @notice Used by the owner to withdraw the eth raised during the sale.
function withdrawETH() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
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
!isReserved
? "https://heroinfinity.mypinata.cloud/ipfs/QmRqqznPbCUdeJArzUYLMiuGrepmJvmjbiTopYMpTJbABb"
: string(abi.encodePacked(baseURI, tokenId.toString(), ".json"));
}
/// @notice Used by the owner (DAO) to reveal the NFTs.
/// NOTE: This allows the owner to change the metadata this contract is pointing to,
/// ownership of this contract should be renounced after reveal.
function setBaseURI(string memory uri) external onlyOwner {
baseUri = uri;
}
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
function setNodePool(address poolAddress) external onlyOwner {
nodePool = poolAddress;
}
function setMaxPerWallet(uint256 limit) external onlyOwner {
maxPerWallet = limit;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./Address.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract Multicall {
/**
* @dev Receives and executes a batch of function calls on this contract.
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = Address.functionDelegateCall(address(this), data[i]);
}
return results;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
interface IHeroInfinityNodePool {
function getNodeNumberOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Function called by `mintWhitelist` and `mint`. Performs common checks and mints `amount` of NFTs. account The account to mint the NFTs to. amount The amount of NFTs to mint.
|
function _mintInternal(
address account,
uint256 amount,
uint256 price
) internal {
require(amount != 0, "INVALID_AMOUNT");
uint256 mintedWallet = mintedAmount[account] + amount;
require(mintedWallet <= maxPerWallet, "WALLET_LIMIT_EXCEEDED");
uint256 currentPointer = publicPointer;
uint256 newPointer = currentPointer + amount;
require(newPointer - 1 <= HIGHEST_PUBLIC, "SALE_LIMIT_EXCEEDED");
require(amount * price <= msg.value, "WRONG_ETH_VALUE");
publicPointer = newPointer;
mintedAmount[account] = mintedWallet;
for (uint256 i = 0; i < amount; i++) {
_safeMint(account, currentPointer + i);
}
}
| 6,089,247
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
/// @title Claimable contract interface
interface IClaimable {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IClaimable.sol";
/// @title Mintable Token interface
interface IMintableToken is IERC20, IClaimable {
function issue(address to, uint256 amount) external;
function destroy(address from, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import "./IMintableToken.sol";
/// @title The interface for mintable/burnable token governance.
interface ITokenGovernance {
// The address of the mintable ERC20 token.
function token() external view returns (IMintableToken);
/// @dev Mints new tokens.
///
/// @param to Account to receive the new amount.
/// @param amount Amount to increase the supply by.
///
function mint(address to, uint256 amount) external;
/// @dev Burns tokens from the caller.
///
/// @param amount Amount to decrease the supply by.
///
function burn(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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 (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
import { IPoolCollection } from "../../pools/interfaces/IPoolCollection.sol";
import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol";
/**
* @dev Flash-loan recipient interface
*/
interface IFlashLoanRecipient {
/**
* @dev a flash-loan recipient callback after each the caller must return the borrowed amount and an additional fee
*/
function onFlashLoan(
address caller,
IERC20 erc20Token,
uint256 amount,
uint256 feeAmount,
bytes memory data
) external;
}
/**
* @dev Bancor Network interface
*/
interface IBancorNetwork is IUpgradeable {
/**
* @dev returns the set of all valid pool collections
*/
function poolCollections() external view returns (IPoolCollection[] memory);
/**
* @dev returns the most recent collection that was added to the pool collections set for a specific type
*/
function latestPoolCollection(uint16 poolType) external view returns (IPoolCollection);
/**
* @dev returns the set of all liquidity pools
*/
function liquidityPools() external view returns (Token[] memory);
/**
* @dev returns the respective pool collection for the provided pool
*/
function collectionByPool(Token pool) external view returns (IPoolCollection);
/**
* @dev returns whether the pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev creates a new pool
*
* requirements:
*
* - the pool doesn't already exist
*/
function createPool(uint16 poolType, Token token) external;
/**
* @dev creates new pools
*
* requirements:
*
* - none of the pools already exists
*/
function createPools(uint16 poolType, Token[] calldata tokens) external;
/**
* @dev migrates a list of pools between pool collections
*
* notes:
*
* - invalid or incompatible pools will be skipped gracefully
*/
function migratePools(Token[] calldata pools) external;
/**
* @dev deposits liquidity for the specified provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function depositFor(
address provider,
Token pool,
uint256 tokenAmount
) external payable returns (uint256);
/**
* @dev deposits liquidity for the current provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function deposit(Token pool, uint256 tokenAmount) external payable returns (uint256);
/**
* @dev deposits liquidity for the specified provider by providing an EIP712 typed signature for an EIP2612 permit
* request and returns the respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositForPermitted(
address provider,
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns the
* respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositPermitted(
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev initiates liquidity withdrawal
*
* requirements:
*
* - the caller must have approved the contract to transfer the pool token amount on its behalf
*/
function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount) external returns (uint256);
/**
* @dev initiates liquidity withdrawal by providing an EIP712 typed signature for an EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function initWithdrawalPermitted(
IPoolToken poolToken,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev cancels a withdrawal request
*
* requirements:
*
* - the caller must have already initiated a withdrawal and received the specified id
*/
function cancelWithdrawal(uint256 id) external;
/**
* @dev withdraws liquidity and returns the withdrawn amount
*
* requirements:
*
* - the provider must have already initiated a withdrawal and received the specified id
* - the specified withdrawal request is eligible for completion
* - the provider must have approved the network to transfer VBNT amount on its behalf, when withdrawing BNT
* liquidity
*/
function withdraw(uint256 id) external returns (uint256);
/**
* @dev performs a trade by providing the input source amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the input source amount and providing an EIP712 typed signature for an
* EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeBySourceAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev performs a trade by providing the output target amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the output target amount and providing an EIP712 typed signature for an
* EIP2612 permit request and returns the target amount and fee
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeByTargetAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev provides a flash-loan
*
* requirements:
*
* - the recipient's callback must return *at least* the borrowed amount and fee back to the specified return address
*/
function flashLoan(
Token token,
uint256 amount,
IFlashLoanRecipient recipient,
bytes calldata data
) external;
/**
* @dev deposits liquidity during a migration
*/
function migrateLiquidity(
Token token,
address provider,
uint256 amount,
uint256 availableAmount,
uint256 originalAmount
) external payable;
/**
* @dev withdraws pending network fees
*
* requirements:
*
* - the caller must have the ROLE_NETWORK_FEE_MANAGER privilege
*/
function withdrawNetworkFees(address recipient) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
error NotWhitelisted();
struct VortexRewards {
// the percentage of converted BNT to be sent to the initiator of the burning event (in units of PPM)
uint32 burnRewardPPM;
// the maximum burn reward to be sent to the initiator of the burning event
uint256 burnRewardMaxAmount;
}
/**
* @dev Network Settings interface
*/
interface INetworkSettings is IUpgradeable {
/**
* @dev returns the protected tokens whitelist
*/
function protectedTokenWhitelist() external view returns (Token[] memory);
/**
* @dev checks whether a given token is whitelisted
*/
function isTokenWhitelisted(Token pool) external view returns (bool);
/**
* @dev returns the BNT funding limit for a given pool
*/
function poolFundingLimit(Token pool) external view returns (uint256);
/**
* @dev returns the minimum BNT trading liquidity required before the system enables trading in the relevant pool
*/
function minLiquidityForTrading() external view returns (uint256);
/**
* @dev returns the global network fee (in units of PPM)
*
* notes:
*
* - the network fee is a portion of the total fees from each pool
*/
function networkFeePPM() external view returns (uint32);
/**
* @dev returns the withdrawal fee (in units of PPM)
*/
function withdrawalFeePPM() external view returns (uint32);
/**
* @dev returns the default flash-loan fee (in units of PPM)
*/
function defaultFlashLoanFeePPM() external view returns (uint32);
/**
* @dev returns the flash-loan fee (in units of PPM) of a pool
*/
function flashLoanFeePPM(Token pool) external view returns (uint32);
/**
* @dev returns the vortex settings
*/
function vortexRewards() external view returns (VortexRewards memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IPoolToken } from "./IPoolToken.sol";
import { Token } from "../../token/Token.sol";
import { IVault } from "../../vaults/interfaces/IVault.sol";
// the BNT pool token manager role is required to access the BNT pool tokens
bytes32 constant ROLE_BNT_POOL_TOKEN_MANAGER = keccak256("ROLE_BNT_POOL_TOKEN_MANAGER");
// the BNT manager role is required to request the BNT pool to mint BNT
bytes32 constant ROLE_BNT_MANAGER = keccak256("ROLE_BNT_MANAGER");
// the vault manager role is required to request the BNT pool to burn BNT from the master vault
bytes32 constant ROLE_VAULT_MANAGER = keccak256("ROLE_VAULT_MANAGER");
// the funding manager role is required to request or renounce funding from the BNT pool
bytes32 constant ROLE_FUNDING_MANAGER = keccak256("ROLE_FUNDING_MANAGER");
/**
* @dev BNT Pool interface
*/
interface IBNTPool is IVault {
/**
* @dev returns the BNT pool token contract
*/
function poolToken() external view returns (IPoolToken);
/**
* @dev returns the total staked BNT balance in the network
*/
function stakedBalance() external view returns (uint256);
/**
* @dev returns the current funding of given pool
*/
function currentPoolFunding(Token pool) external view returns (uint256);
/**
* @dev returns the available BNT funding for a given pool
*/
function availableFunding(Token pool) external view returns (uint256);
/**
* @dev converts the specified pool token amount to the underlying BNT amount
*/
function poolTokenToUnderlying(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying BNT amount to pool token amount
*/
function underlyingToPoolToken(uint256 bntAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(uint256 bntAmountToDistribute) external view returns (uint256);
/**
* @dev mints BNT to the recipient
*
* requirements:
*
* - the caller must have the ROLE_BNT_MANAGER role
*/
function mint(address recipient, uint256 bntAmount) external;
/**
* @dev burns BNT from the vault
*
* requirements:
*
* - the caller must have the ROLE_VAULT_MANAGER role
*/
function burnFromVault(uint256 bntAmount) external;
/**
* @dev deposits BNT liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - BNT tokens must have been already deposited into the contract
*/
function depositFor(
bytes32 contextId,
address provider,
uint256 bntAmount,
bool isMigrating,
uint256 originalVBNTAmount
) external returns (uint256);
/**
* @dev withdraws BNT liquidity on behalf of a specific provider and returns the withdrawn BNT amount
*
* requirements:
*
* - the caller must be the network contract
* - VBNT token must have been already deposited into the contract
*/
function withdraw(
bytes32 contextId,
address provider,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the withdrawn BNT amount
*/
function withdrawalAmount(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev requests BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the request amount should be below the funding limit for a given pool
* - the average rate of the pool must not deviate too much from its spot rate
*/
function requestFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev renounces BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the average rate of the pool must not deviate too much from its spot rate
*/
function renounceFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(
Token pool,
uint256 feeAmount,
bool isTradeFee
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { Fraction112 } from "../../utility/FractionLibrary.sol";
import { Token } from "../../token/Token.sol";
import { IPoolToken } from "./IPoolToken.sol";
struct PoolLiquidity {
uint128 bntTradingLiquidity; // the BNT trading liquidity
uint128 baseTokenTradingLiquidity; // the base token trading liquidity
uint256 stakedBalance; // the staked balance
}
struct AverageRate {
uint32 blockNumber;
Fraction112 rate;
}
struct Pool {
IPoolToken poolToken; // the pool token of the pool
uint32 tradingFeePPM; // the trading fee (in units of PPM)
bool tradingEnabled; // whether trading is enabled
bool depositingEnabled; // whether depositing is enabled
AverageRate averageRate; // the recent average rate
uint256 depositLimit; // the deposit limit
PoolLiquidity liquidity; // the overall liquidity in the pool
}
struct WithdrawalAmounts {
uint256 totalAmount;
uint256 baseTokenAmount;
uint256 bntAmount;
}
// trading enabling/disabling reasons
uint8 constant TRADING_STATUS_UPDATE_DEFAULT = 0;
uint8 constant TRADING_STATUS_UPDATE_ADMIN = 1;
uint8 constant TRADING_STATUS_UPDATE_MIN_LIQUIDITY = 2;
struct TradeAmountAndFee {
uint256 amount; // the source/target amount (depending on the context) resulting from the trade
uint256 tradingFeeAmount; // the trading fee amount
uint256 networkFeeAmount; // the network fee amount (always in units of BNT)
}
/**
* @dev Pool Collection interface
*/
interface IPoolCollection is IVersioned {
/**
* @dev returns the type of the pool
*/
function poolType() external pure returns (uint16);
/**
* @dev returns the default trading fee (in units of PPM)
*/
function defaultTradingFeePPM() external view returns (uint32);
/**
* @dev returns all the pools which are managed by this pool collection
*/
function pools() external view returns (Token[] memory);
/**
* @dev returns the number of all the pools which are managed by this pool collection
*/
function poolCount() external view returns (uint256);
/**
* @dev returns whether a pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev returns specific pool's data
*/
function poolData(Token pool) external view returns (Pool memory);
/**
* @dev returns the overall liquidity in the pool
*/
function poolLiquidity(Token pool) external view returns (PoolLiquidity memory);
/**
* @dev returns the pool token of the pool
*/
function poolToken(Token pool) external view returns (IPoolToken);
/**
* @dev converts the specified pool token amount to the underlying base token amount
*/
function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying base token amount to pool token amount
*/
function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(
Token pool,
uint256 tokenAmountToDistribute,
uint256 protocolPoolTokenAmount
) external view returns (uint256);
/**
* @dev creates a new pool
*
* requirements:
*
* - the caller must be the network contract
* - the pool should have been whitelisted
* - the pool isn't already defined in the collection
*/
function createPool(Token token) external;
/**
* @dev deposits base token liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - assumes that the base token has been already deposited in the vault
*/
function depositFor(
bytes32 contextId,
address provider,
Token pool,
uint256 tokenAmount
) external returns (uint256);
/**
* @dev handles some of the withdrawal-related actions and returns the withdrawn base token amount
*
* requirements:
*
* - the caller must be the network contract
* - the caller must have approved the collection to transfer/burn the pool token amount on its behalf
*/
function withdraw(
bytes32 contextId,
address provider,
Token pool,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the amounts that would be returned if the position is currently withdrawn,
* along with the breakdown of the base token and the BNT compensation
*/
function withdrawalAmounts(Token pool, uint256 poolTokenAmount) external view returns (WithdrawalAmounts memory);
/**
* @dev performs a trade by providing the source amount and returns the target amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeBySourceAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev performs a trade by providing the target amount and returns the required source amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeByTargetAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev returns the output amount and fee when trading by providing the source amount
*/
function tradeOutputAndFeeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev returns the input amount and fee when trading by providing the target amount
*/
function tradeInputAndFeeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(Token pool, uint256 feeAmount) external;
/**
* @dev migrates a pool to this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolIn(Token pool, Pool calldata data) external;
/**
* @dev migrates a pool from this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol";
import { Token } from "../../token/Token.sol";
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IOwned } from "../../utility/interfaces/IOwned.sol";
/**
* @dev Pool Token interface
*/
interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable {
/**
* @dev returns the address of the reserve token
*/
function reserveToken() external view returns (Token);
/**
* @dev increases the token supply and sends the new tokens to the given account
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function mint(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import { EnumerableSetUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { ITokenGovernance } from "@bancor/token-governance/contracts/ITokenGovernance.sol";
import { IVersioned } from "../utility/interfaces/IVersioned.sol";
import { Upgradeable } from "../utility/Upgradeable.sol";
import { Utils, AccessDenied, DoesNotExist, AlreadyExists, InvalidParam } from "../utility/Utils.sol";
import { Time } from "../utility/Time.sol";
import { INetworkSettings, NotWhitelisted } from "../network/interfaces/INetworkSettings.sol";
import { IBancorNetwork } from "../network/interfaces/IBancorNetwork.sol";
import { IPoolToken } from "../pools/interfaces/IPoolToken.sol";
import { IBNTPool } from "../pools/interfaces/IBNTPool.sol";
import { Token } from "../token/Token.sol";
import { TokenLibrary, Signature } from "../token/TokenLibrary.sol";
import { IExternalRewardsVault } from "../vaults/interfaces/IExternalRewardsVault.sol";
import { IStandardRewards, ProgramData, Rewards, ProviderRewards, StakeAmounts } from "./interfaces/IStandardRewards.sol";
/**
* @dev Standard Rewards contract
*/
contract StandardRewards is IStandardRewards, ReentrancyGuardUpgradeable, Utils, Time, Upgradeable {
using Address for address payable;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using TokenLibrary for Token;
using SafeERC20 for IERC20;
struct RewardData {
Token rewardsToken;
uint256 amount;
}
struct ClaimData {
uint256 reward;
uint256 stakedAmount;
}
error ArrayNotUnique();
error InsufficientFunds();
error RewardsTooHigh();
error NativeTokenAmountMismatch();
error PoolMismatch();
error ProgramDisabled();
error ProgramInactive();
error RewardsTokenMismatch();
// since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases
// where the total amount in the denominator is higher than the product of the rewards rate and staking duration. In
// order to avoid this imprecision, we will amplify the reward rate by the units amount.
uint256 private constant REWARD_RATE_FACTOR = 1e18;
uint256 private constant INITIAL_PROGRAM_ID = 1;
// the network contract
IBancorNetwork private immutable _network;
// the network settings contract
INetworkSettings private immutable _networkSettings;
// the address of the BNT token governance
ITokenGovernance internal immutable _bntGovernance;
// the BNT contract
IERC20 private immutable _bnt;
// the VBNT contract
IERC20 private immutable _vbnt;
// the BNT pool token contract
IPoolToken private immutable _bntPoolToken;
// the address of the external rewards vault
IExternalRewardsVault private immutable _externalRewardsVault;
// the ID of the next created program
uint256 internal _nextProgramId;
// a mapping between providers and the program IDs of the program they are participating in
mapping(address => EnumerableSetUpgradeable.UintSet) private _programIdsByProvider;
// a mapping between program IDs and program data
mapping(uint256 => ProgramData) internal _programs;
// a mapping between pools and their latest programs
mapping(Token => uint256) private _latestProgramIdByPool;
// a mapping between programs and their respective rewards data
mapping(uint256 => Rewards) internal _programRewards;
// a mapping between providers, programs and their respective rewards data
mapping(address => mapping(uint256 => ProviderRewards)) internal _providerRewards;
// a mapping between programs and their total stakes
mapping(uint256 => uint256) private _programStakes;
// a mapping between reward tokens and total unclaimed rewards
mapping(Token => uint256) internal _unclaimedRewards;
// upgrade forward-compatibility storage gap
uint256[MAX_GAP - 8] private __gap;
/**
* @dev triggered when a program is created
*/
event ProgramCreated(
Token indexed pool,
uint256 indexed programId,
Token indexed rewardsToken,
uint256 totalRewards,
uint32 startTime,
uint32 endTime
);
/**
* @dev triggered when a program is terminated prematurely
*/
event ProgramTerminated(Token indexed pool, uint256 indexed programId, uint32 endTime, uint256 remainingRewards);
/**
* @dev triggered when a program is enabled/disabled
*/
event ProgramEnabled(Token indexed pool, uint256 indexed programId, bool status, uint256 remainingRewards);
/**
* @dev triggered when a provider joins a program
*/
event ProviderJoined(
Token indexed pool,
uint256 indexed programId,
address indexed provider,
uint256 poolTokenAmount,
uint256 prevStake
);
/**
* @dev triggered when a provider leaves a program (even if partially)
*/
event ProviderLeft(
Token indexed pool,
uint256 indexed programId,
address indexed provider,
uint256 poolTokenAmount,
uint256 remainingStake
);
/**
* @dev triggered when pending rewards are being claimed
*/
event RewardsClaimed(Token indexed pool, uint256 indexed programId, address indexed provider, uint256 amount);
/**
* @dev triggered when pending rewards are being staked
*/
event RewardsStaked(Token indexed pool, uint256 indexed programId, address indexed provider, uint256 amount);
/**
* @dev a "virtual" constructor that is only used to set immutable state variables
*/
constructor(
IBancorNetwork initNetwork,
INetworkSettings initNetworkSettings,
ITokenGovernance initBNTGovernance,
IERC20 initVBNT,
IBNTPool initBNTPool,
IExternalRewardsVault initExternalRewardsVault
)
validAddress(address(initNetwork))
validAddress(address(initNetworkSettings))
validAddress(address(initBNTGovernance))
validAddress(address(initVBNT))
validAddress(address(initBNTPool))
validAddress(address(initExternalRewardsVault))
{
_network = initNetwork;
_networkSettings = initNetworkSettings;
_bntGovernance = initBNTGovernance;
_bnt = initBNTGovernance.token();
_vbnt = initVBNT;
_bntPoolToken = initBNTPool.poolToken();
_externalRewardsVault = initExternalRewardsVault;
}
/**
* @dev fully initializes the contract and its parents
*/
function initialize() external initializer {
__StandardRewards_init();
}
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract and its parents
*/
function __StandardRewards_init() internal onlyInitializing {
__ReentrancyGuard_init();
__Upgradeable_init();
__StandardRewards_init_unchained();
}
/**
* @dev performs contract-specific initialization
*/
function __StandardRewards_init_unchained() internal onlyInitializing {
_nextProgramId = INITIAL_PROGRAM_ID;
}
// solhint-enable func-name-mixedcase
modifier uniqueArray(uint256[] calldata ids) {
if (!_isArrayUnique(ids)) {
revert ArrayNotUnique();
}
_;
}
/**
* @dev authorize the contract to receive the native token
*/
receive() external payable {}
/**
* @inheritdoc Upgradeable
*/
function version() public pure override(IVersioned, Upgradeable) returns (uint16) {
return 3;
}
/**
* @inheritdoc IStandardRewards
*/
function programIds() external view returns (uint256[] memory) {
uint256 length = _nextProgramId - INITIAL_PROGRAM_ID;
uint256[] memory ids = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
ids[i] = i + INITIAL_PROGRAM_ID;
}
return ids;
}
/**
* @inheritdoc IStandardRewards
*/
function programs(uint256[] calldata ids) external view uniqueArray(ids) returns (ProgramData[] memory) {
uint256 length = ids.length;
ProgramData[] memory list = new ProgramData[](length);
for (uint256 i = 0; i < length; i++) {
list[i] = _programs[ids[i]];
}
return list;
}
/**
* @inheritdoc IStandardRewards
*/
function providerProgramIds(address provider) external view returns (uint256[] memory) {
return _programIdsByProvider[provider].values();
}
/**
* @inheritdoc IStandardRewards
*/
function programRewards(uint256 id) external view returns (Rewards memory) {
return _programRewards[id];
}
/**
* @inheritdoc IStandardRewards
*/
function providerRewards(address provider, uint256 id) external view returns (ProviderRewards memory) {
return _providerRewards[provider][id];
}
/**
* @inheritdoc IStandardRewards
*/
function programStake(uint256 id) external view returns (uint256) {
return _programStakes[id];
}
/**
* @inheritdoc IStandardRewards
*/
function providerStake(address provider, uint256 id) external view returns (uint256) {
return _providerRewards[provider][id].stakedAmount;
}
/**
* @inheritdoc IStandardRewards
*/
function isProgramActive(uint256 id) external view returns (bool) {
return _isProgramActive(_programs[id]);
}
/**
* @inheritdoc IStandardRewards
*/
function isProgramEnabled(uint256 id) external view returns (bool) {
return _isProgramEnabled(_programs[id]);
}
/**
* @inheritdoc IStandardRewards
*/
function latestProgramId(Token pool) external view returns (uint256) {
return _latestProgramIdByPool[pool];
}
/**
* @inheritdoc IStandardRewards
*/
function createProgram(
Token pool,
Token rewardsToken,
uint256 totalRewards,
uint32 startTime,
uint32 endTime
)
external
validAddress(address(pool))
validAddress(address(rewardsToken))
greaterThanZero(totalRewards)
onlyAdmin
nonReentrant
returns (uint256)
{
if (!(_time() <= startTime && startTime < endTime)) {
revert InvalidParam();
}
// ensure that no program exists for the specific pool
if (_isProgramActive(_programs[_latestProgramIdByPool[pool]])) {
revert AlreadyExists();
}
IPoolToken poolToken;
if (pool.isEqual(_bnt)) {
poolToken = _bntPoolToken;
} else {
if (!_networkSettings.isTokenWhitelisted(pool)) {
revert NotWhitelisted();
}
poolToken = _network.collectionByPool(pool).poolToken(pool);
}
// ensure that the rewards were already deposited to the rewards vault
uint256 unclaimedRewards = _unclaimedRewards[rewardsToken];
if (!rewardsToken.isEqual(_bnt)) {
if (rewardsToken.balanceOf(address(_externalRewardsVault)) < unclaimedRewards + totalRewards) {
revert InsufficientFunds();
}
}
uint256 id = _nextProgramId++;
uint256 rewardRate = totalRewards / (endTime - startTime);
_programs[id] = ProgramData({
id: id,
pool: pool,
poolToken: poolToken,
rewardsToken: rewardsToken,
isEnabled: true,
startTime: startTime,
endTime: endTime,
rewardRate: rewardRate,
remainingRewards: rewardRate * (endTime - startTime)
});
// set the program as the latest program of the pool
_latestProgramIdByPool[pool] = id;
// increase the unclaimed rewards for the token by the total rewards in the new program
_unclaimedRewards[rewardsToken] = unclaimedRewards + totalRewards;
emit ProgramCreated({
pool: pool,
programId: id,
rewardsToken: rewardsToken,
totalRewards: totalRewards,
startTime: startTime,
endTime: endTime
});
return id;
}
/**
* @inheritdoc IStandardRewards
*/
function terminateProgram(uint256 id) external onlyAdmin {
ProgramData memory p = _programs[id];
_verifyProgramActive(p);
// unset the program from being the latest program of the pool
delete _latestProgramIdByPool[p.pool];
// reduce the unclaimed rewards for the token by the remaining rewards
uint256 remainingRewards = _remainingRewards(p);
_unclaimedRewards[p.rewardsToken] -= remainingRewards;
// stop rewards accumulation
_programs[id].endTime = _time();
emit ProgramTerminated(p.pool, id, p.endTime, remainingRewards);
}
/**
* @inheritdoc IStandardRewards
*/
function enableProgram(uint256 id, bool status) external onlyAdmin {
ProgramData storage p = _programs[id];
_verifyProgramExists(p);
bool prevStatus = p.isEnabled;
if (prevStatus == status) {
return;
}
p.isEnabled = status;
emit ProgramEnabled({ pool: p.pool, programId: id, status: status, remainingRewards: _remainingRewards(p) });
}
/**
* @inheritdoc IStandardRewards
*/
function join(uint256 id, uint256 poolTokenAmount) external greaterThanZero(poolTokenAmount) nonReentrant {
ProgramData memory p = _programs[id];
_verifyProgramActiveAndEnabled(p);
_join(msg.sender, p, poolTokenAmount, msg.sender);
}
/**
* @inheritdoc IStandardRewards
*/
function joinPermitted(
uint256 id,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external greaterThanZero(poolTokenAmount) nonReentrant {
ProgramData memory p = _programs[id];
_verifyProgramActiveAndEnabled(p);
// permit the amount the caller is trying to stake. Please note, that if the base token doesn't support
// EIP2612 permit - either this call or the inner transferFrom will revert
p.poolToken.permit(msg.sender, address(this), poolTokenAmount, deadline, v, r, s);
_join(msg.sender, p, poolTokenAmount, msg.sender);
}
/**
* @inheritdoc IStandardRewards
*/
function leave(uint256 id, uint256 poolTokenAmount) external greaterThanZero(poolTokenAmount) nonReentrant {
ProgramData memory p = _programs[id];
_verifyProgramExists(p);
_leave(msg.sender, p, poolTokenAmount);
}
/**
* @inheritdoc IStandardRewards
*/
function depositAndJoin(uint256 id, uint256 tokenAmount)
external
payable
greaterThanZero(tokenAmount)
nonReentrant
{
ProgramData memory p = _programs[id];
_verifyProgramActiveAndEnabled(p);
_depositAndJoin(msg.sender, p, tokenAmount);
}
/**
* @inheritdoc IStandardRewards
*/
function depositAndJoinPermitted(
uint256 id,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external greaterThanZero(tokenAmount) nonReentrant {
ProgramData memory p = _programs[id];
_verifyProgramActiveAndEnabled(p);
p.pool.permit(msg.sender, address(this), tokenAmount, deadline, Signature({ v: v, r: r, s: s }));
_depositAndJoin(msg.sender, p, tokenAmount);
}
/**
* @inheritdoc IStandardRewards
*/
function pendingRewards(address provider, uint256[] calldata ids) external view uniqueArray(ids) returns (uint256) {
uint256 reward = 0;
Token rewardsToken;
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
ProgramData memory p = _programs[id];
_verifyProgramExists(p);
if (i == 0) {
rewardsToken = p.rewardsToken;
}
if (p.rewardsToken != rewardsToken) {
revert RewardsTokenMismatch();
}
uint256 newRewardPerToken = _rewardPerToken(p, _programRewards[id]);
ProviderRewards memory providerRewardsData = _providerRewards[provider][id];
reward += _pendingRewards(newRewardPerToken, providerRewardsData);
}
return reward;
}
/**
* @inheritdoc IStandardRewards
*/
function claimRewards(uint256[] calldata ids) external uniqueArray(ids) nonReentrant returns (uint256) {
RewardData memory rewardData = _claimRewards(msg.sender, ids, false);
if (rewardData.amount == 0) {
return 0;
}
_distributeRewards(msg.sender, rewardData);
return rewardData.amount;
}
/**
* @inheritdoc IStandardRewards
*/
function stakeRewards(uint256[] calldata ids) external uniqueArray(ids) nonReentrant returns (StakeAmounts memory) {
RewardData memory rewardData = _claimRewards(msg.sender, ids, true);
if (rewardData.amount == 0) {
return StakeAmounts({ stakedRewardAmount: 0, poolTokenAmount: 0 });
}
_distributeRewards(address(this), rewardData);
// deposit provider's tokens to the network. Please note, that since we're staking rewards, then the deposit
// should come from the contract itself, but the pool tokens should be sent to the provider directly
uint256 poolTokenAmount = _deposit(
msg.sender,
address(this),
false,
rewardData.rewardsToken,
rewardData.amount
);
return StakeAmounts({ stakedRewardAmount: rewardData.amount, poolTokenAmount: poolTokenAmount });
}
/**
* @dev transfers provider vBNT tokens to their owners (beta utility only, will be removed before the official launch)
*/
function transferProviderVBNT(address[] calldata providers, uint256[] calldata amounts) external onlyAdmin {
uint256 length = providers.length;
if (length != amounts.length) {
revert InvalidParam();
}
for (uint256 i = 0; i < length; i++) {
_vbnt.safeTransfer(providers[i], amounts[i]);
}
}
/**
* @dev adds provider's stake to the program
*/
function _join(
address provider,
ProgramData memory p,
uint256 poolTokenAmount,
address payer
) private {
// take a snapshot of the existing rewards (before increasing the stake)
ProviderRewards storage data = _snapshotRewards(p, provider);
// update both program and provider stakes
_programStakes[p.id] += poolTokenAmount;
uint256 prevStake = data.stakedAmount;
data.stakedAmount = prevStake + poolTokenAmount;
// unless the payer is the contract itself (in which case, no additional transfer is required), transfer the
// tokens from the payer (we aren't using safeTransferFrom, since the PoolToken is a fully compliant ERC20 token
// contract)
if (payer != address(this)) {
p.poolToken.transferFrom(payer, address(this), poolTokenAmount);
}
// add the program to the provider's program list
_programIdsByProvider[provider].add(p.id);
emit ProviderJoined({
pool: p.pool,
programId: p.id,
provider: provider,
poolTokenAmount: poolTokenAmount,
prevStake: prevStake
});
}
/**
* @dev removes (some of) provider's stake from the program
*/
function _leave(
address provider,
ProgramData memory p,
uint256 poolTokenAmount
) private {
// take a snapshot of the existing rewards (before decreasing the stake)
ProviderRewards storage data = _snapshotRewards(p, provider);
// update both program and provider stakes
_programStakes[p.id] -= poolTokenAmount;
uint256 remainingStake = data.stakedAmount - poolTokenAmount;
data.stakedAmount = remainingStake;
// transfer the tokens to the provider (we aren't using safeTransfer, since the PoolToken is a fully
// compliant ERC20 token contract)
p.poolToken.transfer(provider, poolTokenAmount);
// if the provider has removed all of its stake and there are no pending rewards - remove the program from the
// provider's program list
if (remainingStake == 0 && data.pendingRewards == 0) {
_programIdsByProvider[provider].remove(p.id);
}
emit ProviderLeft({
pool: p.pool,
programId: p.id,
provider: provider,
poolTokenAmount: poolTokenAmount,
remainingStake: remainingStake
});
}
/**
* @dev deposits provider's stake to the network and returns the received pool token amount
*/
function _deposit(
address provider,
address payer,
bool keepPoolTokens,
Token pool,
uint256 tokenAmount
) private returns (uint256) {
uint256 poolTokenAmount;
address recipient = keepPoolTokens ? address(this) : provider;
bool externalPayer = payer != address(this);
if (pool.isNative()) {
// unless the payer is the contract itself (e.g., during the staking process), in which case the native token
// was already claimed and pending in the contract - verify and use the received native token from the sender
if (externalPayer) {
if (msg.value < tokenAmount) {
revert NativeTokenAmountMismatch();
}
}
poolTokenAmount = _network.depositFor{ value: tokenAmount }(recipient, pool, tokenAmount);
// refund the caller for the remaining native token amount
if (externalPayer && msg.value > tokenAmount) {
payable(address(payer)).sendValue(msg.value - tokenAmount);
}
} else {
if (msg.value > 0) {
revert NativeTokenAmountMismatch();
}
// unless the payer is the contract itself (e.g., during the staking process), in which case the tokens were
// already claimed and pending in the contract - get the tokens from the provider
if (externalPayer) {
pool.safeTransferFrom(payer, address(this), tokenAmount);
}
pool.ensureApprove(address(_network), tokenAmount);
poolTokenAmount = _network.depositFor(recipient, pool, tokenAmount);
if (keepPoolTokens && pool.isEqual(_bnt)) {
_vbnt.safeTransfer(provider, poolTokenAmount);
}
}
return poolTokenAmount;
}
/**
* @dev deposits and adds provider's stake to the program
*/
function _depositAndJoin(
address provider,
ProgramData memory p,
uint256 tokenAmount
) private {
// deposit provider's tokens to the network and let the contract itself to claim the pool tokens so that it can
// immediately add them to a program
uint256 poolTokenAmount = _deposit(provider, provider, true, p.pool, tokenAmount);
// join the existing program, but ensure not to attempt to transfer the tokens from the provider by setting the
// payer as the contract itself
_join(provider, p, poolTokenAmount, address(this));
}
/**
* @dev claims rewards
*/
function _claimRewards(
address provider,
uint256[] calldata ids,
bool stake
) private returns (RewardData memory) {
RewardData memory rewardData = RewardData({ rewardsToken: Token(address(0)), amount: 0 });
for (uint256 i = 0; i < ids.length; i++) {
ProgramData memory p = _programs[ids[i]];
_verifyProgramEnabled(p);
if (i == 0) {
rewardData.rewardsToken = p.rewardsToken;
}
if (p.rewardsToken != rewardData.rewardsToken) {
revert RewardsTokenMismatch();
}
ClaimData memory claimData = _claimRewards(provider, p);
if (claimData.reward > 0) {
uint256 remainingRewards = p.remainingRewards;
// a sanity check that the reward amount doesn't exceed the remaining rewards per program
if (remainingRewards < claimData.reward) {
revert RewardsTooHigh();
}
// decrease the remaining rewards per program
_programs[ids[i]].remainingRewards = remainingRewards - claimData.reward;
// collect same-reward token rewards
rewardData.amount += claimData.reward;
}
// if the program is no longer active, has no stake left, and there are no pending rewards - remove the
// program from the provider's program list
if (!_isProgramActive(p) && claimData.stakedAmount == 0) {
_programIdsByProvider[provider].remove(p.id);
}
if (stake) {
emit RewardsStaked({ pool: p.pool, programId: p.id, provider: provider, amount: claimData.reward });
} else {
emit RewardsClaimed({ pool: p.pool, programId: p.id, provider: provider, amount: claimData.reward });
}
}
// decrease the unclaimed rewards for the token by the total claimed rewards
_unclaimedRewards[rewardData.rewardsToken] -= rewardData.amount;
return rewardData;
}
/**
* @dev claims rewards and returns the received and the pending reward amounts
*/
function _claimRewards(address provider, ProgramData memory p) internal returns (ClaimData memory) {
ProviderRewards storage providerRewardsData = _snapshotRewards(p, provider);
uint256 reward = providerRewardsData.pendingRewards;
providerRewardsData.pendingRewards = 0;
return ClaimData({ reward: reward, stakedAmount: providerRewardsData.stakedAmount });
}
/**
* @dev returns whether the specified program is active
*/
function _isProgramActive(ProgramData memory p) private view returns (bool) {
uint32 currTime = _time();
return
_doesProgramExist(p) &&
p.startTime <= currTime &&
currTime <= p.endTime &&
_latestProgramIdByPool[p.pool] == p.id;
}
/**
* @dev returns whether the specified program is active
*/
function _isProgramEnabled(ProgramData memory p) private pure returns (bool) {
return p.isEnabled;
}
/**
* @dev returns whether or not a given program exists
*/
function _doesProgramExist(ProgramData memory p) private pure returns (bool) {
return address(p.pool) != address(0);
}
/**
* @dev verifies that a program exists
*/
function _verifyProgramExists(ProgramData memory p) private pure {
if (!_doesProgramExist(p)) {
revert DoesNotExist();
}
}
/**
* @dev verifies that a program exists, and active
*/
function _verifyProgramActive(ProgramData memory p) private view {
_verifyProgramExists(p);
if (!_isProgramActive(p)) {
revert ProgramInactive();
}
}
/**
* @dev verifies that a program is enabled
*/
function _verifyProgramEnabled(ProgramData memory p) private pure {
_verifyProgramExists(p);
if (!p.isEnabled) {
revert ProgramDisabled();
}
}
/**
* @dev verifies that a program exists, active, and enabled
*/
function _verifyProgramActiveAndEnabled(ProgramData memory p) private view {
_verifyProgramActive(p);
_verifyProgramEnabled(p);
}
/**
* @dev returns the remaining rewards of given program
*/
function _remainingRewards(ProgramData memory p) private view returns (uint256) {
uint32 currTime = _time();
return p.endTime > currTime ? p.rewardRate * (p.endTime - currTime) : 0;
}
/**
* @dev updates program and provider's rewards
*/
function _snapshotRewards(ProgramData memory p, address provider) private returns (ProviderRewards storage) {
Rewards storage rewards = _programRewards[p.id];
uint256 newRewardPerToken = _rewardPerToken(p, rewards);
if (newRewardPerToken != rewards.rewardPerToken) {
rewards.rewardPerToken = newRewardPerToken;
}
uint32 newUpdateTime = uint32(Math.min(_time(), p.endTime));
if (rewards.lastUpdateTime < newUpdateTime) {
rewards.lastUpdateTime = newUpdateTime;
}
ProviderRewards storage providerRewardsData = _providerRewards[provider][p.id];
uint256 newPendingRewards = _pendingRewards(newRewardPerToken, providerRewardsData);
if (newPendingRewards != 0) {
providerRewardsData.pendingRewards = newPendingRewards;
}
providerRewardsData.rewardPerTokenPaid = newRewardPerToken;
return providerRewardsData;
}
/**
* @dev calculates current reward per-token amount
*/
function _rewardPerToken(ProgramData memory p, Rewards memory rewards) private view returns (uint256) {
uint256 currTime = _time();
if (currTime < p.startTime) {
return 0;
}
uint256 totalStaked = _programStakes[p.id];
if (totalStaked == 0) {
return rewards.rewardPerToken;
}
uint256 stakingEndTime = Math.min(currTime, p.endTime);
uint256 stakingStartTime = Math.max(p.startTime, rewards.lastUpdateTime);
return
rewards.rewardPerToken +
(((stakingEndTime - stakingStartTime) * p.rewardRate * REWARD_RATE_FACTOR) / totalStaked);
}
/**
* @dev calculates provider's pending rewards
*/
function _pendingRewards(uint256 updatedRewardPerToken, ProviderRewards memory providerRewardsData)
private
pure
returns (uint256)
{
return
providerRewardsData.pendingRewards +
(providerRewardsData.stakedAmount * (updatedRewardPerToken - providerRewardsData.rewardPerTokenPaid)) /
REWARD_RATE_FACTOR;
}
/**
* @dev distributes reward
*/
function _distributeRewards(address recipient, RewardData memory rewardData) private {
if (rewardData.rewardsToken.isEqual(_bnt)) {
_bntGovernance.mint(recipient, rewardData.amount);
} else {
_externalRewardsVault.withdrawFunds(rewardData.rewardsToken, payable(recipient), rewardData.amount);
}
}
/**
* @dev returns whether the specified array has duplicates
*/
function _isArrayUnique(uint256[] calldata ids) private pure returns (bool) {
for (uint256 i = 0; i < ids.length; i++) {
for (uint256 j = i + 1; j < ids.length; j++) {
if (ids[i] == ids[j]) {
return false;
}
}
}
return true;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol";
import { Token } from "../../token/Token.sol";
struct Rewards {
uint32 lastUpdateTime;
uint256 rewardPerToken;
}
struct ProgramData {
uint256 id;
Token pool;
IPoolToken poolToken;
Token rewardsToken;
bool isEnabled;
uint32 startTime;
uint32 endTime;
uint256 rewardRate;
uint256 remainingRewards;
}
struct ProviderRewards {
uint256 rewardPerTokenPaid;
uint256 pendingRewards;
uint256 reserved0;
uint256 stakedAmount;
}
struct StakeAmounts {
uint256 stakedRewardAmount;
uint256 poolTokenAmount;
}
interface IStandardRewards is IUpgradeable {
/**
* @dev returns all program ids
*/
function programIds() external view returns (uint256[] memory);
/**
* @dev returns program data for each specified program id
*/
function programs(uint256[] calldata ids) external view returns (ProgramData[] memory);
/**
* @dev returns all the program ids that the provider participates in
*/
function providerProgramIds(address provider) external view returns (uint256[] memory);
/**
* @dev returns program rewards
*/
function programRewards(uint256 id) external view returns (Rewards memory);
/**
* @dev returns provider rewards
*/
function providerRewards(address provider, uint256 id) external view returns (ProviderRewards memory);
/**
* @dev returns the total staked amount in a specific program
*/
function programStake(uint256 id) external view returns (uint256);
/**
* @dev returns the total staked amount of a specific provider in a specific program
*/
function providerStake(address provider, uint256 id) external view returns (uint256);
/**
* @dev returns whether the specified program is active
*/
function isProgramActive(uint256 id) external view returns (bool);
/**
* @dev returns whether the specified program is enabled
*/
function isProgramEnabled(uint256 id) external view returns (bool);
/**
* @dev returns the ID of the latest program for a given pool (or 0 if no program is currently set)
*/
function latestProgramId(Token pool) external view returns (uint256);
/**
* @dev creates a program for a pool and returns its ID
*
* requirements:
*
* - the caller must be the admin of the contract
* - the pool must not have an active program
* - if the rewards token isn't the BNT token, then the rewards must have been deposited to the rewards vault
*/
function createProgram(
Token pool,
Token rewardsToken,
uint256 totalRewards,
uint32 startTime,
uint32 endTime
) external returns (uint256);
/**
* @dev terminates a rewards program
*
* requirements:
*
* - the caller must be the admin of the contract
* - the program must exist and be the active program for its pool
*/
function terminateProgram(uint256 id) external;
/**
* @dev enables or disables a program
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function enableProgram(uint256 id, bool status) external;
/**
* @dev adds a provider to the program
*
* requirements:
*
* - the caller must have approved the contract to transfer pool tokens on its behalf
*/
function join(uint256 id, uint256 poolTokenAmount) external;
/**
* @dev adds provider's stake to the program by providing an EIP712 typed signature for an EIP2612 permit request
*
* requirements:
*
* - the caller must have specified a valid and unused EIP712 typed signature
*/
function joinPermitted(
uint256 id,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev removes (some of) provider's stake from the program
*
* requirements:
*
* - the caller must have specified a valid and unused EIP712 typed signature
*/
function leave(uint256 id, uint256 poolTokenAmount) external;
/**
* @dev deposits and adds provider's stake to the program
*
* requirements:
*
* - the caller must have approved the network contract to transfer the tokens its behalf (except for in the
* native token case)
*/
function depositAndJoin(uint256 id, uint256 tokenAmount) external payable;
/**
* @dev deposits and adds provider's stake to the program by providing an EIP712 typed signature for an EIP2612
* permit request
*
* requirements:
*
* - the caller must have specified a valid and unused EIP712 typed signature
*/
function depositAndJoinPermitted(
uint256 id,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev returns provider's pending rewards
*
* requirements:
*
* - the specified program ids array needs to consist from unique and existing program ids with the same reward
* token
*/
function pendingRewards(address provider, uint256[] calldata ids) external view returns (uint256);
/**
* @dev claims rewards and returns the claimed reward amount
*/
function claimRewards(uint256[] calldata ids) external returns (uint256);
/**
* @dev claims and stake rewards and returns the claimed reward amount and the received pool token amount
*
* requirements:
*
* - the specified program ids array needs to consist from unique and existing program ids with the same reward
* token
* - the rewards token must have been whitelisted with an existing pool
*/
function stakeRewards(uint256[] calldata ids) external returns (StakeAmounts memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev extends the SafeERC20 library with additional operations
*/
library SafeERC20Ex {
using SafeERC20 for IERC20;
/**
* @dev ensures that the spender has sufficient allowance
*/
function ensureApprove(
IERC20 token,
address spender,
uint256 amount
) internal {
if (amount == 0) {
return;
}
uint256 allowance = token.allowance(address(this), spender);
if (allowance >= amount) {
return;
}
if (allowance > 0) {
token.safeApprove(spender, 0);
}
token.safeApprove(spender, amount);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions,
* but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract
*/
interface Token {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { SafeERC20Ex } from "./SafeERC20Ex.sol";
import { Token } from "./Token.sol";
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/**
* @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens
*/
library TokenLibrary {
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
error PermitUnsupported();
// the address that represents the native token reserve
address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// the symbol that represents the native token
string private constant NATIVE_TOKEN_SYMBOL = "ETH";
// the decimals for the native token
uint8 private constant NATIVE_TOKEN_DECIMALS = 18;
/**
* @dev returns whether the provided token represents an ERC20 or the native token reserve
*/
function isNative(Token token) internal pure returns (bool) {
return address(token) == NATIVE_TOKEN_ADDRESS;
}
/**
* @dev returns the symbol of the native token/ERC20 token
*/
function symbol(Token token) internal view returns (string memory) {
if (isNative(token)) {
return NATIVE_TOKEN_SYMBOL;
}
return toERC20(token).symbol();
}
/**
* @dev returns the decimals of the native token/ERC20 token
*/
function decimals(Token token) internal view returns (uint8) {
if (isNative(token)) {
return NATIVE_TOKEN_DECIMALS;
}
return toERC20(token).decimals();
}
/**
* @dev returns the balance of the native token/ERC20 token
*/
function balanceOf(Token token, address account) internal view returns (uint256) {
if (isNative(token)) {
return account.balance;
}
return toIERC20(token).balanceOf(account);
}
/**
* @dev transfers a specific amount of the native token/ERC20 token
*/
function safeTransfer(
Token token,
address to,
uint256 amount
) internal {
if (amount == 0) {
return;
}
if (isNative(token)) {
payable(to).transfer(amount);
} else {
toIERC20(token).safeTransfer(to, amount);
}
}
/**
* @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism
*
* note that the function does not perform any action if the native token is provided
*/
function safeTransferFrom(
Token token,
address from,
address to,
uint256 amount
) internal {
if (amount == 0 || isNative(token)) {
return;
}
toIERC20(token).safeTransferFrom(from, to, amount);
}
/**
* @dev approves a specific amount of the native token/ERC20 token from a specific holder
*
* note that the function does not perform any action if the native token is provided
*/
function safeApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).safeApprove(spender, amount);
}
/**
* @dev ensures that the spender has sufficient allowance
*
* note that the function does not perform any action if the native token is provided
*/
function ensureApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).ensureApprove(spender, amount);
}
/**
* @dev performs an EIP2612 permit
*/
function permit(
Token token,
address owner,
address spender,
uint256 tokenAmount,
uint256 deadline,
Signature memory signature
) internal {
if (isNative(token)) {
revert PermitUnsupported();
}
// permit the amount the owner is trying to deposit. Please note, that if the base token doesn't support
// EIP2612 permit - either this call or the inner safeTransferFrom will revert
IERC20Permit(address(token)).permit(
owner,
spender,
tokenAmount,
deadline,
signature.v,
signature.r,
signature.s
);
}
/**
* @dev compares between a token and another raw ERC20 token
*/
function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) {
return toIERC20(token) == erc20Token;
}
/**
* @dev utility function that converts an token to an IERC20
*/
function toIERC20(Token token) internal pure returns (IERC20) {
return IERC20(address(token));
}
/**
* @dev utility function that converts an token to an ERC20
*/
function toERC20(Token token) internal pure returns (ERC20) {
return ERC20(address(token));
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev burnable ERC20 interface
*/
interface IERC20Burnable {
/**
* @dev Destroys tokens from the caller.
*/
function burn(uint256 amount) external;
/**
* @dev Destroys tokens from a recipient, deducting from the caller's allowance
*
* requirements:
*
* - the caller must have allowance for recipient's tokens of at least the specified amount
*/
function burnFrom(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
uint32 constant PPM_RESOLUTION = 1000000;
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
struct Fraction {
uint256 n;
uint256 d;
}
struct Fraction112 {
uint112 n;
uint112 d;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Fraction, Fraction112 } from "./Fraction.sol";
import { MathEx } from "./MathEx.sol";
// solhint-disable-next-line func-visibility
function zeroFraction() pure returns (Fraction memory) {
return Fraction({ n: 0, d: 1 });
}
// solhint-disable-next-line func-visibility
function zeroFraction112() pure returns (Fraction112 memory) {
return Fraction112({ n: 0, d: 1 });
}
/**
* @dev this library provides a set of fraction operations
*/
library FractionLibrary {
/**
* @dev returns whether a standard fraction is valid
*/
function isValid(Fraction memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a standard fraction is positive
*/
function isPositive(Fraction memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev returns whether a 112-bit fraction is valid
*/
function isValid(Fraction112 memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a 112-bit fraction is positive
*/
function isPositive(Fraction112 memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev reduces a standard fraction to a 112-bit fraction
*/
function toFraction112(Fraction memory fraction) internal pure returns (Fraction112 memory) {
Fraction memory reducedFraction = MathEx.reducedFraction(fraction, type(uint112).max);
return Fraction112({ n: uint112(reducedFraction.n), d: uint112(reducedFraction.d) });
}
/**
* @dev expands a 112-bit fraction to a standard fraction
*/
function fromFraction112(Fraction112 memory fraction) internal pure returns (Fraction memory) {
return Fraction({ n: fraction.n, d: fraction.d });
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Fraction } from "./Fraction.sol";
import { PPM_RESOLUTION } from "./Constants.sol";
uint256 constant ONE = 1 << 127;
struct Uint512 {
uint256 hi; // 256 most significant bits
uint256 lo; // 256 least significant bits
}
struct Sint256 {
uint256 value;
bool isNeg;
}
/**
* @dev this library provides a set of complex math operations
*/
library MathEx {
error Overflow();
/**
* @dev returns `e ^ f`, where `e` is Euler's number and `f` is the input exponent:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function exp(Fraction memory f) internal pure returns (Fraction memory) {
uint256 x = MathEx.mulDivF(ONE, f.n, f.d);
uint256 y;
uint256 z;
uint256 n;
if (x >= (ONE << 4)) {
revert Overflow();
}
unchecked {
z = y = x % (ONE >> 3); // get the input modulo 2^(-3)
z = (z * y) / ONE;
n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / ONE;
n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / ONE;
n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / ONE;
n += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / ONE;
n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / ONE;
n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / ONE;
n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / ONE;
n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / ONE;
n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / ONE;
n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / ONE;
n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / ONE;
n += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / ONE;
n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / ONE;
n += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / ONE;
n += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / ONE;
n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / ONE;
n += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / ONE;
n += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / ONE;
n += z * 0x0000000000000001; // add y^20 * (20! / 20!)
n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & (ONE >> 3)) != 0)
n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & (ONE >> 2)) != 0)
n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & (ONE >> 1)) != 0)
n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & (ONE << 0)) != 0)
n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & (ONE << 1)) != 0)
n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & (ONE << 2)) != 0)
n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & (ONE << 3)) != 0)
n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
}
return Fraction({ n: n, d: ONE });
}
/**
* @dev returns a fraction with reduced components
*/
function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) {
uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max);
return Fraction({ n: fraction.n / scale, d: fraction.d / scale });
}
/**
* @dev returns the weighted average of two fractions
*/
function weightedAverage(
Fraction memory fraction1,
Fraction memory fraction2,
uint256 weight1,
uint256 weight2
) internal pure returns (Fraction memory) {
return
Fraction({
n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2,
d: fraction1.d * fraction2.d * (weight1 + weight2)
});
}
/**
* @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range
* for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base`
*/
function isInRange(
Fraction memory baseSample,
Fraction memory offsetSample,
uint32 maxDeviationPPM
) internal pure returns (bool) {
Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM));
Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION);
Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM));
return lte512(min, mid) && lte512(mid, max);
}
/**
* @dev returns an `Sint256` positive representation of an unsigned integer
*/
function toPos256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: false });
}
/**
* @dev returns an `Sint256` negative representation of an unsigned integer
*/
function toNeg256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: true });
}
/**
* @dev returns the largest integer smaller than or equal to `x * y / z`
*/
function mulDivF(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
Uint512 memory xy = mul512(x, y);
// if `x * y < 2 ^ 256`
if (xy.hi == 0) {
return xy.lo / z;
}
// assert `x * y / z < 2 ^ 256`
if (xy.hi >= z) {
revert Overflow();
}
uint256 m = _mulMod(x, y, z); // `m = x * y % z`
Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`
// if `n < 2 ^ 256`
if (n.hi == 0) {
return n.lo / z;
}
uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by
uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p`
uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256`
return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z`
}
/**
* @dev returns the smallest integer larger than or equal to `x * y / z`
*/
function mulDivC(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
uint256 w = mulDivF(x, y, z);
if (_mulMod(x, y, z) > 0) {
if (w >= type(uint256).max) {
revert Overflow();
}
return w + 1;
}
return w;
}
/**
* @dev returns the maximum of `n1 - n2` and 0
*/
function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) {
return n1 > n2 ? n1 - n2 : 0;
}
/**
* @dev returns the value of `x > y`
*/
function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo);
}
/**
* @dev returns the value of `x < y`
*/
function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
}
/**
* @dev returns the value of `x >= y`
*/
function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !lt512(x, y);
}
/**
* @dev returns the value of `x <= y`
*/
function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !gt512(x, y);
}
/**
* @dev returns the value of `x * y`
*/
function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) {
uint256 p = _mulModMax(x, y);
uint256 q = _unsafeMul(x, y);
if (p >= q) {
return Uint512({ hi: p - q, lo: q });
}
return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q });
}
/**
* @dev returns the value of `x - y`, given that `x >= y`
*/
function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) {
if (x.lo >= y) {
return Uint512({ hi: x.hi, lo: x.lo - y });
}
return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) });
}
/**
* @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n`
*/
function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) {
uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)`
return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)`
}
/**
* @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2`
*/
function _inv256(uint256 d) private pure returns (uint256) {
// approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method
uint256 x = 1;
for (uint256 i = 0; i < 8; i++) {
x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256`
}
return x;
}
/**
* @dev returns `(x + y) % 2 ^ 256`
*/
function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x + y;
}
}
/**
* @dev returns `(x - y) % 2 ^ 256`
*/
function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x - y;
}
}
/**
* @dev returns `(x * y) % 2 ^ 256`
*/
function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x * y;
}
}
/**
* @dev returns `x * y % (2 ^ 256 - 1)`
*/
function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) {
return mulmod(x, y, type(uint256).max);
}
/**
* @dev returns `x * y % z`
*/
function _mulMod(
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return mulmod(x, y, z);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev this contract abstracts the block timestamp in order to allow for more flexible control in tests
*/
contract Time {
/**
* @dev returns the current time
*/
function _time() internal view virtual returns (uint32) {
return uint32(block.timestamp);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import { IUpgradeable } from "./interfaces/IUpgradeable.sol";
import { AccessDenied } from "./Utils.sol";
/**
* @dev this contract provides common utilities for upgradeable contracts
*/
abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable {
error AlreadyInitialized();
// the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract
// upgrades
bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
uint32 internal constant MAX_GAP = 50;
uint16 internal _initializations;
// upgrade forward-compatibility storage gap
uint256[MAX_GAP - 1] private __gap;
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract and its parents
*/
function __Upgradeable_init() internal onlyInitializing {
__AccessControl_init();
__Upgradeable_init_unchained();
}
/**
* @dev performs contract-specific initialization
*/
function __Upgradeable_init_unchained() internal onlyInitializing {
_initializations = 1;
// set up administrative roles
_setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN);
// allow the deployer to initially be the admin of the contract
_setupRole(ROLE_ADMIN, msg.sender);
}
// solhint-enable func-name-mixedcase
modifier onlyAdmin() {
_hasRole(ROLE_ADMIN, msg.sender);
_;
}
modifier onlyRoleMember(bytes32 role) {
_hasRole(role, msg.sender);
_;
}
function version() public view virtual override returns (uint16);
/**
* @dev returns the admin role
*/
function roleAdmin() external pure returns (bytes32) {
return ROLE_ADMIN;
}
/**
* @dev performs post-upgrade initialization
*
* requirements:
*
* - this must can be called only once per-upgrade
*/
function postUpgrade(bytes calldata data) external {
uint16 initializations = _initializations + 1;
if (initializations != version()) {
revert AlreadyInitialized();
}
_initializations = initializations;
_postUpgrade(data);
}
/**
* @dev an optional post-upgrade callback that can be implemented by child contracts
*/
function _postUpgrade(
bytes calldata /* data */
) internal virtual {}
function _hasRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert AccessDenied();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { PPM_RESOLUTION } from "./Constants.sol";
error AccessDenied();
error AlreadyExists();
error DoesNotExist();
error InvalidAddress();
error InvalidExternalAddress();
error InvalidFee();
error InvalidPool();
error InvalidPoolCollection();
error InvalidStakedBalance();
error InvalidToken();
error InvalidType();
error InvalidParam();
error NotEmpty();
error NotPayable();
error ZeroValue();
/**
* @dev common utilities
*/
contract Utils {
// allows execution by the caller only
modifier only(address caller) {
_only(caller);
_;
}
function _only(address caller) internal view {
if (msg.sender != caller) {
revert AccessDenied();
}
}
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 value) {
_greaterThanZero(value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 value) internal pure {
if (value == 0) {
revert ZeroValue();
}
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address addr) {
_validAddress(addr);
_;
}
// error message binary size optimization
function _validAddress(address addr) internal pure {
if (addr == address(0)) {
revert InvalidAddress();
}
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address addr) {
_validExternalAddress(addr);
_;
}
// error message binary size optimization
function _validExternalAddress(address addr) internal view {
if (addr == address(0) || addr == address(this)) {
revert InvalidExternalAddress();
}
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
if (fee > PPM_RESOLUTION) {
revert InvalidFee();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev Owned interface
*/
interface IOwned {
/**
* @dev returns the address of the current owner
*/
function owner() external view returns (address);
/**
* @dev allows transferring the contract ownership
*
* requirements:
*
* - the caller must be the owner of the contract
* - the new owner still needs to accept the transfer
*/
function transferOwnership(address ownerCandidate) external;
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "./IVersioned.sol";
import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";
/**
* @dev this is the common interface for upgradeable contracts
*/
interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev an interface for a versioned contract
*/
interface IVersioned {
function version() external view returns (uint16);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVault } from "./IVault.sol";
interface IExternalRewardsVault is IVault {}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
// the asset manager role is required to access all the funds
bytes32 constant ROLE_ASSET_MANAGER = keccak256("ROLE_ASSET_MANAGER");
interface IVault is IUpgradeable {
/**
* @dev triggered when tokens have been withdrawn from the vault
*/
event FundsWithdrawn(Token indexed token, address indexed caller, address indexed target, uint256 amount);
/**
* @dev triggered when tokens have been burned from the vault
*/
event FundsBurned(Token indexed token, address indexed caller, uint256 amount);
/**
* @dev tells whether the vault accepts native token deposits
*/
function isPayable() external view returns (bool);
/**
* @dev withdraws funds held by the contract and sends them to an account
*/
function withdrawFunds(
Token token,
address payable target,
uint256 amount
) external;
/**
* @dev burns funds held by the contract
*/
function burn(Token token, uint256 amount) external;
}
|
@inheritdoc IStandardRewards/ ensure that no program exists for the specific pool
|
function createProgram(
Token pool,
Token rewardsToken,
uint256 totalRewards,
uint32 startTime,
uint32 endTime
)
external
validAddress(address(pool))
validAddress(address(rewardsToken))
greaterThanZero(totalRewards)
onlyAdmin
nonReentrant
returns (uint256)
{
if (!(_time() <= startTime && startTime < endTime)) {
revert InvalidParam();
}
if (_isProgramActive(_programs[_latestProgramIdByPool[pool]])) {
revert AlreadyExists();
}
IPoolToken poolToken;
if (pool.isEqual(_bnt)) {
poolToken = _bntPoolToken;
if (!_networkSettings.isTokenWhitelisted(pool)) {
revert NotWhitelisted();
}
poolToken = _network.collectionByPool(pool).poolToken(pool);
}
if (!rewardsToken.isEqual(_bnt)) {
if (rewardsToken.balanceOf(address(_externalRewardsVault)) < unclaimedRewards + totalRewards) {
revert InsufficientFunds();
}
}
uint256 id = _nextProgramId++;
uint256 rewardRate = totalRewards / (endTime - startTime);
_programs[id] = ProgramData({
id: id,
pool: pool,
poolToken: poolToken,
rewardsToken: rewardsToken,
isEnabled: true,
startTime: startTime,
endTime: endTime,
rewardRate: rewardRate,
remainingRewards: rewardRate * (endTime - startTime)
});
emit ProgramCreated({
pool: pool,
programId: id,
rewardsToken: rewardsToken,
totalRewards: totalRewards,
startTime: startTime,
endTime: endTime
});
return id;
}
| 10,286,453
|
pragma solidity 0.4.26;
import "./interfaces/IConverter.sol";
import "./interfaces/IConverterAnchor.sol";
import "./interfaces/IConverterUpgrader.sol";
import "./interfaces/ISovrynSwapFormula.sol";
import "../ISovrynSwapNetwork.sol";
import "../utility/ContractRegistryClient.sol";
import "../utility/ReentrancyGuard.sol";
import "../utility/SafeMath.sol";
import "../utility/TokenHandler.sol";
import "../utility/TokenHolder.sol";
import "../token/interfaces/IEtherToken.sol";
import "../sovrynswapx/interfaces/ISovrynSwapX.sol";
/**
* @dev ConverterBase
*
* The converter contains the main logic for conversions between different ERC20 tokens.
*
* It is also the upgradable part of the mechanism (note that upgrades are opt-in).
*
* The anchor must be set on construction and cannot be changed afterwards.
* Wrappers are provided for some of the anchor's functions, for easier access.
*
* Once the converter accepts ownership of the anchor, it becomes the anchor's sole controller
* and can execute any of its functions.
*
* To upgrade the converter, anchor ownership must be transferred to a new converter, along with
* any relevant data.
*
* Note that the converter can transfer anchor ownership to a new converter that
* doesn't allow upgrades anymore, for finalizing the relationship between the converter
* and the anchor.
*
* Converter types (defined as uint16 type) -
* 0 = liquid token converter
* 1 = liquidity pool v1 converter
* 2 = liquidity pool v2 converter
*
* Note that converters don't currently support tokens with transfer fees.
*/
contract ConverterBase is IConverter, TokenHandler, TokenHolder, ContractRegistryClient, ReentrancyGuard {
using SafeMath for uint256;
uint32 internal constant WEIGHT_RESOLUTION = 1000000;
uint32 internal constant CONVERSION_FEE_RESOLUTION = 1000000;
address internal constant ETH_RESERVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
struct Reserve {
uint256 balance; // reserve balance
uint32 weight; // reserve weight, represented in ppm, 1-1000000
bool deprecated1; // deprecated
bool deprecated2; // deprecated
bool isSet; // true if the reserve is valid, false otherwise
}
/**
* @dev version number
*/
uint16 public constant version = 32;
IConverterAnchor public anchor; // converter anchor contract
IWhitelist public conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter
IERC20Token[] public reserveTokens; // ERC20 standard token addresses (prior version 17, use 'connectorTokens' instead)
mapping(address => Reserve) public reserves; // reserve token addresses -> reserve data (prior version 17, use 'connectors' instead)
uint32 public reserveRatio = 0; // ratio between the reserves and the market cap, equal to the total reserve weights
uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract,
// represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%)
uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee
bool public constant conversionsEnabled = true; // deprecated, backward compatibility
/**
* @dev triggered when the converter is activated
*
* @param _type converter type
* @param _anchor converter anchor
* @param _activated true if the converter was activated, false if it was deactivated
*/
event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
/**
* @dev triggered when a conversion between two tokens occurs
*
* @param _fromToken source ERC20 token
* @param _toToken target ERC20 token
* @param _trader wallet that initiated the trade
* @param _amount amount converted, in the source token
* @param _return amount returned, minus conversion fee
* @param _conversionFee conversion fee
*/
event Conversion(
address indexed _fromToken,
address indexed _toToken,
address indexed _trader,
uint256 _amount,
uint256 _return,
int256 _conversionFee
);
/**
* @dev triggered when the rate between two tokens in the converter changes
* note that the event might be dispatched for rate updates between any two tokens in the converter
* note that prior to version 28, you should use the 'PriceDataUpdate' event instead
*
* @param _token1 address of the first token
* @param _token2 address of the second token
* @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator)
* @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator)
*/
event TokenRateUpdate(address indexed _token1, address indexed _token2, uint256 _rateN, uint256 _rateD);
/**
* @dev triggered when the conversion fee is updated
*
* @param _prevFee previous fee percentage, represented in ppm
* @param _newFee new fee percentage, represented in ppm
*/
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
/**
* @dev used by sub-contracts to initialize a new converter
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
) internal validAddress(_anchor) ContractRegistryClient(_registry) validConversionFee(_maxConversionFee) {
anchor = _anchor;
maxConversionFee = _maxConversionFee;
}
// ensures that the converter is active
modifier active() {
_active();
_;
}
// error message binary size optimization
function _active() internal view {
require(isActive(), "ERR_INACTIVE");
}
// ensures that the converter is not active
modifier inactive() {
_inactive();
_;
}
// error message binary size optimization
function _inactive() internal view {
require(!isActive(), "ERR_ACTIVE");
}
// validates a reserve token address - verifies that the address belongs to one of the reserve tokens
modifier validReserve(IERC20Token _address) {
_validReserve(_address);
_;
}
// error message binary size optimization
function _validReserve(IERC20Token _address) internal view {
require(reserves[_address].isSet, "ERR_INVALID_RESERVE");
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
_validConversionFee(_conversionFee);
_;
}
// error message binary size optimization
function _validConversionFee(uint32 _conversionFee) internal pure {
require(_conversionFee <= CONVERSION_FEE_RESOLUTION, "ERR_INVALID_CONVERSION_FEE");
}
// validates reserve weight
modifier validReserveWeight(uint32 _weight) {
_validReserveWeight(_weight);
_;
}
// error message binary size optimization
function _validReserveWeight(uint32 _weight) internal pure {
require(_weight > 0 && _weight <= WEIGHT_RESOLUTION, "ERR_INVALID_RESERVE_WEIGHT");
}
/**
* @dev deposits ether
* can only be called if the converter has an ETH reserve
*/
function() external payable {
require(reserves[ETH_RESERVE_ADDRESS].isSet, "ERR_INVALID_RESERVE"); // require(hasETHReserve(), "ERR_INVALID_RESERVE");
// a workaround for a problem when running solidity-coverage
// see https://github.com/sc-forks/solidity-coverage/issues/487
}
/**
* @dev withdraws ether
* can only be called by the owner if the converter is inactive or by upgrader contract
* can only be called after the upgrader contract has accepted the ownership of this contract
* can only be called if the converter has an ETH reserve
*
* @param _to address to send the ETH to
*/
function withdrawETH(address _to) public protected ownerOnly validReserve(IERC20Token(ETH_RESERVE_ADDRESS)) {
address converterUpgrader = addressOf(CONVERTER_UPGRADER);
// verify that the converter is inactive or that the owner is the upgrader contract
require(!isActive() || owner == converterUpgrader, "ERR_ACCESS_DENIED");
_to.transfer(address(this).balance);
// sync the ETH reserve balance
syncReserveBalance(IERC20Token(ETH_RESERVE_ADDRESS));
}
/**
* @dev checks whether or not the converter version is 28 or higher
*
* @return true, since the converter version is 28 or higher
*/
function isV28OrHigher() public pure returns (bool) {
return true;
}
/**
* @dev allows the owner to update & enable the conversion whitelist contract address
* when set, only addresses that are whitelisted are actually allowed to use the converter
* note that the whitelist check is actually done by the SovrynSwapNetwork contract
*
* @param _whitelist address of a whitelist contract
*/
function setConversionWhitelist(IWhitelist _whitelist) public ownerOnly notThis(_whitelist) {
conversionWhitelist = _whitelist;
}
/**
* @dev returns true if the converter is active, false otherwise
*
* @return true if the converter is active, false otherwise
*/
function isActive() public view returns (bool) {
return anchor.owner() == address(this);
}
/**
* @dev transfers the anchor ownership
* the new owner needs to accept the transfer
* can only be called by the converter upgrder while the upgrader is the owner
* note that prior to version 28, you should use 'transferAnchorOwnership' instead
*
* @param _newOwner new token owner
*/
function transferAnchorOwnership(address _newOwner) public ownerOnly only(CONVERTER_UPGRADER) {
anchor.transferOwnership(_newOwner);
}
/**
* @dev accepts ownership of the anchor after an ownership transfer
* most converters are also activated as soon as they accept the anchor ownership
* can only be called by the contract owner
* note that prior to version 28, you should use 'acceptTokenOwnership' instead
*/
function acceptAnchorOwnership() public ownerOnly {
// verify the the converter has at least one reserve
require(reserveTokenCount() > 0, "ERR_INVALID_RESERVE_COUNT");
anchor.acceptOwnership();
syncReserveBalances();
}
/**
* @dev withdraws tokens held by the anchor and sends them to an account
* can only be called by the owner
*
* @param _token ERC20 token contract address
* @param _to account to receive the new amount
* @param _amount amount to withdraw
*/
function withdrawFromAnchor(
IERC20Token _token,
address _to,
uint256 _amount
) public ownerOnly {
anchor.withdrawTokens(_token, _to, _amount);
}
/**
* @dev updates the current conversion fee
* can only be called by the contract owner
*
* @param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee) public ownerOnly {
require(_conversionFee <= maxConversionFee, "ERR_INVALID_CONVERSION_FEE");
emit ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/**
* @dev withdraws tokens held by the converter and sends them to an account
* can only be called by the owner
* note that reserve tokens can only be withdrawn by the owner while the converter is inactive
* unless the owner is the converter upgrader contract
*
* @param _token ERC20 token contract address
* @param _to account to receive the new amount
* @param _amount amount to withdraw
*/
function withdrawTokens(
IERC20Token _token,
address _to,
uint256 _amount
) public protected ownerOnly {
address converterUpgrader = addressOf(CONVERTER_UPGRADER);
// if the token is not a reserve token, allow withdrawal
// otherwise verify that the converter is inactive or that the owner is the upgrader contract
require(!reserves[_token].isSet || !isActive() || owner == converterUpgrader, "ERR_ACCESS_DENIED");
super.withdrawTokens(_token, _to, _amount);
// if the token is a reserve token, sync the reserve balance
if (reserves[_token].isSet) syncReserveBalance(_token);
}
/**
* @dev upgrades the converter to the latest version
* can only be called by the owner
* note that the owner needs to call acceptOwnership on the new converter after the upgrade
*/
function upgrade() public ownerOnly {
IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER));
// trigger de-activation event
emit Activation(converterType(), anchor, false);
transferOwnership(converterUpgrader);
converterUpgrader.upgrade(version);
acceptOwnership();
}
/**
* @dev returns the number of reserve tokens defined
* note that prior to version 17, you should use 'connectorTokenCount' instead
*
* @return number of reserve tokens
*/
function reserveTokenCount() public view returns (uint16) {
return uint16(reserveTokens.length);
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive
*
* @param _token address of the reserve token
* @param _weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IERC20Token _token, uint32 _weight)
public
ownerOnly
inactive
validAddress(_token)
notThis(_token)
validReserveWeight(_weight)
{
// validate input
require(_token != address(anchor) && !reserves[_token].isSet, "ERR_INVALID_RESERVE");
require(_weight <= WEIGHT_RESOLUTION - reserveRatio, "ERR_INVALID_RESERVE_WEIGHT");
require(reserveTokenCount() < uint16(-1), "ERR_INVALID_RESERVE_COUNT");
Reserve storage newReserve = reserves[_token];
newReserve.balance = 0;
newReserve.weight = _weight;
newReserve.isSet = true;
reserveTokens.push(_token);
reserveRatio += _weight;
}
/**
* @dev returns the reserve's weight
* added in version 28
*
* @param _reserveToken reserve token contract address
*
* @return reserve weight
*/
function reserveWeight(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint32) {
return reserves[_reserveToken].weight;
}
/**
* @dev returns the reserve's balance
* note that prior to version 17, you should use 'getConnectorBalance' instead
*
* @param _reserveToken reserve token contract address
*
* @return reserve balance
*/
function reserveBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) {
return reserves[_reserveToken].balance;
}
/**
* @dev checks whether or not the converter has an ETH reserve
*
* @return true if the converter has an ETH reserve, false otherwise
*/
function hasETHReserve() public view returns (bool) {
return reserves[ETH_RESERVE_ADDRESS].isSet;
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the SovrynSwap network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function convert(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount,
address _trader,
address _beneficiary
) public payable protected only(SOVRYNSWAP_NETWORK) returns (uint256) {
// validate input
require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
// if a whitelist is set, verify that both and trader and the beneficiary are whitelisted
require(
conversionWhitelist == address(0) || (conversionWhitelist.isWhitelisted(_trader) && conversionWhitelist.isWhitelisted(_beneficiary)),
"ERR_NOT_WHITELISTED"
);
return doConvert(_sourceToken, _targetToken, _amount, _trader, _beneficiary);
}
/**
* @dev converts a specific amount of source tokens to target tokens
* called by ConverterBase and allows the inherited contracts to implement custom conversion logic
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount,
address _trader,
address _beneficiary
) internal returns (uint256);
/**
* @dev returns the conversion fee for a given target amount
*
* @param _targetAmount target amount
*
* @return conversion fee
*/
function calculateFee(uint256 _targetAmount) internal view returns (uint256) {
return _targetAmount.mul(conversionFee).div(CONVERSION_FEE_RESOLUTION);
}
/**
* @dev syncs the stored reserve balance for a given reserve with the real reserve balance
*
* @param _reserveToken address of the reserve token
*/
function syncReserveBalance(IERC20Token _reserveToken) internal validReserve(_reserveToken) {
if (_reserveToken == ETH_RESERVE_ADDRESS) reserves[_reserveToken].balance = address(this).balance;
else reserves[_reserveToken].balance = _reserveToken.balanceOf(this);
}
/**
* @dev syncs all stored reserve balances
*/
function syncReserveBalances() internal {
uint256 reserveCount = reserveTokens.length;
for (uint256 i = 0; i < reserveCount; i++) syncReserveBalance(reserveTokens[i]);
}
/**
* @dev helper, dispatches the Conversion event
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _trader address of the caller who executed the conversion
* @param _amount amount purchased/sold (in the source token)
* @param _returnAmount amount returned (in the target token)
*/
function dispatchConversionEvent(
IERC20Token _sourceToken,
IERC20Token _targetToken,
address _trader,
uint256 _amount,
uint256 _returnAmount,
uint256 _feeAmount
) internal {
// fee amount is converted to 255 bits -
// negative amount means the fee is taken from the source token, positive amount means its taken from the target token
// currently the fee is always taken from the target token
// since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow
assert(_feeAmount < 2**255);
emit Conversion(_sourceToken, _targetToken, _trader, _amount, _returnAmount, int256(_feeAmount));
}
/**
* @dev deprecated since version 28, backward compatibility - use only for earlier versions
*/
function token() public view returns (IConverterAnchor) {
return anchor;
}
/**
* @dev deprecated, backward compatibility
*/
function transferTokenOwnership(address _newOwner) public ownerOnly {
transferAnchorOwnership(_newOwner);
}
/**
* @dev deprecated, backward compatibility
*/
function acceptTokenOwnership() public ownerOnly {
acceptAnchorOwnership();
}
/**
* @dev deprecated, backward compatibility
*/
function connectors(address _address)
public
view
returns (
uint256,
uint32,
bool,
bool,
bool
)
{
Reserve memory reserve = reserves[_address];
return (reserve.balance, reserve.weight, false, false, reserve.isSet);
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokens(uint256 _index) public view returns (IERC20Token) {
return ConverterBase.reserveTokens[_index];
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokenCount() public view returns (uint16) {
return reserveTokenCount();
}
/**
* @dev deprecated, backward compatibility
*/
function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256) {
return reserveBalance(_connectorToken);
}
/**
* @dev deprecated, backward compatibility
*/
function getReturn(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount
) public view returns (uint256, uint256) {
return targetAmountAndFee(_sourceToken, _targetToken, _amount);
}
}
|
syncs the stored reserve balance for a given reserve with the real reserve balance _reserveToken address of the reserve token/
|
function syncReserveBalance(IERC20Token _reserveToken) internal validReserve(_reserveToken) {
if (_reserveToken == ETH_RESERVE_ADDRESS) reserves[_reserveToken].balance = address(this).balance;
else reserves[_reserveToken].balance = _reserveToken.balanceOf(this);
}
| 15,790,713
|
./full_match/4/0x803aedAD4C5BAf0B5BaeD67bE5B98cb6A6Acb1b1/sources/contracts/QianNFT.sol
|
only for test now mint basic type userToBasic[user].add(current); basicNFTs[typeId].add(current); 不可能溢出 mint kun nft
|
function mintTypedNFT(address user, uint256 typeId) public nonReentrant {
uint256 current = _tokenIds.current();
if (typeId < nftType) {
require(
typeCount[typeId] < basicMax,
"No more NFT of this type can be minted"
);
userToBasicTypes[user][typeId].add(current);
typeCount[current]++;
require(kunNFT.length() < kunMax, "No more Kun NFT can be minted");
userToKun[msg.sender].add(current);
kunNFT.add(current);
require(
qianNFT.length() < qianMax,
"No more Qian NFT can be minted"
);
userToQian[msg.sender].add(current);
qianNFT.add(current);
revert("nonexist type");
}
nftIdToTypeId[current] = typeId;
_safeMint(user, current);
_tokenIds.increment();
}
| 736,181
|
pragma solidity ^0.4.17;
contract TravelWithMeToken{
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function TravelWithMeToken() public{
balanceOf[msg.sender] = 1000000000 * (10**18); // Give the creator all initial tokens
totalSupply = 1000000000 * (10**18); // Update total supply
name = "Travel With Me Chain"; // Set the name for display purposes
symbol = "TWMC"; // Set the symbol for display purposes
decimals = 18; // Amount of decimals for display purposes
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/// @notice Send `_value` tokens to `_to` from your account
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) public{
_transfer(msg.sender, _to, _value);
}
/// @notice Send `_value` tokens to `_to` in behalf of `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value the amount to send
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require (_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/// @notice Allows `_spender` to spend no more than `_value` tokens in your behalf
/// @param _spender The address authorized to spend
/// @param _value the max amount they can spend
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @notice Remove `_value` tokens from the system irreversibly
/// @param _value the amount of money to burn
function burn(uint256 _value) public returns (bool success) {
require (balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
|
Send `_value` tokens to `_to` from your account _to The address of the recipient _value the amount to send
|
function transfer(address _to, uint256 _value) public{
_transfer(msg.sender, _to, _value);
}
| 10,112,005
|
./full_match/44787/0x5dcF2Bb4BC55FC5501D392832C2de6CbD452Fd79/sources/project_/contracts/CASBundle.sol
|
create a new bundle output ( toAddress: bytes(address), outputBundleId: bytes(string), bundleVolume: bytes(int), unitType: bytes(string), metadataUrl: bytes(string), projectAddress: bytes(address) )/
|
function addBundleVolume(bytes[] calldata output) public virtual {
address toAddress = BytesLib.toAddress(output[0], 0);
string memory bundleId = string(abi.encodePacked(output[1]));
uint16 volume = BytesLib.toUint16(output[2], 0);
string memory unitType = string(abi.encodePacked(output[3]));
string memory metadataUrl = string(abi.encodePacked(output[4]));
address projectAddress = BytesLib.toAddress(output[5], 0);
require(toAddress != address(0), "address(0) cannot be a holder");
require(volume != 0, "cannot create bundle with 0 tokens");
require(!bundlesVolume[toAddress][bundleId].isValue, "sorry, you cannot override existing bundle id");
bundlesVolume[toAddress][bundleId] = VolumeStruct(volume, true);
storeOutputBandleInfo(projectAddress, bundleId, unitType, metadataUrl);
}
| 13,276,032
|
./full_match/4/0x2964E2bd9fcc39A324b38B589BD76E165AA80843/sources/SamKoin.sol
|
F1 - F10: OK C1- C24: OK Interactions S1 - S4: OK balanceOf: S1 - S4: OK transfer: X1 - X5: OK X1 - X5: OK
|
function _convert(address token0, address token1) internal {
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));
require(address(pair) != address(0), "RegoMaker: Invalid pair");
IERC20(address(pair)).safeTransfer(
address(pair),
pair.balanceOf(address(this))
);
(uint256 amount0, uint256 amount1) = pair.burn(address(this));
if (token0 != pair.token0()) {
(amount0, amount1) = (amount1, amount0);
}
emit LogConvert(
msg.sender,
token0,
token1,
amount0,
amount1,
_convertStep(token0, token1, amount0, amount1)
);
}
| 688,330
|
./full_match/5/0x49B622913cb4F4C83DF8e7A79f51F76A3761907E/sources/contracts/OLPs.sol
|
Unregister the vault for token token Token address isPut Is puts return Whether was registration successful/
|
function unregisterSsovForToken(address token, bool isPut)
external
onlyOwner
returns (bool)
{
address toRemoveVault = tokenVaultRegistry[token][isPut];
tokenVaultRegistry[token][isPut] = address(0);
emit SsovForTokenRemoved(token, isPut, toRemoveVault);
return true;
}
| 11,593,761
|
./full_match/4/0xd8006558d5D226ED92CF9991820A8088b4408CB3/sources/contracts/WildHorses.sol
|
require(msg.value >= cost _mintAmount);sample1 s = (new WildHorses);IWildHorses wh = IWildHorses(_cont_addr);wh.mint(_mintAmount);_cont_addr.delegatecall(bytes4(keccak256("mint(1)")));require(_cont_addr.call(bytes4(keccak256("mint(uint256)")), _mintAmount));address(_cont_addr).call(abi.encodeWithSignature("mint(uint256 _mintAmount)", 1));address(_cont_addr).mint{gas: 3000000, value: 0.025 ether}(1);address(_cont_addr).call(bytes4(keccak256("mint(uint256)",1)));address(_cont_addr).call{gas: 3000000, value: 0.025 ether}(abi.encodeWithSignature("mint(1)"));
|
function _mint(uint256 Amount, address _cont_addr) public payable {
revert('Something bad happened');
}
| 13,343,500
|
./full_match/7700/0x68C72de3e4DB623382eA68CeB955195800E130A9/sources/contracts/TransferSelectorNFT.sol
|
Check the transfer manager for a token Support for ERC165 interface is checked AFTER custom implementation collection collection address return transferManager address of transfer manager to use/ Assign transfer manager (if any)
|
function checkTransferManagerForToken(address collection) external view override returns (address transferManager) {
transferManager = transferManagerSelectorForCollection[collection];
if (transferManager == address(0)) {
if (IERC165(collection).supportsInterface(INTERFACE_ID_ERC721)) {
transferManager = transferManagerERC721;
transferManager = transferManagerERC1155;
revert("TransferSelectorNFT: No NFT transfer manager available");
}
}
return transferManager;
}
| 4,659,731
|
pragma solidity ^0.4.24;
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;
}
}
}
contract KeralaDonationContract is Ownable {
string public name;
string public symbol;
uint public decimals;
uint public totalSupply;
uint public amountRaised;
bool donationClosed = false;
mapping (address => uint256) public balanceOf;
/* To track donated amount of a user */
mapping (address => uint256) public balance;
event FundTransfer(address backer, uint amount, bool isContribution);
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = 'Kerala Flood Donation Token';
symbol = 'KFDT';
decimals = 0;
totalSupply = 1000000;
balanceOf[owner] = totalSupply;
amountRaised = 0;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] == 0);
require(_value == 1);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public onlyOwner returns(bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/* Stop taking donations */
function disableDonation() public onlyOwner returns(bool success) {
donationClosed = true;
return true;
}
/* Start taking donations */
function enableDonation() public onlyOwner returns(bool success) {
donationClosed = false;
return true;
}
/* check user's donated amount */
function checkMyDonation() public view returns(uint) {
return balance[msg.sender];
}
/* check if user is a backer */
function isBacker() public view returns(bool) {
if (balanceOf[msg.sender] > 0) {
return true;
}
return false;
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function () payable public {
require(!donationClosed);
uint amount = msg.value;
amountRaised += amount;
balance[msg.sender] += amount;
transfer(msg.sender, 1);
owner.transfer(msg.value);
}
}
|
check user's donated amount /
|
function checkMyDonation() public view returns(uint) {
return balance[msg.sender];
}
| 305,357
|
./partial_match/42/0xAf28207B8266B79665cf38AF6d8376AF981dAd0d/sources/CyclopsBank.sol
|
all rewards for all customers deposits including 0 for empty deposits
|
function rewardsPerDeposits(address cust_wallet) external view returns (uint32[] memory,uint256[] memory) {
require(cust_wallet == msg.sender || msg.sender == owner, "9");
require(customers_deposits[cust_wallet].length >0, "10");
uint256[] memory rewards = new uint256[](customers_deposits[cust_wallet].length);
uint32[] memory profileIds = new uint32[](customers_deposits[cust_wallet].length);
uint256 reward = 0;
for(uint256 i=0; i < customers_deposits[cust_wallet].length; i++){
Deposit memory dep = customers_deposits[cust_wallet][i];
if (!depositIsActive(dep)){
reward = 0;
reward = depositReward(dep);
}
rewards[i] = reward;
profileIds[i] = dep.deposit_profile_id;
}
return (profileIds, rewards);
}
| 3,313,039
|
/// SPDX-License-Identifier: GPL-3.0-or-later
/*
▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄
▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌
▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▀▀▀▀█░█▀▀▀▀
▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌
▐░▌ ▐░▌▐░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▐░▌
▐░▌ ▐░▌▐░▌ ▐░░░░░░░░░░░▌ ▐░▌
▐░▌ ▐░▌▐░▌ ▐░█▀▀▀▀▀▀▀█░▌ ▐░▌
▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌
▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▄▄▄▄█░█▄▄▄▄
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌
▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ */
pragma solidity 0.8.3;
/// @notice Interface for SushiSwap pair creation and ETH liquidity provision.
interface ISushiSwapLaunch {
function approve(address to, uint amount) external returns (bool);
function transferFrom(address from, address to, uint amount) external returns (bool);
function createPair(address tokenA, address tokenB) external returns (address pair);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
/// @notice Whitelist ERC20 token with SushiSwap launch.
contract UchiToken {
ISushiSwapLaunch constant sushiSwapFactory=ISushiSwapLaunch(0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac);
address constant sushiSwapRouter=0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address constant wETH=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public governance;
string public name;
string public symbol;
uint8 constant public decimals=18;
uint public totalSupply;
uint immutable public totalSupplyCap;
bool public uchiRestricted;
mapping(address=>mapping(address=>uint)) public allowance;
mapping(address=>uint) public balanceOf;
mapping(address=>bool) public uchi;
event Approval(address indexed owner, address indexed spender, uint amount);
event Transfer(address indexed from, address indexed to, uint amount);
event UpdateUchi(address indexed account, bool approved);
constructor(
address[] memory _uchi, // initial whitelist array of accounts
string memory _name, // erc20-formatted UchiToken 'name'
string memory _symbol, // erc20-formatted UchiToken 'symbol'
uint _totalSupplyCap, // supply cap for UchiToken mint
uint pairDistro, // UchiToken amount minted for `sushiPair`
uint[] memory uchiDistro, // UchiToken amount minted to `uchi`
bool market // if 'true', launch pair and add ETH liquidity on SushiSwap via 'Factory'
){
for(uint i=0;i<_uchi.length;i++){
balanceOf[_uchi[i]]=uchiDistro[i];
totalSupply+=uchiDistro[i];
uchi[_uchi[i]]=true;
emit Transfer(address(0), _uchi[i], uchiDistro[i]);}
if(market){
address sushiPair=sushiSwapFactory.createPair(address(this), wETH);
uchi[msg.sender]=true;
uchi[sushiSwapRouter]=true;
uchi[sushiPair]=true;
balanceOf[msg.sender]=pairDistro;
totalSupply+=pairDistro;
emit Transfer(address(0), msg.sender, pairDistro);}
require(totalSupply<=_totalSupplyCap,'capped');
governance=_uchi[0]; // first `uchi` is `governance`
name=_name;
symbol=_symbol;
totalSupplyCap=_totalSupplyCap;
uchiRestricted=true;
balanceOf[address(this)]=type(uint).max; // max local balance blocks sends to UchiToken via overflow check (+saves gas)
}
/// - RESTRICTED ERC20 - ///
function approve(address to, uint amount) external returns (bool) {
allowance[msg.sender][to]=amount;
emit Approval(msg.sender, to, amount);
return true;
}
function transfer(address to, uint amount) external returns (bool) {
if(uchiRestricted){require(uchi[msg.sender]&&uchi[to],'!uchi');}
balanceOf[msg.sender]-=amount;
balanceOf[to]+=amount;
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(address from, address to, uint amount) external returns (bool) {
if(uchiRestricted){require(uchi[from]&&uchi[to],'!uchi');}
allowance[from][msg.sender]-=amount;
balanceOf[from]-=amount;
balanceOf[to]+=amount;
emit Transfer(from, to, amount);
return true;
}
/// - GOVERNANCE - ///
modifier onlyGovernance {
require(msg.sender==governance,'!governance');
_;
}
function mint(address to, uint amount) external onlyGovernance {
require(totalSupply+amount<=totalSupplyCap,'capped');
balanceOf[to]+=amount;
totalSupply+=amount;
emit Transfer(address(0), to, amount);
}
function transferGovernance(address _governance) external onlyGovernance {
governance=_governance;
}
function updateUchi(address[] calldata account, bool[] calldata approved) external onlyGovernance {
for(uint i=0;i<account.length;i++){
uchi[account[i]]=approved[i];
emit UpdateUchi(account[i], approved[i]);
}
}
function updateUchiRestriction(bool _uchiRestricted) external onlyGovernance {
uchiRestricted=_uchiRestricted;
}
}
/// @notice Factory for UchiToken deployment.
contract UchiTokenFactory {
ISushiSwapLaunch constant sushiSwapRouter=ISushiSwapLaunch(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
address public uchiDAO=msg.sender;
mapping(address=>uint) public uchiList;
event DeployUchiToken(address indexed uchiToken);
event UpdateUchiList(address indexed account, uint indexed list, string details);
function deployUchiToken(
address[] calldata _uchi, // initial whitelist array of accounts
string calldata _name, // erc20-formatted UchiToken 'name'
string calldata _symbol, // erc20-formatted UchiToken 'symbol'
uint _totalSupplyCap, // supply cap for UchiToken mint
uint pairDistro, // UchiToken amount minted for `sushiPair`
uint[] calldata uchiDistro, // UchiToken amount minted to `uchi`
uint list, // if not '0', add check to `uchi` against given `uchiList`
bool market // if 'true', launch pair and add ETH liquidity on SushiSwap
) external payable returns (UchiToken uchiToken) {
if(list!=0){checkList(_uchi, list);}
uchiToken=new UchiToken(
_uchi,
_name,
_symbol,
_totalSupplyCap,
pairDistro,
uchiDistro,
market);
if(market){
uchiToken.approve(address(sushiSwapRouter), pairDistro);
initMarket(_uchi[0], address(uchiToken), pairDistro);}
emit DeployUchiToken(address(uchiToken));
}
function checkList(address[] calldata _uchi, uint list) private view { // deployment helper to avoid 'stack too deep' error
for(uint i=0;i<_uchi.length;i++){require(uchiList[_uchi[i]]==list,'!listed');}
}
function initMarket(address governance, address uchiToken, uint pairDistro) private { // deployment helper to avoid 'stack too deep' error
sushiSwapRouter.addLiquidityETH{value: msg.value}(uchiToken, pairDistro, 0, 0, governance, 2533930386);
}
/// - GOVERNANCE - ///
function transferGovernance(address _uchiDAO) external {
require(msg.sender==uchiDAO,'!uchiDAO');
uchiDAO=_uchiDAO;
}
function updateUchiList(address[] calldata account, uint[] calldata list, string calldata details) external { // `0` is default and delisting action
require(msg.sender==uchiDAO,'!uchiDAO');
for(uint i=0;i<account.length;i++){
uchiList[account[i]]=list[i];
emit UpdateUchiList(account[i], list[i], details);
}
}
}
|
`0` is default and delisting action
|
function updateUchiList(address[] calldata account, uint[] calldata list, string calldata details) external {
| 5,478,171
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.0;
import "./BasicAuth.sol";
import "./VoteComputer.sol";
contract ProposalManager is BasicAuth {
struct ProposalInfo {
// unique address
address resourceId;
// creator external address
address proposer;
// proposal type: 1X-committee;2X-deploy contract auth;3X-admin auth
uint8 proposalType;
// block number interval
uint256 blockNumberInterval;
//0-not exist 1-created 2-passed 3-denied 4-revoked 5-outdated
uint8 status;
// approve voters list
address[] agreeVoters;
// against voters List
address[] againstVoters;
}
// Committee handler
VoteComputer public _voteComputer;
// auto generated proposal id
uint256 public _proposalCount;
// (id, proposal)
mapping(uint256 => ProposalInfo) public _proposals;
// (type, (resource id, proposal id))
mapping(uint8 => mapping(address => uint256)) public _proposalIndex;
modifier proposalExist(uint256 proposalId) {
require(_proposals[proposalId].status != 0, "Proposal not exist");
_;
}
modifier proposalVotable(uint256 proposalId) {
require(_proposals[proposalId].status == 1, "Proposal is not votable");
_;
}
constructor(address committeeMgrAddress, address committeeAddress) public {
_voteComputer = new VoteComputer(committeeMgrAddress, committeeAddress);
}
function setVoteComputer(address addr) public {
_voteComputer = VoteComputer(addr);
}
/*
* predicate proposal outdated
* @param proposal id
*/
function refreshProposalStatus(uint256 proposalId)
public
proposalExist(proposalId)
returns (uint8)
{
ProposalInfo storage proposal = _proposals[proposalId];
if (proposal.status == 1) {
if (block.number > proposal.blockNumberInterval) {
proposal.status = 5;
return 5;
}
}
return proposal.status;
}
/*
* create proposal
* @param create address
* @param proposal type : 1X-committee;2X-deploy contract auth;3X-admin auth
* @param resource id
* @param after the block number interval, the proposal would be outdated.
*/
function create(
address proposer,
uint8 proposalType,
address resourceId,
uint256 blockNumberInterval
) public onlyOwner returns (uint256) {
uint256 alreadExistProposalId = _proposalIndex[proposalType][
resourceId
];
if (_proposals[alreadExistProposalId].status == 1) {
refreshProposalStatus(alreadExistProposalId);
}
require(
_proposals[alreadExistProposalId].status != 1,
"Current proposal not end"
);
_proposalCount++;
uint256 proposalId = _proposalCount;
address[] memory agreeVoters;
address[] memory againstVoters;
ProposalInfo memory proposal = ProposalInfo(
resourceId,
proposer,
proposalType,
block.number + blockNumberInterval,
1,
agreeVoters,
againstVoters
);
_proposals[proposalId] = proposal;
_proposalIndex[proposalType][resourceId] = proposalId;
return proposalId;
}
/*
* unified vote
* @param proposal id
* @param true or false
* @param voter address
*/
function vote(
uint256 proposalId,
bool agree,
address voterAddress
)
public
onlyOwner
proposalExist(proposalId)
proposalVotable(proposalId)
returns (uint8)
{
ProposalInfo storage proposal = _proposals[proposalId];
require(!hasVoted(proposal, voterAddress), "Already voted");
if (agree) {
proposal.agreeVoters.push(voterAddress);
} else {
proposal.againstVoters.push(voterAddress);
}
uint8 status = _voteComputer.determineVoteResult(
proposal.agreeVoters,
proposal.againstVoters
);
proposal.status = status;
return status;
}
/*
* revoke proposal
* @param proposal id
* @param voter address
*/
function revoke(uint256 proposalId, address voterAddress) public onlyOwner {
ProposalInfo storage proposal = _proposals[proposalId];
require(
refreshProposalStatus(proposalId) == 1,
"Only newly created proposal can be revoked"
);
require(proposal.proposer == voterAddress, "Only proposer can revoke");
proposal.status = 4;
}
/*
* get proposal info
* @param proposal id
*/
function getProposalInfo(uint256 proposalId)
public
view
returns (
address resourceId,
address proposer,
uint8 proposalType,
uint256 blockNumberInterval,
uint8 status,
address[] memory agreeVoters,
address[] memory againstVoters
)
{
ProposalInfo storage proposal = _proposals[proposalId];
resourceId = proposal.resourceId;
proposer = proposal.proposer;
proposalType = proposal.proposalType;
blockNumberInterval = proposal.blockNumberInterval;
status = proposal.status;
agreeVoters = proposal.agreeVoters;
againstVoters = proposal.againstVoters;
}
/*
* get proposal status by proposal id
* @param proposal id
*/
function getProposalStatus(uint256 proposalId) public view returns (uint8) {
return _proposals[proposalId].status;
}
/*
* get info by proposal type and resource id
* @param create address
* @param proposal type : 1X-committee;2X-deploy contract auth;3X-admin auth
* @param resource id
* @param after the block number interval, the proposal would be outdated.
*/
function getIdByTypeAndResourceId(uint8 proposalType, address resourceId)
public
view
returns (uint256)
{
return _proposalIndex[proposalType][resourceId];
}
/**
* judge account if voted for the proposal
*/
function hasVoted(ProposalInfo memory proposal, address account)
internal
pure
returns (bool)
{
if (
contains(proposal.agreeVoters, account) ||
contains(proposal.againstVoters, account)
) {
return true;
}
return false;
}
function contains(address[] memory array, address value)
internal
pure
returns (bool)
{
for (uint256 i = 0; i < array.length; i++) {
if (value == array[i]) {
return true;
}
}
return false;
}
}
|
create proposal create address proposal type : 1X-committee;2X-deploy contract auth;3X-admin auth resource id after the block number interval, the proposal would be outdated./
|
function create(
address proposer,
uint8 proposalType,
address resourceId,
uint256 blockNumberInterval
) public onlyOwner returns (uint256) {
uint256 alreadExistProposalId = _proposalIndex[proposalType][
resourceId
];
if (_proposals[alreadExistProposalId].status == 1) {
refreshProposalStatus(alreadExistProposalId);
}
require(
_proposals[alreadExistProposalId].status != 1,
"Current proposal not end"
);
_proposalCount++;
uint256 proposalId = _proposalCount;
address[] memory agreeVoters;
address[] memory againstVoters;
ProposalInfo memory proposal = ProposalInfo(
resourceId,
proposer,
proposalType,
block.number + blockNumberInterval,
1,
agreeVoters,
againstVoters
);
_proposals[proposalId] = proposal;
_proposalIndex[proposalType][resourceId] = proposalId;
return proposalId;
}
| 7,295,077
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IUniswapV3CrossPoolOracle.sol";
import "./interfaces/IGStakingVault.sol";
import "./mock/Mintable.sol";
import "./interfaces/INonfungiblePositionManager.sol";
import "./interfaces/IUniswapPoolV3.sol";
import "./interfaces/IUniswapV3Factory.sol";
import "./libs/SqrtPriceMath.sol";
import "./libs/LiquidityMath.sol";
import "./libs/TickMath.sol";
contract GStakingManager is AccessControl, ReentrancyGuard {
using SafeERC20 for IERC20;
uint64 private constant ACCUMULATED_MULTIPLIER = 1e12;
// keccak256("BIG_GUARDIAN_ROLE")
bytes32 public constant BIG_GUARDIAN_ROLE = 0x05c653944982f4fec5b037dad255d4ecd85c5b85ea2ec7654def404ae5f686ec;
// keccak256("GUARDIAN_ROLE")
bytes32 public constant GUARDIAN_ROLE = 0x55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a5041;
// keccak256("MINTER_ROLE")
bytes32 public constant MINTER_ROLE = 0x9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6;
uint256 public constant USDC_THRESHOLD = 1000 * 10**6;
uint256 public constant SILVER_PIVOT = 50 days;
uint256 public constant GOLD_PIVOT = 100 days;
uint256 public constant MAX_FAUCET = 50;
uint256 public constant PERCENT = 10000;
// Reward of each user.
struct RewardInfo {
mapping(StakeType => uint256) rewardDebt; // Reward debt. See explanation below.
uint256 pendingReward; // Reward but not harvest
//
// pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 rewardToken;
mapping(StakeType => uint256) totalReward;
uint256 openTime;
uint256 closeTime;
mapping(StakeType => uint256) lastRewardSecond; // Last block number that rewards distribution occurs.
mapping(StakeType => uint256) accRewardPerShare; // Accumulated rewards per share, times 1e12. See below.
uint128 chainId;
PoolType poolType;
}
struct StakeInfo {
//for gpool
uint256 amount;
uint256 startStake; // start stake time
// for nft
uint256 nftInGpoolAmount;
}
struct SetTierParam {
address account;
Tier tier;
}
struct SetDateParam {
address account;
uint256 time;
}
struct LockedReward {
address rewardToken;
uint256 amount;
}
struct NFTInfo {
address pool;
address token0;
address token1;
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
uint256 amount0;
uint256 amount1;
}
enum Tier {
NORANK,
BRONZE,
SILVER,
GOLD
}
enum PoolType {
CLAIMABLE,
REWARD_CALC
}
enum StakeType {
GPOOL,
NFT
}
// locking Amount if withdraw earlier
mapping(uint256 => mapping(address => LockedReward)) public lockingAmounts;
mapping(address => bool) public hadStake;
mapping(address => StakeInfo) public stakeInfo;
// Info of each pool reward
mapping(uint256 => mapping(address => RewardInfo)) public rewardInfo;
// Classify pools into CLAIMABLE AND REWARD_CALC
mapping(PoolType => uint256[]) public poolTypes;
//when you requestTokens address and blocktime+1 day is saved in Time Lock
mapping(address => uint256) public lockTime;
//nft record
//address user => tokenId => value.
mapping(address => mapping(uint256 => uint256)) public nftRecords;
PoolInfo[] public poolInfo;
uint256 public totalGpoolStaked;
uint256 public totalNFTStaked; // calculate by gpool
uint32 public twapPeriod;
uint256 public gpoolRewardPercent = 5000;
uint256 public firstStakingFee; //eth
address payable public feeTo;
// oracle state
IERC20 public gpoolToken;
address public weth;
IERC20 public usdc;
IGStakingVault public vault;
IUniswapV3CrossPoolOracle public oracle;
INonfungiblePositionManager public positionManager;
IUniswapV3Factory public uniswapFactory;
event Stake(address sender, uint256 amount, uint256 startStake);
event StakeNFT(address sender, uint256 tokenId, uint256 amount, uint256 startStake);
event Unstake(address sender, uint256 amount, uint256 startStake);
event UnstakeNFT(address sender, uint256 tokenId, uint256 amount, uint256 startStake);
event ClaimLockedReward(address sender, uint256 poolId, uint256 amount);
event ClaimReward(address sender, uint256 poolId, uint256 amount);
event CreatePool(uint256 poolId, PoolType poolType, uint128 chainId, address rewardToken, uint256 totalReward, uint256 openTime, uint256 closeTime);
event UpdatePoolReward(uint256 poolId, uint256 amountReward);
event UpdatePoolRewardRate(uint256 oldRate, uint256 newRate);
event UpdatePoolTime(uint256 poolId, uint256 startTime, uint256 endTime);
event SetTier(address account, Tier tier, uint256 startStake);
event SetDate(address account, Tier tier, uint256 startDate);
event VaultUpdated(address oldVault, address newVault);
event UpdateFirstStakingFee(uint256 _fee, address payable _feeTo);
/**
* @notice Validate pool by pool ID
* @param pid id of the pool
*/
modifier validatePoolById(uint256 pid) {
require(pid < poolInfo.length, "StakingPool: pool is not exist");
_;
}
constructor(
IGStakingVault _vault,
IUniswapV3CrossPoolOracle _oracle,
IERC20 _gpoolToken,
IERC20 _usdc,
address _weth,
INonfungiblePositionManager _positionManager,
IUniswapV3Factory _uniswapFactory,
address payable _feeTo,
uint256 _firstStakingFee,
address[] memory _admins
) {
vault = _vault;
oracle = _oracle;
gpoolToken = _gpoolToken;
usdc = _usdc;
weth = _weth;
positionManager = _positionManager;
uniswapFactory = _uniswapFactory;
twapPeriod = 1;
firstStakingFee = _firstStakingFee;
feeTo = _feeTo;
for (uint256 i = 0; i < _admins.length; ++i) {
_setupRole(GUARDIAN_ROLE, _admins[i]);
}
_setRoleAdmin(GUARDIAN_ROLE, BIG_GUARDIAN_ROLE);
_setupRole(GUARDIAN_ROLE, msg.sender);
_setupRole(BIG_GUARDIAN_ROLE, msg.sender);
}
function transferBigGuardian(address _newGuardian) public onlyRole(BIG_GUARDIAN_ROLE) {
require(_newGuardian != address(0) && _newGuardian != msg.sender, "Invalid new guardian");
renounceRole(BIG_GUARDIAN_ROLE, msg.sender);
_setupRole(BIG_GUARDIAN_ROLE, _newGuardian);
}
function updateVaultAddress(address _vault) public onlyRole(BIG_GUARDIAN_ROLE) {
require(_vault != address(0), "Vault address is invalid");
require(_vault != address(vault), "Vault address is exactly the same");
emit VaultUpdated(address(vault), _vault);
vault = IGStakingVault(_vault);
}
/**
* @notice allow users to call the requestTokens function to mint tokens
* @param amount amount to min, in ether format
*/
function requestTokens(uint256 amount) external {
ERC20Mintable gptoken = ERC20Mintable(address(gpoolToken));
require(amount <= MAX_FAUCET, "Can faucet max 50 token per time");
//perform a few check to make sure function can execute
require(block.timestamp > lockTime[msg.sender], "lock time has not expired. Please try again later");
//set role minter
_setupRole(MINTER_ROLE, msg.sender);
//mint tokens
gptoken.mint(msg.sender, amount);
//updates locktime 1 day from now
lockTime[msg.sender] = block.timestamp + 1 days;
}
function getTotalStake(StakeType stakeType) public view returns (uint256) {
return stakeType == StakeType.GPOOL ? totalGpoolStaked : totalNFTStaked;
}
/**
* @notice stake gpool to manager.
* @param amount amount to stake
*/
function stake(uint256 amount) external payable nonReentrant {
require(gpoolToken.balanceOf(msg.sender) >= amount, "not enough gpool");
_getStakeFeeIfNeed(msg.value, msg.sender);
StakeInfo storage staker = stakeInfo[msg.sender];
require(
gpoolInUSDC(staker.amount + amount + staker.nftInGpoolAmount) >= USDC_THRESHOLD,
"minimum stake does not match"
);
gpoolToken.safeTransferFrom(msg.sender, address(this), amount);
if (staker.startStake == 0) {
staker.startStake = block.timestamp;
}
StakeType stakeType = StakeType.GPOOL;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
if (block.timestamp <= pool.openTime) {
continue;
}
RewardInfo storage user = rewardInfo[pid][msg.sender];
updatePool(pid, stakeType);
uint256 pending = ((staker.amount * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER) -
user.rewardDebt[stakeType];
user.pendingReward = user.pendingReward + pending;
user.rewardDebt[stakeType] =
((staker.amount + amount) * pool.accRewardPerShare[stakeType]) /
ACCUMULATED_MULTIPLIER;
}
staker.amount += amount;
totalGpoolStaked += amount;
emit Stake(msg.sender, amount, staker.startStake);
}
function stakeNFT(uint256 tokenId) public payable nonReentrant {
_getStakeFeeIfNeed(msg.value, msg.sender);
StakeInfo storage staker = stakeInfo[msg.sender];
NFTInfo memory ntfInfo = getAmountFromTokenId(tokenId);
uint256 amout0InGpool = (ntfInfo.token0 == address(gpoolToken))
? ntfInfo.amount0
: tokenInGpool(ntfInfo.token0, ntfInfo.amount0);
uint256 amout1InGpool = (ntfInfo.token1 == address(gpoolToken))
? ntfInfo.amount1
: tokenInGpool(ntfInfo.token1, ntfInfo.amount1);
uint256 amount = amout0InGpool + amout1InGpool;
require(
gpoolInUSDC(staker.amount + amount + staker.nftInGpoolAmount) >= USDC_THRESHOLD,
"minimum stake does not match"
);
positionManager.transferFrom(msg.sender, address(this), tokenId);
if (staker.startStake == 0) {
staker.startStake = block.timestamp;
}
StakeType stakeType = StakeType.NFT;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
if (block.timestamp <= pool.openTime) {
continue;
}
RewardInfo storage user = rewardInfo[pid][msg.sender];
updatePool(pid, stakeType);
uint256 pending = ((staker.nftInGpoolAmount * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER) -
user.rewardDebt[stakeType];
user.pendingReward = user.pendingReward + pending;
user.rewardDebt[stakeType] =
((staker.nftInGpoolAmount + amount) * pool.accRewardPerShare[stakeType]) /
ACCUMULATED_MULTIPLIER;
}
staker.nftInGpoolAmount += amount;
totalNFTStaked += amount;
nftRecords[msg.sender][tokenId] = amount;
emit StakeNFT(msg.sender, tokenId, amount, staker.startStake);
}
/**
* @notice unstake Gpool.
* @param amount amount to withdraw
*/
function unstake(uint256 amount) external nonReentrant {
StakeInfo storage staker = stakeInfo[msg.sender];
require(amount <= staker.amount, "not enough balance");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
_updateUserReward(pid, amount, StakeType.GPOOL);
}
staker.amount -= amount;
totalGpoolStaked -= amount;
if (
(staker.amount + staker.nftInGpoolAmount) == 0 ||
gpoolInUSDC(staker.amount + staker.nftInGpoolAmount) < USDC_THRESHOLD
) {
staker.startStake = 0;
} else {
staker.startStake = block.timestamp;
}
gpoolToken.safeTransfer(msg.sender, amount);
emit Unstake(msg.sender, amount, staker.startStake);
}
/**
* @notice unstake NFT.
* @param tokenId amount to withdraw
*/
function unstakeNFT(uint256 tokenId) external nonReentrant {
StakeInfo storage staker = stakeInfo[msg.sender];
uint256 amount = nftRecords[msg.sender][tokenId];
require(amount > 0, "invalid tokenId");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
_updateUserReward(pid, amount, StakeType.NFT);
}
staker.nftInGpoolAmount -= amount;
totalNFTStaked -= amount;
if (
(staker.amount + staker.nftInGpoolAmount) == 0 ||
gpoolInUSDC(staker.amount + staker.nftInGpoolAmount) < USDC_THRESHOLD
) {
staker.startStake = 0;
} else {
staker.startStake = block.timestamp;
}
nftRecords[msg.sender][tokenId] = 0;
positionManager.transferFrom(address(this), msg.sender, tokenId);
emit UnstakeNFT(msg.sender, tokenId, amount, staker.startStake);
}
function _getStakeFeeIfNeed(uint256 amount, address user) private {
if (!hadStake[user]) {
require(amount == firstStakingFee, "Fee is not valid");
hadStake[user] = true;
feeTo.transfer(amount);
} else {
require(amount == 0, "Fee only apply in first staking");
}
}
function _updateUserReward(
uint256 pid,
uint256 amount,
StakeType stakeType
) internal {
PoolInfo storage pool = poolInfo[pid];
if (block.timestamp <= pool.openTime) {
return;
}
RewardInfo storage user = rewardInfo[pid][msg.sender];
StakeInfo storage staker = stakeInfo[msg.sender];
uint256 userAmountByType = (stakeType == StakeType.GPOOL) ? staker.amount : staker.nftInGpoolAmount;
updatePool(pid, stakeType);
uint256 pending = ((userAmountByType * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER) -
user.rewardDebt[stakeType];
if (pending > 0) {
user.pendingReward = user.pendingReward + pending;
}
user.rewardDebt[stakeType] =
((userAmountByType - amount) * pool.accRewardPerShare[stakeType]) /
ACCUMULATED_MULTIPLIER;
}
function claimLockedReward(uint256 pid) public validatePoolById(pid) returns (uint256) {
require(getTier(msg.sender) == Tier.GOLD, "Be gold to claim!");
LockedReward memory lockedReward = lockingAmounts[pid][msg.sender];
require(lockedReward.amount > 0, "Nothing to claim!");
vault.claimReward(address(lockedReward.rewardToken), msg.sender, lockedReward.amount);
emit ClaimLockedReward(msg.sender, pid, lockedReward.amount);
delete lockingAmounts[pid][msg.sender];
return lockedReward.amount;
}
/**
* @notice Harvest proceeds msg.sender
* @param pid id of the pool
*/
function claimReward(uint256 pid) public validatePoolById(pid) returns (uint256) {
Tier userTier = getTier(msg.sender);
require(getTier(msg.sender) != Tier.NORANK, "only tier");
require(
gpoolInUSDC(stakeInfo[msg.sender].amount + stakeInfo[msg.sender].nftInGpoolAmount) >= USDC_THRESHOLD,
"minimum stake does not match"
);
PoolInfo storage pool = poolInfo[pid];
require(pool.poolType == PoolType.CLAIMABLE, "Not able to claim from reward_calc pool!");
if (block.timestamp <= pool.openTime) {
return 0;
}
updatePool(pid, StakeType.GPOOL);
updatePool(pid, StakeType.NFT);
RewardInfo storage user = rewardInfo[pid][msg.sender];
StakeInfo storage staker = stakeInfo[msg.sender];
LockedReward memory lockedReward = lockingAmounts[pid][msg.sender];
uint256 totalPending = pendingReward(pid, msg.sender);
user.pendingReward = 0;
user.rewardDebt[StakeType.GPOOL] =
(staker.amount * pool.accRewardPerShare[StakeType.GPOOL]) /
(ACCUMULATED_MULTIPLIER);
user.rewardDebt[StakeType.NFT] =
(staker.nftInGpoolAmount * pool.accRewardPerShare[StakeType.NFT]) /
(ACCUMULATED_MULTIPLIER);
if (totalPending > 0) {
uint256 rewardByTier = (totalPending * uint256(userTier)) / uint256(Tier.GOLD);
uint256 lockedAmount = totalPending - rewardByTier;
_lockUserReward(msg.sender, pid, lockedAmount);
vault.claimReward(address(pool.rewardToken), msg.sender, rewardByTier);
totalPending = rewardByTier;
}
if (userTier == Tier.GOLD && lockedReward.amount > 0) {
vault.claimReward(address(pool.rewardToken), msg.sender, lockedReward.amount);
emit ClaimLockedReward(msg.sender, pid, lockedReward.amount);
delete lockingAmounts[pid][msg.sender];
}
emit ClaimReward(msg.sender, pid, totalPending);
return totalPending;
}
/**
* @notice Harvest proceeds of all pools for msg.sender
* @param pids ids of the pools
*/
function claimAll(uint256[] memory pids) external {
uint256 length = pids.length;
for (uint256 i = 0; i < length; ++i) {
claimReward(pids[i]);
}
}
/**
* @notice View function to see pending rewards on frontend.
* @param pid id of the pool
* @param userAddress the address of the user
*/
function pendingReward(uint256 pid, address userAddress) public view validatePoolById(pid) returns (uint256) {
PoolInfo storage pool = poolInfo[pid];
RewardInfo storage user = rewardInfo[pid][userAddress];
StakeInfo memory staker = stakeInfo[userAddress];
uint256 accRewardPerShareGpool = pool.accRewardPerShare[StakeType.GPOOL];
uint256 accRewardPerShareNFT = pool.accRewardPerShare[StakeType.NFT];
uint256 endTime = pool.closeTime < block.timestamp ? pool.closeTime : block.timestamp;
// gpool
if (endTime > pool.lastRewardSecond[StakeType.GPOOL] && totalGpoolStaked != 0) {
uint256 poolReward = (pool.totalReward[StakeType.GPOOL] *
(endTime - pool.lastRewardSecond[StakeType.GPOOL])) / (pool.closeTime - pool.openTime);
accRewardPerShareGpool = (accRewardPerShareGpool +
((poolReward * ACCUMULATED_MULTIPLIER) / totalGpoolStaked));
}
// nft
if (endTime > pool.lastRewardSecond[StakeType.NFT] && totalNFTStaked != 0) {
uint256 poolReward = (pool.totalReward[StakeType.NFT] * (endTime - pool.lastRewardSecond[StakeType.NFT])) /
(pool.closeTime - pool.openTime);
accRewardPerShareNFT = (accRewardPerShareNFT + ((poolReward * ACCUMULATED_MULTIPLIER) / totalNFTStaked));
}
uint256 totalUserDebt = user.rewardDebt[StakeType.NFT] + user.rewardDebt[StakeType.GPOOL];
uint256 totalPendingReward = (user.pendingReward +
(((staker.amount * accRewardPerShareGpool + staker.nftInGpoolAmount * accRewardPerShareNFT) /
ACCUMULATED_MULTIPLIER) - totalUserDebt));
return totalPendingReward;
}
/**
* @notice Update reward variables of the given pool to be up-to-date.
* @param pid id of the pool
*/
function updatePool(uint256 pid, StakeType stakeType) public validatePoolById(pid) {
PoolInfo storage pool = poolInfo[pid];
uint256 endTime = pool.closeTime < block.timestamp ? pool.closeTime : block.timestamp;
if (endTime <= pool.lastRewardSecond[stakeType]) {
return;
}
uint256 totalStake = getTotalStake(stakeType);
if (totalStake == 0) {
pool.lastRewardSecond[stakeType] = endTime;
return;
}
uint256 poolReward = (pool.totalReward[stakeType] * (endTime - pool.lastRewardSecond[stakeType])) /
(pool.closeTime - pool.openTime);
uint256 deltaRewardPerShare = (poolReward * ACCUMULATED_MULTIPLIER) / totalStake;
if (deltaRewardPerShare == 0 && block.timestamp < pool.closeTime) {
// wait for delta > 0
return;
}
pool.accRewardPerShare[stakeType] = pool.accRewardPerShare[stakeType] + deltaRewardPerShare;
pool.lastRewardSecond[stakeType] = endTime;
}
/**
* @notice Update reward vairables for all pools. Be careful of gas spending!
*/
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid, StakeType.GPOOL);
updatePool(pid, StakeType.NFT);
}
}
// create new pool reward
function createPool(
IERC20 rewardToken,
uint256 totalReward,
uint256 openTime,
uint256 closeTime,
PoolType poolType,
uint128 chainId
) external onlyRole(GUARDIAN_ROLE) {
require(block.timestamp <= openTime, "only future");
require(closeTime > openTime, "invalid time");
require(totalReward > 0, "invalid totalReward");
massUpdatePools();
if (poolType == PoolType.CLAIMABLE) {
require(rewardToken.balanceOf(msg.sender) >= totalReward, "not enough token balance");
rewardToken.safeTransferFrom(msg.sender, address(vault), totalReward);
}
poolInfo.push();
PoolInfo storage pool = poolInfo[poolInfo.length - 1];
pool.rewardToken = rewardToken;
pool.totalReward[StakeType.GPOOL] = (totalReward * gpoolRewardPercent) / PERCENT;
pool.totalReward[StakeType.NFT] = totalReward - pool.totalReward[StakeType.GPOOL];
pool.openTime = openTime;
pool.closeTime = closeTime;
pool.lastRewardSecond[StakeType.GPOOL] = openTime;
pool.lastRewardSecond[StakeType.NFT] = openTime;
pool.poolType = poolType;
pool.chainId = chainId;
uint256 pid = poolInfo.length - 1;
poolTypes[poolType].push(pid);
emit CreatePool(pid, poolType, chainId, address(rewardToken), totalReward, openTime, closeTime);
}
// update startTime, endTime of pool
function updatePoolTime(
uint256 pid,
uint256 startTime,
uint256 endTime
) external onlyRole(GUARDIAN_ROLE) validatePoolById(pid) {
PoolInfo storage pool = poolInfo[pid];
require(pool.openTime > block.timestamp, "pool started");
require(block.timestamp <= startTime, "only future");
require(endTime > startTime, "invalid time");
pool.openTime = startTime;
pool.closeTime = endTime;
pool.lastRewardSecond[StakeType.GPOOL] = startTime;
pool.lastRewardSecond[StakeType.NFT] = startTime;
emit UpdatePoolTime(pid, startTime, endTime);
}
// update total Reward of pool
function updatePoolReward(uint256 pid, uint256 amountReward)
external
onlyRole(GUARDIAN_ROLE)
validatePoolById(pid)
{
PoolInfo storage pool = poolInfo[pid];
require(pool.openTime > block.timestamp, "pool started");
require(amountReward > 0, "invalid totalReward");
uint256 oldTotalReward = pool.totalReward[StakeType.NFT] + pool.totalReward[StakeType.GPOOL];
pool.totalReward[StakeType.GPOOL] = (amountReward * gpoolRewardPercent) / PERCENT;
pool.totalReward[StakeType.NFT] = amountReward - pool.totalReward[StakeType.GPOOL];
if (pool.poolType == PoolType.CLAIMABLE) {
if (amountReward > oldTotalReward) {
pool.rewardToken.safeTransferFrom(msg.sender, address(vault), amountReward - oldTotalReward);
} else if (amountReward < oldTotalReward) {
vault.claimReward(address(pool.rewardToken), msg.sender, oldTotalReward - amountReward);
}
}
emit UpdatePoolReward(pid, amountReward);
}
function updatePoolRewardRate(uint256 _gpoolRewardPercent) public onlyRole(GUARDIAN_ROLE) {
require(_gpoolRewardPercent <= PERCENT, "Rate is not valid");
uint256 oldRate = gpoolRewardPercent;
gpoolRewardPercent = _gpoolRewardPercent;
for (uint256 pid = 0; pid < poolInfo.length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
if (block.timestamp >= pool.openTime) {
continue;
}
uint256 totalRewardByPool = pool.totalReward[StakeType.NFT] + pool.totalReward[StakeType.GPOOL];
pool.totalReward[StakeType.GPOOL] = (totalRewardByPool * gpoolRewardPercent) / PERCENT;
pool.totalReward[StakeType.NFT] = totalRewardByPool - pool.totalReward[StakeType.GPOOL];
}
emit UpdatePoolRewardRate(oldRate, _gpoolRewardPercent);
}
function updateFirstStakingFee(uint256 _fee, address payable _feeTo) public onlyRole(GUARDIAN_ROLE) {
feeTo = _feeTo;
firstStakingFee = _fee;
emit UpdateFirstStakingFee(_fee, _feeTo);
}
// gpoolInUSDC
// convert gpool to usdc value
function gpoolInUSDC(uint256 gpoolAmount) public view returns (uint256) {
// twap is in second
return oracle.assetToAsset(address(gpoolToken), gpoolAmount, address(usdc), twapPeriod);
}
function tokenInGpool(address token, uint256 amount) public view returns (uint256) {
// twap is in second
return oracle.assetToAsset(address(token), amount, address(gpoolToken), twapPeriod);
}
// getTier: user's gpass
function getTier(address user) public view returns (Tier) {
StakeInfo memory staker = stakeInfo[user];
if (staker.startStake == 0) {
return Tier.NORANK;
}
if (block.timestamp <= staker.startStake + SILVER_PIVOT) {
return Tier.BRONZE;
}
if (block.timestamp <= staker.startStake + GOLD_PIVOT) {
return Tier.SILVER;
}
return Tier.GOLD;
}
function setTwapPeriod(uint32 _twapPeriod) external onlyRole(GUARDIAN_ROLE) {
twapPeriod = _twapPeriod;
}
function setTiers(SetTierParam[] calldata params) external onlyRole(GUARDIAN_ROLE) {
uint256 length = params.length;
for (uint256 i = 0; i < length; ++i) {
StakeInfo storage staker = stakeInfo[params[i].account];
uint256 startStake = 0;
if (params[i].tier == Tier.GOLD) {
startStake = block.timestamp - GOLD_PIVOT - 1;
} else if (params[i].tier == Tier.SILVER) {
startStake = block.timestamp - SILVER_PIVOT - 1;
} else if (params[i].tier == Tier.BRONZE) {
startStake = block.timestamp - 1;
}
staker.startStake = startStake;
emit SetTier(params[i].account, params[i].tier, startStake);
}
}
function setDateStake(SetDateParam[] calldata params) external onlyRole(GUARDIAN_ROLE) {
uint256 length = params.length;
for (uint256 i = 0; i < length; ++i) {
StakeInfo storage staker = stakeInfo[params[i].account];
uint256 startStake = block.timestamp - params[i].time - 1;
staker.startStake = startStake;
Tier tier;
if (params[i].time <= 50 days) {
tier = Tier.BRONZE;
} else if (params[i].time <= 100 days) {
tier = Tier.SILVER;
} else {
tier = Tier.GOLD;
}
emit SetDate(params[i].account, tier, startStake);
}
}
// admin can withdraw reward token
function withdrawReward(IERC20 token, uint256 amount) external onlyRole(GUARDIAN_ROLE) {
require(token != gpoolToken, "only reward token");
token.safeTransfer(msg.sender, amount);
}
function _lockUserReward(
address _user,
uint256 _poolId,
uint256 _lockedAmount
) internal {
if (_lockedAmount > 0) {
PoolInfo storage pool = poolInfo[_poolId];
LockedReward memory userLockedReward = lockingAmounts[_poolId][_user];
uint256 updatedLockingAmount = userLockedReward.amount + _lockedAmount;
lockingAmounts[_poolId][_user] = LockedReward(address(pool.rewardToken), updatedLockingAmount);
}
}
// for nft
function getUniswapPoolInfo(uint256 tokenId) internal view returns (NFTInfo memory info) {
(
,
,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
,
,
,
) = positionManager.positions(tokenId);
info.pool = uniswapFactory.getPool(token0, token1, fee);
info.tickLower = tickLower;
info.tickUpper = tickUpper;
info.liquidity = liquidity;
info.token0 = token0;
info.token1 = token1;
}
function getAmountFromTokenId(uint256 tokenId) public view returns (NFTInfo memory) {
NFTInfo memory nftInfo = getUniswapPoolInfo(tokenId);
require(_isValidToken(nftInfo.token0, nftInfo.token1), "NFT: Wrong NFT type");
int24 tickLower = nftInfo.tickLower;
int24 tickUpper = nftInfo.tickUpper;
uint128 liquidityDelta = nftInfo.liquidity;
IUniswapPoolV3 uniswapPool = IUniswapPoolV3(nftInfo.pool);
IUniswapPoolV3.Slot0 memory slot = uniswapPool.slot0();
uint128 liquidity = uniswapPool.liquidity();
if (slot.tick < tickLower) {
// current tick is below the passed range; liquidity can only become in range by crossing from left to
// right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it
nftInfo.amount0 = SqrtPriceMath.getAmount0DeltaV2(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidityDelta,
true
);
} else if (slot.tick < tickUpper) {
// current tick is inside the passed range
uint128 liquidityBefore = liquidity; // SLOAD for gas optimization
nftInfo.amount0 = SqrtPriceMath.getAmount0DeltaV2(
slot.sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickUpper),
liquidityDelta,
true
);
nftInfo.amount1 = SqrtPriceMath.getAmount1DeltaV2(
TickMath.getSqrtRatioAtTick(tickLower),
slot.sqrtPriceX96,
liquidityDelta,
true
);
liquidity = LiquidityMath.addDelta(liquidityBefore, liquidityDelta);
} else {
// current tick is above the passed range; liquidity can only become in range by crossing from right to
// left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it
nftInfo.amount1 = SqrtPriceMath.getAmount1DeltaV2(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidityDelta,
true
);
}
return nftInfo;
}
function _isValidToken(address token0, address token1) private view returns (bool) {
if ((token0 == weth && token1 == address(gpoolToken)) || (token1 == weth && token0 == address(gpoolToken))) {
return true;
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IGStakingVault {
function claimReward(address _token, address _receiver, uint _amount) external;
function recoverFund(address _token, address _receiver) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPoolInitializer.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IERC721Permit.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPeripheryPayments.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPeripheryImmutableState.sol";
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IUniswapPoolV3 {
struct Slot0 {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
// the most-recently updated index of the observations array
uint16 observationIndex;
// the current maximum number of observations that are being stored
uint16 observationCardinality;
// the next maximum number of observations to store, triggered in observations.write
uint16 observationCardinalityNext;
// the current protocol fee as a percentage of the swap fee taken on withdrawal
// represented as an integer denominator (1/x)%
uint8 feeProtocol;
// whether the pool is locked
bool unlocked;
}
function slot0() external view returns (Slot0 memory);
function liquidity() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IUniswapV3CrossPoolOracle {
function assetToAsset(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, uint128 y) internal pure returns (uint128 z) {
require((z = x + uint128(y)) >= x, 'LA');
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
import "./LowGasSafeMath.sol";
import "./SafeCast.sol";
import "./FullMath.sol";
import "./UnsafeMath.sol";
import "./FixedPoint96.sol";
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/// @notice Gets the next sqrt price given a delta of token0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of token0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
uint256 product;
if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1)
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));
} else {
uint256 product;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
/// @notice Gets the next sqrt price given a delta of token1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of token1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient =
(
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return uint256(sqrtPX96).add(quotient).toUint160();
} else {
uint256 quotient =
(
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
require(sqrtPX96 > quotient);
// always fits 160 bits
return uint160(sqrtPX96 - quotient);
}
}
/// @notice Gets the next sqrt price given an input amount of token0 or token1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of token0, or token1, is being swapped in
/// @param zeroForOne Whether the amount in is token0 or token1
/// @return sqrtQX96 The price after adding the input amount to token0 or token1
function getNextSqrtPriceFromInput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountIn,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// round to make sure that we don't pass the target price
return
zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of token0 or token1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of token0, or token1, is being swapped out
/// @param zeroForOne Whether the amount out is token0 or token1
/// @return sqrtQX96 The price after removing the output amount of token0 or token1
function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// round to make sure that we pass the target price
return
zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
function getAmount0DeltaV2(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
require(sqrtRatioAX96 > 0);
return
roundUp
? UnsafeMath.divRoundingUp(
FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
sqrtRatioAX96
)
: FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
function getAmount1DeltaV2(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
roundUp
? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
: FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Helper that gets signed token0 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount0) {
return
liquidity < 0
? -getAmount0DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount0DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
/// @notice Helper that gets signed token1 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount1) {
return
liquidity < 0
? -getAmount1DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount1DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(int256(MAX_TICK)), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title ERC20Mintable
* @dev Implementation of the ERC20Mintable. Extension of {ERC20} that adds a minting behaviour.
*/
abstract contract ERC20Mintable is ERC20 {
// indicates if minting is finished
bool private _mintingFinished = false;
/**
* @dev Emitted during finish minting
*/
event MintFinished();
/**
* @dev Tokens can be minted only before minting finished.
*/
modifier canMint() {
require(!_mintingFinished, "ERC20Mintable: minting is finished");
_;
}
/**
* @return if minting is finished or not.
*/
function mintingFinished() public view returns (bool) {
return _mintingFinished;
}
/**
* @dev Function to mint tokens.
*
* WARNING: it allows everyone to mint new tokens. Access controls MUST be defined in derived contracts.
*
* @param account The address that will receive the minted tokens
* @param amount The amount of tokens to mint
*/
function mint(address account, uint256 amount) public canMint {
_mint(account, amount);
}
/**
* @dev Function to stop minting new tokens.
*
* WARNING: it allows everyone to finish minting. Access controls MUST be defined in derived contracts.
*/
function finishMinting() public canMint {
_finishMinting();
}
/**
* @dev Function to stop minting new tokens.
*/
function _finishMinting() internal virtual {
_mintingFinished = true;
emit MintFinished();
}
}
|
Gets the amount0 delta between two prices Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), i.e. liquidity (sqrt(upper) - sqrt(lower)) / (sqrt(upper) sqrt(lower)) sqrtRatioAX96 A sqrt price sqrtRatioBX96 Another sqrt price liquidity The amount of usable liquidity roundUp Whether to round the amount up or down return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
|
function getAmount0DeltaV2(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
require(sqrtRatioAX96 > 0);
return
roundUp
? UnsafeMath.divRoundingUp(
FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
sqrtRatioAX96
)
: FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
}
| 5,408,957
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract GameContract {
uint256 constant SCISSORS = 1;
uint256 constant ROCK = 2;
uint256 constant PAPER = 3;
enum RESULT_TYPE {
UNDECIDED,
WIN_1,
DRAW,
WIN_2
}
enum ROOM_STATUS {
EMPTY,
ONE_PERSON,
FULL,
PLAYED
}
struct Room {
uint256 id;
address address_1;
address address_2;
uint256 betAmount;
ROOM_STATUS status;
RESULT_TYPE result;
//Token will be used in the room
string token;
// Player's option in hashcode
bytes32 hashcode_1;
bytes32 hashcode_2;
// Player's option in number (rock, scissors, paper), set after sending secret key
// if choose = 0 => player haven't sent secret key
uint256 choose_1;
uint256 choose_2;
// Check if a player sent secret key or not
bool[2] checks;
}
struct Currency {
address addressToken;
string symbol;
}
uint256 public feeRatePercentage;
mapping(string => address) listToken;
// Array include list of token using in game
Currency[] public arrCurrency;
Room[] public rooms;
// Keep track of opened room number
uint256 public roomNumber;
// Check number of opening rooms (1 person)
uint256 public openingRoomNumber;
// Check if someone is already a owner of a opening room or not
// If they were, stop them from opening a new one
mapping(address => uint256) public ownerCount;
// Check number of rooms a player has joined
mapping(address => uint256) public playerRoomsCount;
event CreateRoom(Room _room);
event JoinRoom(Room _room);
event MakeResult(Room _room);
event Withdraw(Room _room, address _player);
address owner;
constructor(uint256 _feeRatePercentage) {
owner = msg.sender;
feeRatePercentage = _feeRatePercentage;
}
//Check balance of contract corresponding to each token
function balance(string memory _token) public view returns (uint256) {
if (sha256(bytes(_token)) == sha256(bytes(""))) {
return address(this).balance;
} else {
return ERC20(listToken[_token]).balanceOf(address(this));
}
}
//Add token in game
function addCurrency(address _addressToken) public {
require(msg.sender == owner, "You are not allowed");
string memory _symbol = ERC20(_addressToken).symbol();
arrCurrency.push(Currency(_addressToken, _symbol));
listToken[_symbol] = _addressToken;
}
function getCurrencies() public view returns (Currency[] memory) {
return arrCurrency;
}
// Check number of opening room
function getOpeningRooms() public view returns (Room[] memory) {
Room[] memory results = new Room[](openingRoomNumber);
uint256 rid = 0;
for (uint256 i; i < roomNumber; i++) {
if (rooms[i].status == ROOM_STATUS.ONE_PERSON) {
results[rid] = rooms[i];
rid += 1;
}
}
return results;
}
function getPlayerRooms(address _player)
public
view
returns (Room[] memory)
{
uint256 count = playerRoomsCount[_player];
Room[] memory results = new Room[](count);
uint256 rid = 0;
for (uint256 i; i < roomNumber; i++) {
if (
rooms[i].address_1 == _player || rooms[i].address_2 == _player
) {
results[rid] = rooms[i];
rid += 1;
}
}
return results;
}
// Send bet amount to create a room
function createRoom(string memory _token) public payable {
require(
ownerCount[msg.sender] <= 10,
"You have already reached to limit."
);
require(msg.value > 0, "Bet amount must greater than 0");
checkValidToken(_token, msg.value);
Room memory room;
room.id = roomNumber;
room.status = ROOM_STATUS.ONE_PERSON;
room.address_1 = msg.sender;
room.betAmount = msg.value;
room.token = _token;
rooms.push(room);
ownerCount[msg.sender] += 1;
playerRoomsCount[msg.sender] += 1;
openingRoomNumber += 1;
roomNumber += 1;
emit CreateRoom(room);
}
// Player send option here to join a room
function sendHashcode(uint256 _id, bytes32 _hashcode) public payable {
Room storage room = rooms[_id];
// With room owner: Only send option if room is full (after other player sent hashcode)
if (room.address_1 == msg.sender) {
require(room.status == ROOM_STATUS.FULL, "Room is unavailable");
require(
!room.checks[1],
"You can not send hashcode after the second player have already secret code"
);
room.hashcode_1 = _hashcode;
}
// With guest player: Only send option if room has one person
else {
require(
!room.checks[0],
"You can not send hashcode after room owner have already secret code"
);
require(
room.status == ROOM_STATUS.ONE_PERSON,
"Room is unavailable"
);
require(
msg.value == room.betAmount,
"You must bet equal in the first 1"
);
checkValidToken(room.token, room.betAmount);
room.status = ROOM_STATUS.FULL;
room.hashcode_2 = _hashcode;
room.address_2 = msg.sender;
playerRoomsCount[msg.sender] = playerRoomsCount[msg.sender] + 1;
openingRoomNumber -= 1;
emit JoinRoom(room);
}
}
// Hàm rút tiền . Một trong 2 người chơi đều có quyền rút tiền khi 1 trong 2 chưa gửi key bí mật lên hợp đồng.
// Nếu chủ phòng là người rút thì tiền cược 2 người chơi sẽ về lại tài khoản của họ và phòng trở về trạng thái available
// Nếu người chơi 2 rút tiền thì họ sẽ nhận lại tiền và phòng trở về trạng thái 1.
function withdraw(uint256 _id) public payable {
Room storage room = rooms[_id];
require(
msg.sender == room.address_1 || msg.sender == room.address_2,
"You are not players in this room"
);
require(!room.checks[0] && !room.checks[0], "You can not withdraw");
uint256 withdrawAmountMinusFee = (room.betAmount / 100) *
(100 - feeRatePercentage);
if (msg.sender == room.address_1) {
transferToken(room.address_1, room.token, withdrawAmountMinusFee);
if (room.status == ROOM_STATUS.FULL) {
// If this room has 2 players, send money back to both of them
transferToken(
room.address_2,
room.token,
withdrawAmountMinusFee
);
} else if (room.status == ROOM_STATUS.ONE_PERSON) {
openingRoomNumber -= 1;
}
room.status = ROOM_STATUS.EMPTY;
ownerCount[msg.sender] -= 1;
} else if (msg.sender == room.address_2) {
room.status = ROOM_STATUS.ONE_PERSON;
openingRoomNumber += 1;
// Delete player 2 data in this room
room.address_2 = address(0);
room.hashcode_2 = "";
transferToken(room.address_2, room.token, withdrawAmountMinusFee);
playerRoomsCount[msg.sender] = playerRoomsCount[msg.sender] - 1;
}
emit Withdraw(room, msg.sender);
}
// After both players sent hashcode, continue by sending secret code
function sendSecret(uint256 _id, string memory _secretCode) public payable {
Room storage room = rooms[_id];
require(room.status == ROOM_STATUS.FULL, "Room is unavailable");
// Find sender's option by secret key
if (msg.sender == room.address_1) {
uint256 choose = getPlayerOption(_secretCode, room.hashcode_1);
require(choose > 0, "the first secret code is wrong");
room.checks[0] = true;
room.choose_1 = choose;
} else if (msg.sender == room.address_2) {
require(
room.hashcode_1 != "",
"Player 1 haven't sent option. Please wait."
);
uint256 choose = getPlayerOption(_secretCode, room.hashcode_2);
require(choose > 0, "the second secret code is wrong");
room.checks[1] = true;
room.choose_2 = choose;
}
// If both players sent secret key, make result and send money to winner
if (room.checks[0] && room.checks[1]) {
room.result = getResult(room.choose_1, room.choose_2);
room.status = ROOM_STATUS.PLAYED;
ownerCount[room.address_1] = 0;
uint256 betAmountMinusFee = ((room.betAmount * 2) / 100) *
(100 - feeRatePercentage);
if (room.result == RESULT_TYPE.DRAW) {
transferToken(
room.address_1,
room.token,
betAmountMinusFee / 2
);
transferToken(
room.address_2,
room.token,
betAmountMinusFee / 2
);
} else if (room.result == RESULT_TYPE.WIN_1) {
transferToken(room.address_1, room.token, betAmountMinusFee);
} else if (room.result == RESULT_TYPE.WIN_2) {
transferToken(room.address_2, room.token, betAmountMinusFee);
}
emit MakeResult(room);
}
}
function checkValidToken(string memory _token, uint256 _amount) private {
if (sha256(bytes(_token)) != sha256(bytes(""))) {
require(listToken[_token] != address(0), "Token is invalid");
require(
ERC20(listToken[_token]).allowance(msg.sender, address(this)) ==
_amount,
"You must call approve first in web3"
);
require(
ERC20(listToken[_token]).transferFrom(
msg.sender,
address(this),
_amount
),
"Transfer failed"
);
}
}
function transferToken(
address _address,
string memory _tokenSymbol,
uint256 _amount
) private {
if (sha256(bytes(_tokenSymbol)) == sha256(bytes(""))) {
payable(_address).transfer(_amount);
} else {
ERC20(listToken[_tokenSymbol]).transfer(_address, _amount);
}
}
/**
Pure functions
**/
function getResult(uint256 _choose_1, uint256 _choose_2)
private
pure
returns (RESULT_TYPE result)
{
if (_choose_1 == SCISSORS && _choose_2 == ROCK) {
return RESULT_TYPE.WIN_2;
}
if (_choose_1 == SCISSORS && _choose_2 == PAPER) {
return RESULT_TYPE.WIN_1;
}
if (_choose_1 == SCISSORS && _choose_2 == SCISSORS) {
return RESULT_TYPE.DRAW;
}
if (_choose_1 == ROCK && _choose_2 == SCISSORS) {
return RESULT_TYPE.WIN_1;
}
if (_choose_1 == ROCK && _choose_2 == PAPER) {
return RESULT_TYPE.WIN_2;
}
if (_choose_1 == ROCK && _choose_2 == ROCK) {
return RESULT_TYPE.DRAW;
}
if (_choose_1 == PAPER && _choose_2 == SCISSORS) {
return RESULT_TYPE.WIN_2;
}
if (_choose_1 == PAPER && _choose_2 == PAPER) {
return RESULT_TYPE.DRAW;
}
if (_choose_1 == PAPER && _choose_2 == ROCK) {
return RESULT_TYPE.WIN_1;
}
}
function getPlayerOption(string memory _secretCode, bytes32 _hashcode)
private
pure
returns (uint256)
{
if (getHashcode(_secretCode, SCISSORS) == _hashcode) {
return SCISSORS;
}
if (getHashcode(_secretCode, ROCK) == _hashcode) {
return ROCK;
}
if (getHashcode(_secretCode, PAPER) == _hashcode) {
return PAPER;
}
return 0;
}
function getHashcode(string memory _secretCode, uint256 _option)
public
pure
returns (bytes32)
{
return
sha256(bytes.concat(bytes(_secretCode), bytes(uint2str(_option))));
}
function uint2str(uint256 _i) internal pure returns (string memory str) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0) {
bstr[--k] = bytes1(uint8(48 + (j % 10)));
j /= 10;
}
str = string(bstr);
return str;
}
}
|
After both players sent hashcode, continue by sending secret code Find sender's option by secret key If both players sent secret key, make result and send money to winner
|
function sendSecret(uint256 _id, string memory _secretCode) public payable {
Room storage room = rooms[_id];
require(room.status == ROOM_STATUS.FULL, "Room is unavailable");
if (msg.sender == room.address_1) {
uint256 choose = getPlayerOption(_secretCode, room.hashcode_1);
require(choose > 0, "the first secret code is wrong");
room.checks[0] = true;
room.choose_1 = choose;
require(
room.hashcode_1 != "",
"Player 1 haven't sent option. Please wait."
);
uint256 choose = getPlayerOption(_secretCode, room.hashcode_2);
require(choose > 0, "the second secret code is wrong");
room.checks[1] = true;
room.choose_2 = choose;
}
if (room.checks[0] && room.checks[1]) {
room.result = getResult(room.choose_1, room.choose_2);
room.status = ROOM_STATUS.PLAYED;
ownerCount[room.address_1] = 0;
uint256 betAmountMinusFee = ((room.betAmount * 2) / 100) *
(100 - feeRatePercentage);
if (room.result == RESULT_TYPE.DRAW) {
transferToken(
room.address_1,
room.token,
betAmountMinusFee / 2
);
transferToken(
room.address_2,
room.token,
betAmountMinusFee / 2
);
transferToken(room.address_1, room.token, betAmountMinusFee);
transferToken(room.address_2, room.token, betAmountMinusFee);
}
emit MakeResult(room);
}
}
| 6,475,241
|
./full_match/1/0x09808feA0Cc0067fCA564e746a05296C0024C4c3/sources/contracts/C1/AJMANREC1.sol
|
Function that mints the NFT this is a dumb function that simply mints a number of NFTs for a given address.
|
function mint(address _address, uint256 _qty) internal {
_mint(_address, _qty);
}
| 9,731,011
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
contract BBI is ERC20, Ownable {
using SafeMath for uint256;
modifier lockSwap() {
_inSwap = true;
_;
_inSwap = false;
}
modifier liquidityAdd() {
_inLiquidityAdd = true;
_;
_inLiquidityAdd = false;
}
// == CONSTANTS ==
uint256 public constant MAX_SUPPLY = 1_000_000_000 ether;
uint256 public constant BPS_DENOMINATOR = 10_000;
uint256 public constant SNIPE_BLOCKS = 2;
// == LIMITS ==
/// @notice Wallet limit in wei.
uint256 public walletLimit;
/// @notice Buy limit in wei.
uint256 public buyLimit;
/// @notice Cooldown in seconds
uint256 public cooldown = 20;
// == TAXES ==
/// @notice Buy marketingTax in BPS
uint256 public buyMarketingTax = 300;
/// @notice Buy devTax in BPS
uint256 public buyDevTax = 400;
/// @notice Buy autoLiquidityTax in BPS
uint256 public buyAutoLiquidityTax = 200;
/// @notice Buy treasuryTax in BPS
uint256 public buyTreasuryTax = 100;
/// @notice Sell marketingTax in BPS
uint256 public sellMarketingTax = 900;
/// @notice Sell devTax in BPS
uint256 public sellDevTax = 1000;
/// @notice Sell autoLiquidityTax in BPS
uint256 public sellAutoLiquidityTax = 400;
/// @notice Sell treasuryTax in BPS
uint256 public sellTreasuryTax = 200;
/// @notice address that marketingTax is sent to
address payable public marketingTaxWallet;
/// @notice address that devTax is sent to
address payable public devTaxWallet;
/// @notice address that treasuryTax is sent to
address payable public treasuryTaxWallet;
/// @notice tokens that are allocated for marketingTax tax
uint256 public totalMarketingTax;
/// @notice tokens that are allocated for devTax tax
uint256 public totalDevTax;
/// @notice tokens that are allocated for auto liquidity tax
uint256 public totalAutoLiquidityTax;
/// @notice tokens that are allocated for treasury tax
uint256 public totalTreasuryTax;
// == FLAGS ==
/// @notice flag indicating Uniswap trading status
bool public tradingActive = false;
/// @notice flag indicating swapAll enabled
bool public swapFees = true;
// == UNISWAP ==
IUniswapV2Router02 public router = IUniswapV2Router02(address(0));
address public pair;
// == WALLET STATUSES ==
/// @notice Maps each wallet to their tax exlcusion status
mapping(address => bool) public taxExcluded;
/// @notice Maps each wallet to the last timestamp they bought
mapping(address => uint256) public lastBuy;
/// @notice Maps each wallet to their blacklist status
mapping(address => bool) public blacklist;
/// @notice Maps each wallet to their whitelist status on buy limit
mapping(address => bool) public walletLimitWhitelist;
// == MISC ==
/// @notice Block when trading is first enabled
uint256 public tradingBlock;
// == INTERNAL ==
uint256 internal _totalSupply = 0;
bool internal _inSwap = false;
bool internal _inLiquidityAdd = false;
mapping(address => uint256) private _balances;
event MarketingTaxWalletChanged(address previousWallet, address nextWallet);
event DevTaxWalletChanged(address previousWallet, address nextWallet);
event TreasuryTaxWalletChanged(address previousWallet, address nextWallet);
event BuyMarketingTaxChanged(uint256 previousTax, uint256 nextTax);
event SellMarketingTaxChanged(uint256 previousTax, uint256 nextTax);
event BuyDevTaxChanged(uint256 previousTax, uint256 nextTax);
event SellDevTaxChanged(uint256 previousTax, uint256 nextTax);
event BuyAutoLiquidityTaxChanged(uint256 previousTax, uint256 nextTax);
event SellAutoLiquidityTaxChanged(uint256 previousTax, uint256 nextTax);
event BuyTreasuryTaxChanged(uint256 previousTax, uint256 nextTax);
event SellTreasuryTaxChanged(uint256 previousTax, uint256 nextTax);
event MarketingTaxRescued(uint256 amount);
event DevTaxRescued(uint256 amount);
event AutoLiquidityTaxRescued(uint256 amount);
event TreasuryTaxRescued(uint256 amount);
event TradingActiveChanged(bool enabled);
event TaxExclusionChanged(address user, bool taxExcluded);
event MaxTransferChanged(uint256 previousMax, uint256 nextMax);
event BuyLimitChanged(uint256 previousMax, uint256 nextMax);
event WalletLimitChanged(uint256 previousMax, uint256 nextMax);
event CooldownChanged(uint256 previousCooldown, uint256 nextCooldown);
event BlacklistUpdated(address user, bool previousStatus, bool nextStatus);
event SwapFeesChanged(bool previousStatus, bool nextStatus);
event WalletLimitWhitelistUpdated(
address user,
bool previousStatus,
bool nextStatus
);
constructor(
address _factory,
address _router,
uint256 _buyLimit,
uint256 _walletLimit,
address payable _marketingTaxWallet,
address payable _devTaxWallet,
address payable _treasuryTaxWallet
) ERC20("Butkus Balboa Inu", "BBI") Ownable() {
taxExcluded[owner()] = true;
taxExcluded[address(0)] = true;
taxExcluded[_marketingTaxWallet] = true;
taxExcluded[_devTaxWallet] = true;
taxExcluded[address(this)] = true;
buyLimit = _buyLimit;
walletLimit = _walletLimit;
marketingTaxWallet = _marketingTaxWallet;
devTaxWallet = _devTaxWallet;
treasuryTaxWallet = _treasuryTaxWallet;
router = IUniswapV2Router02(_router);
IUniswapV2Factory uniswapContract = IUniswapV2Factory(_factory);
pair = uniswapContract.createPair(address(this), router.WETH());
_updateWalletLimitWhitelist(address(this), true);
_updateWalletLimitWhitelist(pair, true);
}
/// @notice Change the address of the buyback wallet
/// @param _marketingTaxWallet The new address of the buyback wallet
function setMarketingTaxWallet(address payable _marketingTaxWallet)
external
onlyOwner
{
emit MarketingTaxWalletChanged(marketingTaxWallet, _marketingTaxWallet);
marketingTaxWallet = _marketingTaxWallet;
}
/// @notice Change the address of the devTax wallet
/// @param _devTaxWallet The new address of the devTax wallet
function setDevTaxWallet(address payable _devTaxWallet) external onlyOwner {
emit DevTaxWalletChanged(devTaxWallet, _devTaxWallet);
devTaxWallet = _devTaxWallet;
}
/// @notice Change the address of the treasuryTax wallet
/// @param _treasuryTaxWallet The new address of the treasuryTax wallet
function setTreasuryTaxWallet(address payable _treasuryTaxWallet)
external
onlyOwner
{
emit TreasuryTaxWalletChanged(treasuryTaxWallet, _treasuryTaxWallet);
treasuryTaxWallet = _treasuryTaxWallet;
}
/// @notice Change the buy marketingTax rate
/// @param _buyMarketingTax The new buy marketingTax rate
function setBuyMarketingTax(uint256 _buyMarketingTax) external onlyOwner {
require(
_buyMarketingTax <= BPS_DENOMINATOR,
"_buyMarketingTax cannot exceed BPS_DENOMINATOR"
);
emit BuyMarketingTaxChanged(buyMarketingTax, _buyMarketingTax);
buyMarketingTax = _buyMarketingTax;
}
/// @notice Change the sell marketingTax rate
/// @param _sellMarketingTax The new sell marketingTax rate
function setSellMarketingTax(uint256 _sellMarketingTax) external onlyOwner {
require(
_sellMarketingTax <= BPS_DENOMINATOR,
"_sellMarketingTax cannot exceed BPS_DENOMINATOR"
);
emit SellMarketingTaxChanged(sellMarketingTax, _sellMarketingTax);
sellMarketingTax = _sellMarketingTax;
}
/// @notice Change the buy devTax rate
/// @param _buyDevTax The new devTax rate
function setBuyDevTax(uint256 _buyDevTax) external onlyOwner {
require(
_buyDevTax <= BPS_DENOMINATOR,
"_buyDevTax cannot exceed BPS_DENOMINATOR"
);
emit BuyDevTaxChanged(buyDevTax, _buyDevTax);
buyDevTax = _buyDevTax;
}
/// @notice Change the buy devTax rate
/// @param _sellDevTax The new devTax rate
function setSellDevTax(uint256 _sellDevTax) external onlyOwner {
require(
_sellDevTax <= BPS_DENOMINATOR,
"_sellDevTax cannot exceed BPS_DENOMINATOR"
);
emit SellDevTaxChanged(sellDevTax, _sellDevTax);
sellDevTax = _sellDevTax;
}
/// @notice Change the buy autoLiquidityTax rate
/// @param _buyAutoLiquidityTax The new buy autoLiquidityTax rate
function setBuyAutoLiquidityTax(uint256 _buyAutoLiquidityTax)
external
onlyOwner
{
require(
_buyAutoLiquidityTax <= BPS_DENOMINATOR,
"_buyAutoLiquidityTax cannot exceed BPS_DENOMINATOR"
);
emit BuyAutoLiquidityTaxChanged(
buyAutoLiquidityTax,
_buyAutoLiquidityTax
);
buyAutoLiquidityTax = _buyAutoLiquidityTax;
}
/// @notice Change the sell autoLiquidityTax rate
/// @param _sellAutoLiquidityTax The new sell autoLiquidityTax rate
function setSellAutoLiquidityTax(uint256 _sellAutoLiquidityTax)
external
onlyOwner
{
require(
_sellAutoLiquidityTax <= BPS_DENOMINATOR,
"_sellAutoLiquidityTax cannot exceed BPS_DENOMINATOR"
);
emit SellAutoLiquidityTaxChanged(
sellAutoLiquidityTax,
_sellAutoLiquidityTax
);
sellAutoLiquidityTax = _sellAutoLiquidityTax;
}
/// @notice Change the buy treasuryTax rate
/// @param _buyTreasuryTax The new treasuryTax rate
function setBuyTreasuryTax(uint256 _buyTreasuryTax) external onlyOwner {
require(
_buyTreasuryTax <= BPS_DENOMINATOR,
"_buyTreasuryTax cannot exceed BPS_DENOMINATOR"
);
emit BuyTreasuryTaxChanged(buyTreasuryTax, _buyTreasuryTax);
buyTreasuryTax = _buyTreasuryTax;
}
/// @notice Change the buy treasuryTax rate
/// @param _sellTreasuryTax The new treasuryTax rate
function setSellTreasuryTax(uint256 _sellTreasuryTax) external onlyOwner {
require(
_sellTreasuryTax <= BPS_DENOMINATOR,
"_sellTreasuryTax cannot exceed BPS_DENOMINATOR"
);
emit SellTreasuryTaxChanged(sellTreasuryTax, _sellTreasuryTax);
sellTreasuryTax = _sellTreasuryTax;
}
/// @notice Change the cooldown for buys
/// @param _cooldown The new cooldown in seconds
function setCooldown(uint256 _cooldown) external onlyOwner {
emit CooldownChanged(cooldown, _cooldown);
cooldown = _cooldown;
}
/// @notice Rescue BBI from the marketingTax amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of BBI to rescue
/// @param _recipient The recipient of the rescued BBI
function rescueMarketingTaxTokens(uint256 _amount, address _recipient)
external
onlyOwner
{
require(
_amount <= totalMarketingTax,
"Amount cannot be greater than totalMarketingTax"
);
_rawTransfer(address(this), _recipient, _amount);
emit MarketingTaxRescued(_amount);
totalMarketingTax -= _amount;
}
/// @notice Rescue BBI from the devTax amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of BBI to rescue
/// @param _recipient The recipient of the rescued BBI
function rescueDevTaxTokens(uint256 _amount, address _recipient)
external
onlyOwner
{
require(
_amount <= totalDevTax,
"Amount cannot be greater than totalDevTax"
);
_rawTransfer(address(this), _recipient, _amount);
emit DevTaxRescued(_amount);
totalDevTax -= _amount;
}
/// @notice Rescue BBI from the autoLiquidityTax amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of BBI to rescue
/// @param _recipient The recipient of the rescued BBI
function rescueAutoLiquidityTaxTokens(uint256 _amount, address _recipient)
external
onlyOwner
{
require(
_amount <= totalAutoLiquidityTax,
"Amount cannot be greater than totalAutoLiquidityTax"
);
_rawTransfer(address(this), _recipient, _amount);
emit AutoLiquidityTaxRescued(_amount);
totalAutoLiquidityTax -= _amount;
}
/// @notice Rescue BBI from the treasuryTax amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of BBI to rescue
/// @param _recipient The recipient of the rescued BBI
function rescueTreasuryTaxTokens(uint256 _amount, address _recipient)
external
onlyOwner
{
require(
_amount <= totalTreasuryTax,
"Amount cannot be greater than totalTreasuryTax"
);
_rawTransfer(address(this), _recipient, _amount);
emit TreasuryTaxRescued(_amount);
totalTreasuryTax -= _amount;
}
function addLiquidity(uint256 tokens)
external
payable
onlyOwner
liquidityAdd
{
_mint(address(this), tokens);
_approve(address(this), address(router), tokens);
router.addLiquidityETH{value: msg.value}(
address(this),
tokens,
0,
0,
owner(),
// solhint-disable-next-line not-rely-on-time
block.timestamp
);
}
/// @notice Admin function to update a wallet's blacklist status
/// @param user the wallet
/// @param status the new status
function updateBlacklist(address user, bool status)
external
virtual
onlyOwner
{
_updateBlacklist(user, status);
}
function _updateBlacklist(address user, bool status) internal virtual {
emit BlacklistUpdated(user, blacklist[user], status);
blacklist[user] = status;
}
/// @notice Admin function to update a wallet's buy limit status
/// @param user the wallet
/// @param status the new status
function updateWalletLimitWhitelist(address user, bool status)
external
virtual
onlyOwner
{
_updateWalletLimitWhitelist(user, status);
}
function _updateWalletLimitWhitelist(address user, bool status)
internal
virtual
{
emit WalletLimitWhitelistUpdated(
user,
walletLimitWhitelist[user],
status
);
walletLimitWhitelist[user] = status;
}
/// @notice Enables or disables trading on Uniswap
function setTradingActive(bool _tradingActive) external onlyOwner {
if (_tradingActive && tradingBlock == 0) {
tradingBlock = block.number;
}
tradingActive = _tradingActive;
emit TradingActiveChanged(_tradingActive);
}
/// @notice Updates tax exclusion status
/// @param _account Account to update the tax exclusion status of
/// @param _taxExcluded If true, exclude taxes for this user
function setTaxExcluded(address _account, bool _taxExcluded)
public
onlyOwner
{
taxExcluded[_account] = _taxExcluded;
emit TaxExclusionChanged(_account, _taxExcluded);
}
/// @notice Updates the max amount allowed to buy
/// @param _buyLimit The new buy limit
function setBuyLimit(uint256 _buyLimit) external onlyOwner {
emit BuyLimitChanged(buyLimit, _buyLimit);
buyLimit = _buyLimit;
}
/// @notice Updates the max amount allowed to be held by a single wallet
/// @param _walletLimit The new max
function setWalletLimit(uint256 _walletLimit) external onlyOwner {
emit WalletLimitChanged(walletLimit, _walletLimit);
walletLimit = _walletLimit;
}
/// @notice Enable or disable whether swap occurs during `_transfer`
/// @param _swapFees If true, enables swap during `_transfer`
function setSwapFees(bool _swapFees) external onlyOwner {
emit SwapFeesChanged(swapFees, _swapFees);
swapFees = _swapFees;
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function _addBalance(address account, uint256 amount) internal {
_balances[account] = _balances[account] + amount;
}
function _subtractBalance(address account, uint256 amount) internal {
_balances[account] = _balances[account] - amount;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(!blacklist[recipient], "Recipient is blacklisted");
if (taxExcluded[sender] || taxExcluded[recipient]) {
_rawTransfer(sender, recipient, amount);
return;
}
// Enforce wallet limits
if (!walletLimitWhitelist[recipient]) {
require(
balanceOf(recipient).add(amount) <= walletLimit,
"Wallet limit exceeded"
);
}
uint256 send = amount;
uint256 marketingTax;
uint256 devTax;
uint256 autoLiquidityTax;
uint256 treasuryTax;
if (sender == pair) {
require(tradingActive, "Trading is not yet active");
require(
balanceOf(recipient).add(amount) <= buyLimit,
"Buy limit exceeded"
);
if (block.number <= tradingBlock + SNIPE_BLOCKS) {
_updateBlacklist(recipient, true);
}
if (cooldown > 0) {
require(
lastBuy[recipient] + cooldown <= block.timestamp,
"Cooldown still active"
);
lastBuy[recipient] = block.timestamp;
}
(
send,
marketingTax,
devTax,
autoLiquidityTax,
treasuryTax
) = _getTaxAmounts(amount, true);
} else if (recipient == pair) {
require(tradingActive, "Trading is not yet active");
if (swapFees) swapAll();
(
send,
marketingTax,
devTax,
autoLiquidityTax,
treasuryTax
) = _getTaxAmounts(amount, false);
}
_rawTransfer(sender, recipient, send);
_takeTaxes(sender, marketingTax, devTax, autoLiquidityTax, treasuryTax);
}
/// @notice Peforms auto liquidity and tax distribution
function swapAll() public lockSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
// Auto-liquidity
uint256 autoLiquidityAmount = totalAutoLiquidityTax.div(2);
uint256 walletTaxes = totalMarketingTax.add(totalDevTax).add(
totalTreasuryTax
);
_approve(
address(this),
address(router),
walletTaxes.add(totalAutoLiquidityTax)
);
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
autoLiquidityAmount.add(walletTaxes),
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
router.addLiquidityETH{value: address(this).balance}(
address(this),
autoLiquidityAmount,
0,
0,
address(0xdead),
block.timestamp
);
totalAutoLiquidityTax = 0;
// Distribute remaining taxes
uint256 contractEth = address(this).balance;
uint256 marketingTaxEth = contractEth.mul(totalMarketingTax).div(
walletTaxes
);
uint256 devTaxEth = contractEth.mul(totalDevTax).div(walletTaxes);
uint256 treasuryTaxEth = contractEth.mul(totalTreasuryTax).div(
walletTaxes
);
totalMarketingTax = 0;
totalDevTax = 0;
totalTreasuryTax = 0;
if (marketingTaxEth > 0) {
marketingTaxWallet.transfer(marketingTaxEth);
}
if (devTaxEth > 0) {
devTaxWallet.transfer(devTaxEth);
}
if (treasuryTaxEth > 0) {
treasuryTaxWallet.transfer(treasuryTaxEth);
}
}
/// @notice Admin function to rescue ETH from the contract
function rescueETH() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
/// @notice Transfers BBI from an account to this contract for taxes
/// @param _account The account to transfer BBI from
/// @param _marketingTaxAmount The amount of marketingTax tax to transfer
/// @param _devTaxAmount The amount of devTax tax to transfer
function _takeTaxes(
address _account,
uint256 _marketingTaxAmount,
uint256 _devTaxAmount,
uint256 _autoLiquidityTaxAmount,
uint256 _treasuryTaxAmount
) internal {
require(_account != address(0), "taxation from the zero address");
uint256 totalAmount = _marketingTaxAmount
.add(_devTaxAmount)
.add(_autoLiquidityTaxAmount)
.add(_treasuryTaxAmount);
_rawTransfer(_account, address(this), totalAmount);
totalMarketingTax += _marketingTaxAmount;
totalDevTax += _devTaxAmount;
totalAutoLiquidityTax += _autoLiquidityTaxAmount;
totalTreasuryTax += _treasuryTaxAmount;
}
/// @notice Get a breakdown of send and tax amounts
/// @param amount The amount to tax in wei
/// @return send The raw amount to send
/// @return marketingTax The raw marketingTax tax amount
/// @return devTax The raw devTax tax amount
function _getTaxAmounts(uint256 amount, bool buying)
internal
view
returns (
uint256 send,
uint256 marketingTax,
uint256 devTax,
uint256 autoLiquidityTax,
uint256 treasuryTax
)
{
if (buying) {
marketingTax = amount.mul(buyMarketingTax).div(BPS_DENOMINATOR);
devTax = amount.mul(buyDevTax).div(BPS_DENOMINATOR);
autoLiquidityTax = amount.mul(buyAutoLiquidityTax).div(
BPS_DENOMINATOR
);
treasuryTax = amount.mul(buyTreasuryTax).div(BPS_DENOMINATOR);
} else {
marketingTax = amount.mul(sellMarketingTax).div(BPS_DENOMINATOR);
devTax = amount.mul(sellDevTax).div(BPS_DENOMINATOR);
autoLiquidityTax = amount.mul(sellAutoLiquidityTax).div(
BPS_DENOMINATOR
);
treasuryTax = amount.mul(sellTreasuryTax).div(BPS_DENOMINATOR);
}
send = amount.sub(marketingTax).sub(devTax).sub(autoLiquidityTax).sub(
treasuryTax
);
}
// modified from OpenZeppelin ERC20
function _rawTransfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "transfer from the zero address");
require(recipient != address(0), "transfer to the zero address");
uint256 senderBalance = balanceOf(sender);
require(senderBalance >= amount, "transfer amount exceeds balance");
unchecked {
_subtractBalance(sender, amount);
}
_addBalance(recipient, amount);
emit Transfer(sender, recipient, amount);
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function _mint(address account, uint256 amount) internal override {
require(_totalSupply.add(amount) <= MAX_SUPPLY, "Max supply exceeded");
_totalSupply += amount;
_addBalance(account, amount);
emit Transfer(address(0), account, amount);
}
function mint(address account, uint256 amount) external onlyOwner {
_mint(account, amount);
}
function airdrop(address[] memory accounts, uint256[] memory amounts)
external
onlyOwner
{
require(accounts.length == amounts.length, "array lengths must match");
for (uint256 i = 0; i < accounts.length; i++) {
_mint(accounts[i], amounts[i]);
}
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
|
Updates tax exclusion status _account Account to update the tax exclusion status of _taxExcluded If true, exclude taxes for this user
|
function setTaxExcluded(address _account, bool _taxExcluded)
public
onlyOwner
{
taxExcluded[_account] = _taxExcluded;
emit TaxExclusionChanged(_account, _taxExcluded);
}
| 1,608,863
|
/**
* @title smart real estate platform implementation
* @author Maxim Akimov - <devstylesoftware@gmail.com>
*/
// ver from 23/06/2018 v0.3
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
address public ownerCandidat;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public{
require(newOwner != address(0));
ownerCandidat = newOwner;
}
/**
* @dev Allows safe change current owner to a newOwner.
*/
function confirmOwnership() public{
require(msg.sender == ownerCandidat);
owner = msg.sender;
}
}
contract realestate is Ownable{
using SafeMath for uint;
enum statuses {
created,canceled,signed,finished
}
struct _dealData{
address buyer;
address seller;
address signer;
uint sum;
uint fee;
uint atCreated;
uint atClosed;
uint balance;
statuses status;
uint dealNumber;
string comment;
uint objectType; // 0 - old 1 - new
uint date;
bool isProlong;
}
struct _dealSigns{
address signBuyer;
address signSeller;
address finishSignBuyer;
address finishSignSeller;
address finishSignSigner;
}
event MoneyTransfer(
address indexed _from,
address indexed _to,
uint _value
);
address public agencyOwner;
address public agencyReceiver;
_dealData[] private deals;
_dealSigns[] private signs;
mapping (uint=>uint) private dealNumbers;
// **************** modifiers **************** //
modifier onlyAgency(){
require(msg.sender == agencyOwner);
_;
}
modifier onlySigner(uint _dealNumber){
uint deal = dealNumbers[_dealNumber];
require(msg.sender == deals[deal].signer);
_;
}
constructor() public{
agencyOwner = msg.sender;
agencyReceiver = msg.sender;
}
/**
* @dev Change eth address of agency for create deal
* @param _newAgency - new agency eth address
*/
function changeAgencyOwner(address _newAgency) public {
require(msg.sender == agencyOwner || msg.sender == owner);
agencyOwner = _newAgency;
}
/**
* @dev Change eth address of agency for recieve fee
* @param _agencyReceiver - new agency eth address
*/
function changeAgencyReceiver (address _agencyReceiver) public{
require(msg.sender == agencyOwner || msg.sender == owner);
agencyReceiver = _agencyReceiver;
}
/**
* @dev to prolongate a deal for some days
* @param _dealNumber - uniq number of deal
* @param _days - count of days from current time
*/
function changeDealDate(uint _dealNumber, uint _days) onlyAgency public{
uint deal = dealNumbers[_dealNumber];
require(deals[deal].isProlong);
deals[deal].date = now + _days * 1 days;
}
/**
* @dev Get all signs of deal by _dealNumber
* @param _dealNumber - uniq number of deal
*/
function getSigns(uint _dealNumber) constant public returns (
address signBuyer,
address signSeller,
address finishSignBuyer,
address finishSignSeller,
address finishSignSigner){
uint deal = dealNumbers[_dealNumber];
return (
signs[deal].signBuyer,
signs[deal].signSeller,
signs[deal].finishSignBuyer,
signs[deal].finishSignSeller,
signs[deal].finishSignSigner
);
}
/**
* @dev Get main data of deal by _dealNumber
* @param _dealNumber - uniq number of deal
*/
function getDealByNumber(uint _dealNumber) constant public returns (
address buyer,
address sender,
address agency,
uint sum,
uint atCreated,
statuses status,
uint objectType) {
uint deal = dealNumbers[_dealNumber];
return (
deals[deal].buyer,
deals[deal].seller,
deals[deal].signer,
deals[deal].sum,
deals[deal].atCreated,
deals[deal].status,
deals[deal].objectType
);
}
/**
* @dev Get lenght of priviate array deals (for agency only)
*/
function getDealsLength() onlyAgency constant public returns (uint len){
return deals.length;
}
/**
* @dev Get main data of deal
* @param deal - uniq id from priviate array deals
*/
function getDealById(uint deal) onlyAgency constant public returns (
address buyer,
address sender,
address agency,
uint sum,
uint atCreated,
statuses status,
uint objectType,
uint dealID) {
return (
deals[deal].buyer,
deals[deal].seller,
deals[deal].signer,
deals[deal].sum,
deals[deal].atCreated,
deals[deal].status,
deals[deal].objectType,
deal
);
}
/**
* @dev Get comment, fee, atCloced, date, is prolong of deal
* @param _dealNumber - uniq number of deal
*/
function getDealDataByNumber(uint _dealNumber) constant public returns (
string comment,
uint fee,
uint atClosed,
uint date,
bool isProlong) {
uint deal = dealNumbers[_dealNumber];
return (
deals[deal].comment,
deals[deal].fee,
deals[deal].atClosed,
deals[deal].date,
deals[deal].isProlong
);
}
/**
* @dev function for create deal by agency owner only
* @param _buyer - eth address of buyer
* @param _seller - eth address of seller
* @param _signer - eth address of signer (how cah canceled deal)
* @param _sum - sum of the deal (in wei)
* @param _fee - fee of the deal (in wei)
* @param _objectType - type of property (0 - old, 1 - new)
* @param _dealNumber - uniq number of deal
* @param _comment - any text coment of the deal
* @param whoPay - point out who pay fee of the deal (0 - buyer, 1 - seller)
* @param _countDays - Hoe many days allow for deal processing
* @param _isProlong - Allow to prolongate deal, if true
*/
function addDeal(
address _buyer,
address _seller,
address _signer,
uint _sum,
uint _fee,
uint _objectType,
uint _dealNumber,
string _comment,
uint whoPay,
uint _countDays,
bool _isProlong) onlyAgency public{
if(whoPay ==0){
_sum = _sum.add(_fee);
}
uint newIndex = deals.length++; signs.length ++;
deals[newIndex].buyer = _buyer;
deals[newIndex].seller = _seller;
deals[newIndex].signer = _signer;
deals[newIndex].sum = _sum;
deals[newIndex].fee = _fee;
deals[newIndex].date = now + _countDays * 1 days;
deals[newIndex].isProlong = _isProlong;
deals[newIndex].atCreated = now;
deals[newIndex].comment = _comment;
deals[newIndex].status = statuses.created;
deals[newIndex].balance = 0;
deals[newIndex].objectType = _objectType;
deals[newIndex].dealNumber = _dealNumber;
dealNumbers[_dealNumber] = newIndex;
signs[newIndex].signBuyer = 0x0;
signs[newIndex].signSeller = 0x0;
signs[newIndex].finishSignSeller = 0x0;
signs[newIndex].finishSignBuyer = 0x0;
signs[newIndex].finishSignSigner = 0x0;
}
/**
* @dev function for sign deal by buyer and for transfer money (call after sign seller only)
* @param _dealNumber (deal number)
*/
function signBuyer(uint _dealNumber) public payable{
uint deal = dealNumbers[_dealNumber];
//If sign of buyer is mpty and sender it is buyer for this deal
require(signs[deal].signBuyer == 0x0 && msg.sender == deals[deal].buyer);
require(signs[deal].signSeller == deals[deal].seller);
//Check, value of tx need >= summ of deal
//TODO: need change maker!!!!
require(deals[deal].sum == msg.value);
signs[deal].signBuyer = msg.sender;
deals[deal].balance = msg.value;
deals[deal].status = statuses.signed;
}
/**
* @dev function for sign deal by seller (in start and before buyer)
* @param _dealNumber (deal number)
*/
function signSeller(uint _dealNumber) public {
uint deal = dealNumbers[_dealNumber];
//If sign of seller is empty and sender it is seller for this deal
require(signs[deal].signSeller == 0x0 && msg.sender == deals[deal].seller);
signs[deal].signSeller = msg.sender;
}
// Agency sign
/* function signAgency(uint _dealNumber) onlyAgency public {
uint deal = dealNumbers[_dealNumber];
//If sign of Agency is empty and sender it is agency for this deal
require(deals[deal].signAgency == 0x0);
deals[deal].signAgency = msg.sender;
}*/
/**
* @dev function for buyer (for mmoney refund after time of the deal)
* @param _dealNumber (deal number)
*/
function refund(uint _dealNumber) public{
uint deal = dealNumbers[_dealNumber];
require(now > deals[deal].date && deals[deal].balance > 0 && msg.sender == deals[deal].buyer);
deals[deal].buyer.transfer(deals[deal].balance);
deals[deal].balance = 0;
}
/**
* @dev function for sign in end of the deal (for finis need 2 sign from 3)
* @param _dealNumber (deal number)
*/
function finishDeal(uint _dealNumber) public{
uint deal = dealNumbers[_dealNumber];
require(deals[deal].balance > 0 && deals[deal].status == statuses.signed );
//SIGNING.....
if(msg.sender == deals[deal].buyer){
signs[deal].finishSignBuyer = msg.sender;
}
if(msg.sender == deals[deal].seller){
signs[deal].finishSignSeller = msg.sender;
}
if(msg.sender ==deals[deal].signer){
signs[deal].finishSignSigner = msg.sender;
}
//////////////////////////
uint signCount = 0;
if(deals[deal].buyer == signs[deal].finishSignBuyer){
signCount++;
}
if(deals[deal].seller == signs[deal].finishSignSeller){
signCount++;
}
if(deals[deal].signer == signs[deal].finishSignSigner){
signCount++;
}
if(signCount >= 2){
//transfer fund to seller
deals[deal].seller.transfer(deals[deal].sum - deals[deal].fee);
emit MoneyTransfer(this,deals[deal].seller,deals[deal].sum-deals[deal].fee);
//transer fund to agency (fee)
agencyReceiver.transfer(deals[deal].fee);
emit MoneyTransfer(this,agencyReceiver,deals[deal].fee);
deals[deal].balance = 0;
deals[deal].status = statuses.finished;
deals[deal].atClosed = now;
}
}
/**
* @dev function for cancel deal (accessable ony for signer of current deal)
* @param _dealNumber (deal number)
*/
function cancelDeal(uint _dealNumber) onlySigner(_dealNumber) public{
uint deal = dealNumbers[_dealNumber];
require(deals[deal].balance > 0 && deals[deal].status == statuses.signed);
deals[deal].buyer.transfer(deals[deal].balance);
emit MoneyTransfer(this,deals[deal].buyer,deals[deal].balance);
deals[deal].balance = 0;
deals[deal].status = statuses.canceled;
deals[deal].atClosed = now;
}
}
|
Get all signs of deal by _dealNumber _dealNumber - uniq number of deal/
|
function getSigns(uint _dealNumber) constant public returns (
address signBuyer,
address signSeller,
address finishSignBuyer,
address finishSignSeller,
address finishSignSigner){
uint deal = dealNumbers[_dealNumber];
return (
signs[deal].signBuyer,
signs[deal].signSeller,
signs[deal].finishSignBuyer,
signs[deal].finishSignSeller,
signs[deal].finishSignSigner
);
}
| 7,216,463
|
pragma solidity >=0.4.4;
import 'truffle/Assert.sol';
import "../contracts/Token.sol";
import "../contracts/Common.sol";
contract Person {
Token token;
function Person(address _token) {
token = Token(_token);
}
function transfer(address to, uint value) returns (bool) {
return token.transfer(to, value);
}
function approve(address spender, uint value) returns (bool) {
return token.approve(spender, 100);
}
function transferFrom(address from, address to, uint value)
returns (bool) {
return token.transferFrom(from, to, value);
}
function burn(uint value) returns (bool) {
return token.burn(value);
}
}
contract ICO {
Token token;
function ICO(address _token) {
token = Token(_token);
}
function mint(address a, uint value) {
token.mint(a, value);
}
}
contract TokenTest is EventDefinitions {
Token token;
ICO ico;
ICO controller;
Person p1;
Person p2;
Person p3;
address a1;
address a2;
address a3;
function setUp() {
token = new Token();
ico = new ICO(token);
controller = new ICO(token);
token.setICO(ico);
token.setController(controller);
p1 = new Person(token);
p2 = new Person(token);
p3 = new Person(token);
a1 = address(p1);
a2 = address(p2);
a3 = address(p3);
ico.mint(address(p1), 1000);
ico.mint(address(p2), 1000);
ico.mint(address(p3), 1000);
}
function testSupply() {
Assert.equal(token.totalSupply(), 3000, "total supply");
}
function testTransfer() {
// expectEventsExact(token); // i did it
Transfer(a1, a2, 200);
p1.transfer(a2, 200);
Assert.equal(token.balanceOf(a1), 800, "p1 balance");
Assert.equal(token.balanceOf(a2), 1200, "p2 balance");
}
function testTransferAll() {
// expectEventsExact(token); //i did it
Transfer(a1, a2, 1000);
Transfer(a2, a1, 2000);
p1.transfer(a2, 1000);
Assert.equal(token.balanceOf(a1), 0, "p1 balance");
Assert.equal(token.balanceOf(a2), 2000, "p2 balance");
p2.transfer(a1, 2000);
Assert.equal(token.balanceOf(a1), 2000, "p1 balance 2");
Assert.equal(token.balanceOf(a2), 0, "p2 balance 2");
}
function testTransferFrom() {
// expectEventsExact(token);// i did it
Approval(a1, a2, 100);
Transfer(a1, a3, 50);
p1.approve(a2, 100);
Assert.equal(token.allowance(a1, a2), 100, "allowance");
p2.transferFrom(a1, a3, 50);
Assert.equal(token.balanceOf(a1), 950, "p1 balance");
Assert.equal(token.balanceOf(a3), 1050, "p3 balance");
Assert.equal(token.allowance(a1, a2), 50, "new allowance");
}
function testTransferFrom2() {
// expectEventsExact(token); //i did it
Transfer(a3, a1, 1000);
Approval(a1, a2, 100);
Transfer(a1, a3, 50);
p3.transfer(a1, 1000);
Assert.equal(token.balanceOf(a3), 0, "p1 balance");
Assert.equal(token.balanceOf(a1), 2000, "p2 balance");
p1.approve(a2, 100);
Assert.equal(token.allowance(a1, a2), 100, "allowance");
p2.transferFrom(a1, a3, 50);
Assert.equal(token.balanceOf(a1), 1950, "p1 balance");
Assert.equal(token.balanceOf(a3), 50, "p3 balance");
Assert.equal(token.allowance(a1, a2), 50, "new allowance");
}
/* older tests when threw instead of returning false
function testThrowTransfer() {
expectEventsExact(token);
p1.transfer(address(p2), 1001);
}
function testThrowTransferFrom() {
expectEventsExact(token);
Approval(a1, a2, 100);
p1.approve(a2, 100);
Assert.equal(token.allowance(a1, a2), 100, "allowance");
p2.transferFrom(a1, a3, 200);
}
function testThrowTransferFrom2() {
Assert.equal(token.allowance(a1, a2), 0, "allowance");
p2.transferFrom(a1, a3, 200);
}
*/
function testBadTransfer() {
uint initialbal = token.balanceOf(a1);
bool result = p1.transfer(a2, 1001);
Assert.equal(result, false, "result");
Assert.equal(initialbal, token.balanceOf(a1), "balance");
}
function testBadTransferFrom() {
// expectEventsExact(token); //i did it
Approval(a1, a2, 100);
uint initialbal = token.balanceOf(a1);
p1.approve(a2, 100);
Assert.equal(token.allowance(a1, a2), 100, "allowance");
bool result = p2.transferFrom(a1, a3, 200);
Assert.equal(result, false, "result");
Assert.equal(initialbal, token.balanceOf(a1), "balance");
}
function testBadTransferFrom2() {
uint initialbal = token.balanceOf(a1);
Assert.equal(token.allowance(a1, a2), 0, "allowance");
bool result = p2.transferFrom(a1, a3, 200);
Assert.equal(result, false, "result");
Assert.equal(initialbal, token.balanceOf(a1), "balance");
}
//this function initially passed without throw
//but actually we want to throw for now
//we don't want people to burn with the current placeholder tokenHolder
//so, changed the placeholder so it returns false causing throw
//and changed this test to pass if it throws
function testThrowsBurn() {
address th = address(new TokenHolder());
token.setTokenHolder(th);
uint firstbal = token.balanceOf(address(p1));
uint firstsupply = token.totalSupply();
bool result = p1.burn(3);
Assert.equal(token.balanceOf(address(p1)), firstbal - 3, "burned bal");
Assert.equal(token.totalSupply(), firstsupply - 3, "burned supply");
Assert.equal(result, true, "burn result");
}
function testThrowsSetTokenHolder() {
address th = address(new TokenHolder());
token.setTokenHolder(th);
token.lockTokenHolder();
token.setTokenHolder(0x1);
}
}
|
older tests when threw instead of returning false
|
function testThrowTransfer() {
expectEventsExact(token);
p1.transfer(address(p2), 1001);
}
| 2,518,975
|
./partial_match/1/0x1bDC2A3711f8F8EFCD038718b5e85Bc19E23bB97/sources/AVENGERS.sol
|
Triggers stopped state. Requirements: - The contract must not be paused./
|
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
| 2,604,415
|
/**
*Submitted for verification at Etherscan.io on 2022-01-05
*/
// SPDX-License-Identifier: Unlicensed
//He who has the spirit of the warrior has wealth.
//Web: http://www.ghosturai.com/
//TG: https://t.me/Ghosturai
//Twitter: https://twitter.com/GhosturaiETH
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 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(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 Ghosturai is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0x170ED1822d17C29E2499a3285d70Df60205FB8aD);
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;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
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 earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude 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("Ghosturai", "Ghosturai") {
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 = 4;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 8;
uint256 _sellMarketingFee = 4;
uint256 _sellLiquidityFee = 3;
uint256 _sellDevFee = 8;
uint256 _earlySellLiquidityFee = 3;
uint256 _earlySellMarketingFee = 4;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn
maxWallet = totalSupply * 10 / 1000; // 1% maxWallet
swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // 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;
launchedAt = block.number;
}
// 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;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// 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, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
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 blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 1) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 2;
sellMarketingFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 2;
sellMarketingFee = 2;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
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("Ghosturai", "Ghosturai") {
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 = 4;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 8;
uint256 _sellMarketingFee = 4;
uint256 _sellLiquidityFee = 3;
uint256 _sellDevFee = 8;
uint256 _earlySellLiquidityFee = 3;
uint256 _earlySellMarketingFee = 4;
uint256 totalSupply = 1 * 1e12 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
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);
| 7,669,243
|
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
mapping(address => uint256) private authorizedCallers; // Addresses that can access this contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint256 public constant PARTICIPATION_FUND = 10 ether;
uint256 public constant INSURANCE_PAY_LIMIT = 1 ether;
struct AirlineStatus {
bool registered;
bool participated;
uint256 funded;
}
struct Airlines {
mapping (address => address[]) airlineVotes;
mapping (address => AirlineStatus) airlineStatus;
uint256 count;
}
Airlines private airlines;
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
struct Passenger {
mapping(bytes32 => uint256) boughtFlightInsurance;
uint256 flightInsuranceCredit;
}
mapping(address => Passenger) private passengers;
address[] private passengerAddresses;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
address firstAirline
)
public
{
contractOwner = msg.sender;
airlines.count = 1;
airlines.airlineStatus[firstAirline].registered = true;
airlines.airlineStatus[firstAirline].participated = 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" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the "ExternallyOwnedAccount" account to be the function caller
*/
modifier requireExternallyOwnedAccount()
{
require(msg.sender == tx.origin, "Contracts not allowed");
_;
}
/**
* @dev Modifier that requires the "authorized" account to be the function caller
*/
modifier isCallerAuthorized()
{
require(authorizedCallers[msg.sender] == 1, "Caller is not authorized");
_;
}
/**
* @dev Modifier that checks the airline registration prerequisites
*/
modifier isAirlineNotRegisteredAndFunded(address fundAirline, address registerAirline)
{
require(!airlines.airlineStatus[registerAirline].registered, "airline is already registered");
require(airlines.airlineStatus[fundAirline].participated, "the caller airline has not paid participation fee.");
_;
}
/**
* @dev Modifier that checks the flight registration prerequisites
*/
modifier isAirlineRegisteredAndFunded(address fundAirline, address registerAirline)
{
require(airlines.airlineStatus[registerAirline].registered, "airline is not registered yet.");
require(airlines.airlineStatus[fundAirline].participated, "the caller airline has not paid participation fee.");
_;
}
/**
* @dev Modifier that checks the airline registration requirements
*/
modifier canRegisterAirline(address airline)
{
if (airlines.count >= 4) {
bool isDuplicate = false;
for(uint c=0; c<airlines.airlineVotes[airline].length; c++) {
if (airlines.airlineVotes[airline][c] == tx.origin) {
isDuplicate = true;
break;
}
}
require(!isDuplicate, "the caller airline has already voted for passed in airline.");
}
_;
}
/**
* @dev Modifier that checks the passenger buy insurance requirements
*/
modifier isFlightRegistered(
address airline,
string flight,
uint256 timestamp
)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
require(flights[flightKey].isRegistered, "Flight is not registered yet.");
_;
}
/**
* @dev Modifier that checks the flight registration requirements
*/
modifier canRegisterFlight(
address airline,
string flight,
uint256 timestamp
)
{
require(!flights[getFlightKey(airline, flight, timestamp)].isRegistered, "flight is already registered");
require(timestamp > block.timestamp, "flight must be in future");
_;
}
/**
* @dev Modifier that checks the airline funding
*/
modifier canFund()
{
require(airlines.airlineStatus[tx.origin].registered, "airline is not registered");
require(!airlines.airlineStatus[tx.origin].participated, "airline has already participated");
require(airlines.airlineStatus[tx.origin].funded + msg.value <= PARTICIPATION_FUND, "Airline over funded the surety");
require(tx.origin.balance >= 0 ether, "airline must have enough balance");
_;
}
/**
* @dev Modifier that checks the flight insurance buy
*/
modifier canBuy(
address airline,
string flight,
uint256 timestamp
)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
require(passengers[tx.origin].boughtFlightInsurance[flightKey] + msg.value <= INSURANCE_PAY_LIMIT, "Passenger overbought the insurance.");
require(tx.origin.balance >= 0 ether, "Passenger must have some balance to buy.");
_;
}
/**
* @dev Modifier that checks the insurance credit payout
*/
modifier canPay()
{
require(passengers[tx.origin].flightInsuranceCredit > 0, "Passenger should not get credit payout.");
require(address(this).balance >= passengers[tx.origin].flightInsuranceCredit, "Contract address has insufficient balance.");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function authorizeCaller(
address dataContract
)
external
requireContractOwner
{
authorizedCallers[dataContract] = 1;
}
function deauthorizeCaller(
address dataContract
)
external
requireContractOwner
{
authorizedCallers[dataContract] = 0;
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address airline
)
external
requireIsOperational
isCallerAuthorized
isAirlineNotRegisteredAndFunded(tx.origin, airline)
canRegisterAirline(airline)
returns(bool, uint256)
{
bool success;
uint256 votes;
if (airlines.count < 4) {
airlines.airlineStatus[airline].registered = true;
airlines.airlineVotes[airline].push(tx.origin);
success = true;
votes = airlines.airlineVotes[airline].length;
airlines.count = airlines.count.add(1);
} else {
airlines.airlineVotes[airline].push(tx.origin);
if (airlines.airlineVotes[airline].length < airlines.count.div(2)) {
success = false;
votes = airlines.airlineVotes[airline].length;
} else {
airlines.airlineStatus[airline].registered = true;
success = true;
votes = airlines.airlineVotes[airline].length;
airlines.count = airlines.count.add(1);
}
}
return (success, votes);
}
function isAirline
(
address airline
)
external
view
returns(bool)
{
return airlines.airlineStatus[airline].registered;
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight
(
address airline,
string flight,
uint256 timestamp
)
external
requireIsOperational
isAirlineRegisteredAndFunded(airline, airline)
canRegisterFlight(airline, flight, timestamp)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey] = Flight(true, STATUS_CODE_UNKNOWN, timestamp, airline);
}
function getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev View flight status for DApps
*
*/
function viewFlightStatus
(
address airline,
string flight,
uint256 timestamp
)
view
external
isFlightRegistered(airline, flight, timestamp)
returns(uint8)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
return flights[flightKey].statusCode;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
address airline,
string flight,
uint256 timestamp
)
external
requireIsOperational
requireExternallyOwnedAccount
isFlightRegistered(airline, flight, timestamp)
canBuy(airline, flight, timestamp)
payable
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
passengers[tx.origin].boughtFlightInsurance[flightKey] += msg.value;
passengerAddresses.push(tx.origin);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address airline,
string flight,
uint256 timestamp
)
public
requireIsOperational
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
for(uint c=0; c<passengerAddresses.length; c++) {
Passenger storage passenger = passengers[passengerAddresses[c]];
if (passenger.boughtFlightInsurance[flightKey] > 0) {
// credit 1.5x insurance amount
passenger.flightInsuranceCredit += passenger.boughtFlightInsurance[flightKey].mul(3).div(2);
passenger.boughtFlightInsurance[flightKey] = 0;
}
}
}
/**
* @dev Process flight status data changes
*/
function processFlightStatus
(
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
external
requireIsOperational
isFlightRegistered(airline, flight, timestamp)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey].updatedTimestamp = timestamp;
flights[flightKey].statusCode = statusCode;
if (statusCode == STATUS_CODE_LATE_AIRLINE) {
creditInsurees(airline, flight, timestamp);
}
}
/**
* @dev Get insuree's credit
*/
function getInsureeCredit
(
)
external
view
returns (uint256)
{
return passengers[tx.origin].flightInsuranceCredit;
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
)
external
canPay
requireIsOperational
requireExternallyOwnedAccount
{
uint256 credit = passengers[tx.origin].flightInsuranceCredit;
passengers[tx.origin].flightInsuranceCredit = 0;
tx.origin.transfer(credit);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
canFund
requireIsOperational
requireExternallyOwnedAccount
payable
{
airlines.airlineStatus[tx.origin].funded += msg.value;
if (airlines.airlineStatus[tx.origin].funded == PARTICIPATION_FUND) {
airlines.airlineStatus[tx.origin].participated = true;
}
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
|
Process flight status data changes/
|
function processFlightStatus
(
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
external
requireIsOperational
isFlightRegistered(airline, flight, timestamp)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey].updatedTimestamp = timestamp;
flights[flightKey].statusCode = statusCode;
if (statusCode == STATUS_CODE_LATE_AIRLINE) {
creditInsurees(airline, flight, timestamp);
}
}
| 12,991,127
|
./full_match/43113/0x8B83afE5278863e68287ba184604dF0F86d2c10D/sources/FarmManager_flat.sol
|
Stops the given farm's emissions and refunds any leftover reward token(s) to the msg.sender.
|
function stopEmission(address farmAddress) external checkOwnership(farmAddress) {
IFarmingRewards(farmAddress).stopEmission(msg.sender);
}
| 7,131,771
|
//Address: 0x94249cbca4036c381e2a7ce4f64278146ba7d483
//Contract name: TTGCoin
//Balance: 0 Ether
//Verification Date: 6/10/2018
//Transacion Count: 8
// CODE STARTS HERE
pragma solidity ^0.4.2;
//import "./SafeMathLib.sol";
/**
* Safe unsigned safe math.
*
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli
*
* Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol
*
* Maintained here until merged to mainline zeppelin-solidity.
*
*/
library SafeMathLib {
function times(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function plus(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c>=a);
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
require(b > 0);
uint c = a / b;
require(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c>=a && c>=b);
return c;
}
}
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function allowance(address owner, address spender) public constant returns (uint);
function transfer(address to, uint value) public returns (bool ok);
function transferFrom(address from, address to, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal pure returns (uint) {
assert(b > 0);
uint c = a / b;
require(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
//function assert(bool assertion) internal pure{
// require (assertion);
//}
}
/**
* Standard ERC20 token with Short Hand Attack and approve() race condition mitigation.
*
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, SafeMath {
/* Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
/* Actual balances of token holders */
mapping(address => uint) balances;
/* approve() allowances */
mapping (address => mapping (address => uint)) allowed;
/* Interface declaration */
function isToken() public pure returns (bool weAre) {
return true;
}
/**
*
* Fix for the ERC20 short address attack
*
* http://vessenes.com/the-erc20-short-address-attack-explained/
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool success) {
require(_value >= 0);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
//requre the alloced greater than _value
require(_allowance >= _value);
require(_value >= 0);
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value)public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
//if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
/* Util */
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
}
/*
* Ownable
*
* Base contract with an owner.
* Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
*/
contract Ownable {
address public owner;
mapping (address => bool) private admins;
mapping (address => bool) private developers;
mapping (address => bool) private founds;
function Ownable() internal{
owner = msg.sender;
}
modifier onlyAdmins(){
require(admins[msg.sender]);
_;
}
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
function getOwner() view public returns (address){
return owner;
}
function isDeveloper () view internal returns (bool) {
return developers[msg.sender];
}
function isFounder () view internal returns (bool){
return founds[msg.sender];
}
function addDeveloper (address _dev) onlyOwner() public {
developers[_dev] = true;
}
function removeDeveloper (address _dev) onlyOwner() public {
delete developers[_dev];
}
function addFound (address _found) onlyOwner() public {
founds[_found] = true;
}
function removeFound (address _found) onlyOwner() public {
delete founds[_found];
}
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* Define interface for distrible the token
*/
contract DistributeToken is StandardToken, Ownable{
event AirDrop(address from, address to, uint amount);
event CrowdDistribute(address from, address to, uint amount);
using SafeMathLib for uint;
/* The finalizer contract that allows Distribute token */
// address public distAgent;
mapping (address => bool) private distAgents;
uint private maxAirDrop = 1000*10**18;//need below 1000 TTG
uint private havedAirDrop = 0;
uint public totalAirDrop = 0; //totalSupply * 5%
bool public finishCrowdCoin = false;
uint private havedCrowdCoin = 0;
uint public totalCrowdCoin = 0; //totalSupply * 50%
uint private havedDistDevCoin = 0;
uint public totalDevCoin = 0; //totalSupply * 20%
uint private havedDistFoundCoin = 0;
uint public totalFoundCoin = 0; //totalSupply * 20%
/**
* 0:1:100000;1:1:50000 2:1:25000 3:1:12500 4:1:12500
*/
uint private crowState = 0;//
/**
* .
*/
function setDistributeAgent(address addr, bool enabled) onlyOwner public {
require(addr != address(0));
// We don't do interface check here as we might want to a normal wallet address to act as a release agent
distAgents[addr] = enabled;
}
function setTotalAirDrop(uint Amount) onlyOwner public {
// We don't do interface check here as we might want to a normal wallet address to act as a release agent
totalAirDrop = Amount;
}
/** The function can be called only by a whitelisted release agent. */
modifier onlyDistributeAgent() {
require(distAgents[msg.sender] == true) ;
_;
}
/* Withdraw */
/*
NOTICE: These functions withdraw the ETH which remained in the contract account when user call CrowdDistribute
*/
function withdrawAll () onlyOwner() public {
owner.transfer(this.balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
function distributeToFound(address receiver, uint amount) onlyOwner() public returns (uint actual){
require((amount+havedDistFoundCoin) < totalFoundCoin);
balances[owner] = balances[owner].sub(amount);
balances[receiver] = balances[receiver].plus(amount);
havedDistFoundCoin = havedDistFoundCoin.plus(amount);
addFound(receiver);
// This will make the mint transaction apper in EtherScan.io
// We can remove this after there is a standardized minting event
emit Transfer(0, receiver, amount);
return amount;
}
function distributeToDev(address receiver, uint amount) onlyOwner() public returns (uint actual){
require((amount+havedDistDevCoin) < totalDevCoin);
balances[owner] = balances[owner].sub(amount);
balances[receiver] = balances[receiver].plus(amount);
havedDistDevCoin = havedDistDevCoin.plus(amount);
addDeveloper(receiver);
// This will make the mint transaction apper in EtherScan.io
// We can remove this after there is a standardized minting event
emit Transfer(0, receiver, amount);
return amount;
}
function airDrop(address transmitter, address receiver, uint amount) public returns (uint actual){
require(receiver != address(0));
require(amount <= maxAirDrop);
require((amount+havedAirDrop) < totalAirDrop);
require(distAgents[msg.sender] == true);
balances[owner] = balances[owner].sub(amount);
balances[receiver] = balances[receiver].plus(amount);
havedAirDrop = havedAirDrop.plus(amount);
// This will make the mint transaction apper in EtherScan.io
// We can remove this after there is a standardized minting event
emit AirDrop(0, receiver, amount);
return amount;
}
function crowdDistribution() payable public returns (uint actual) {
require(msg.sender != address(0));
require(!isContract(msg.sender));
require(msg.value != 0);
require(totalCrowdCoin > havedCrowdCoin);
require(finishCrowdCoin == false);
uint actualAmount = calculateCrowdAmount(msg.value);
require(actualAmount != 0);
havedCrowdCoin = havedCrowdCoin.plus(actualAmount);
balances[owner] = balances[owner].sub(actualAmount);
balances[msg.sender] = balances[msg.sender].plus(actualAmount);
switchCrowdState();
// This will make the mint transaction apper in EtherScan.io
// We can remove this after there is a standardized minting event
emit CrowdDistribute(0, msg.sender, actualAmount);
return actualAmount;
}
function switchCrowdState () internal{
if (havedCrowdCoin < totalCrowdCoin.mul(10).div(100) ){
crowState = 0;
}else if (havedCrowdCoin < totalCrowdCoin.mul(20).div(100) ){
crowState = 1;
} else if (havedCrowdCoin < totalCrowdCoin.mul(30).div(100) ){
crowState = 2;
} else if (havedCrowdCoin < totalCrowdCoin.mul(40).div(100) ){
crowState = 3;
} else if (havedCrowdCoin < totalCrowdCoin.mul(50).div(100) ){
crowState = 4;
}
if (havedCrowdCoin >= totalCrowdCoin) {
finishCrowdCoin = true;
}
}
function calculateCrowdAmount (uint _price) internal view returns (uint _crow) {
if (crowState == 0) {
return _price.mul(50000);
}
else if (crowState == 1) {
return _price.mul(30000);
} else if (crowState == 2) {
return _price.mul(20000);
} else if (crowState == 3) {
return _price.mul(15000);
} else if (crowState == 4) {
return _price.mul(10000);
}
return 0;
}
}
/**
* Define interface for releasing the token transfer after a successful crowdsale.
*/
contract ReleasableToken is ERC20, Ownable {
/* The finalizer contract that allows unlift the transfer limits on this token */
address public releaseAgent;
/** A TTG contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/
bool public released = false;
uint private maxTransferForDev = 40000000*10**18;
uint private maxTransferFoFounds= 20000000*10**18;
uint private maxTransfer = 0;//other user is not limited.
/** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */
mapping (address => bool) public transferAgents;
/**
* Limit token transfer until the crowdsale is over.
*
*/
modifier canTransfer(address _sender, uint _value) {
//if owner can Transfer all the time
if(_sender != owner){
if(isDeveloper()){
require(_value < maxTransferForDev);
}else if(isFounder()){
require(_value < maxTransferFoFounds);
}else if(maxTransfer != 0){
require(_value < maxTransfer);
}
if(!released) {
require(transferAgents[_sender]);
}
}
_;
}
function setMaxTranferLimit(uint dev, uint found, uint other) onlyOwner public {
require(dev < totalSupply);
require(found < totalSupply);
require(other < totalSupply);
maxTransferForDev = dev;
maxTransferFoFounds = found;
maxTransfer = other;
}
/**
* Set the contract that can call release and make the token transferable.
*
* Design choice. Allow reset the release agent to fix fat finger mistakes.
*/
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
// We don't do interface check here as we might want to a normal wallet address to act as a release agent
releaseAgent = addr;
}
/**
* Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period.
*/
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
/**
* One way function to release the tokens to the wild.
*
* Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached).
*/
function releaseTokenTransfer() public onlyReleaseAgent {
released = true;
}
/** The function can be called only before or after the tokens have been releasesd */
modifier inReleaseState(bool releaseState) {
require(releaseState == released);
_;
}
/** The function can be called only by a whitelisted release agent. */
modifier onlyReleaseAgent() {
require(msg.sender == releaseAgent);
_;
}
function transfer(address _to, uint _value) public canTransfer(msg.sender,_value) returns (bool success) {
// Call StandardToken.transfer()
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public canTransfer(_from,_value) returns (bool success) {
// Call StandardToken.transferForm()
return super.transferFrom(_from, _to, _value);
}
}
contract RecycleToken is StandardToken, Ownable {
using SafeMathLib for uint;
/**
* recycle user token to owner account
*
*/
function recycle(address from, uint amount) onlyAdmins public {
require(from != address(0));
require(balances[from] >= amount);
balances[owner] = balances[owner].add(amount);
balances[from] = balances[from].sub(amount);
// This will make the mint transaction apper in EtherScan.io
// We can remove this after there is a standardized minting event
emit Transfer(from, owner, amount);
}
}
/**
* A token that can increase its supply by another contract.
*
* This allows uncapped crowdsale by dynamically increasing the supply when money pours in.
* Only mint agents, contracts whitelisted by owner, can mint new tokens.
*
*/
contract MintableToken is StandardToken, Ownable {
using SafeMathLib for uint;
bool public mintingFinished = false;
/** List of agents that are allowed to create new tokens */
mapping (address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state );
/**
* Create new tokens and allocate them to an address..
*
* Only callably by a crowdsale contract (mint agent).
*/
function mint(address receiver, uint amount) onlyMintAgent canMint public {
//totalsupply is not changed, send amount TTG to receiver from owner account.
balances[owner] = balances[owner].sub(amount);
balances[receiver] = balances[receiver].plus(amount);
// This will make the mint transaction apper in EtherScan.io
// We can remove this after there is a standardized minting event
emit Transfer(0, receiver, amount);
}
/**
* Owner can allow a crowdsale contract to mint new tokens.
*/
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
emit MintingAgentChanged(addr, state);
}
modifier onlyMintAgent() {
// Only crowdsale contracts are allowed to mint new tokens
require(mintAgents[msg.sender]);
_;
}
function enableMint() onlyOwner public {
mintingFinished = false;
}
/** Make sure we are not done yet. */
modifier canMint() {
require(!mintingFinished);
_;
}
}
/**
* A crowdsaled token.
*
* An ERC-20 token designed specifically for crowdsales with investor protection and further development path.
*
* - The token transfer() is disabled until the crowdsale is over
* - The token contract gives an opt-in upgrade path to a new contract
* - The same token can be part of several crowdsales through approve() mechanism
* - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens)
*
*/
contract TTGCoin is ReleasableToken, MintableToken , DistributeToken, RecycleToken{
/** Name and symbol were updated. */
event UpdatedTokenInformation(string newName, string newSymbol);
string public name;
string public symbol;
uint public decimals;
/**
* Construct the token.
*
* This token must be created through a team multisig wallet, so that it is owned by that wallet.
*
*/
function TTGCoin() public {
// Create any address, can be transferred
// to team multisig via changeOwner(),
owner = msg.sender;
addAdmin(owner);
name = "TotalGame Coin";
symbol = "TTG";
totalSupply = 2000000000*10**18;
decimals = 18;
// Create initially all balance on the team multisig
balances[msg.sender] = totalSupply;
//Mint feature is not allow now
mintingFinished = true;
//Set the distribute totaltoken strategy
totalAirDrop = totalSupply.mul(10).div(100);
totalCrowdCoin = totalSupply.mul(50).div(100);
totalDevCoin = totalSupply.mul(20).div(100);
totalFoundCoin = totalSupply.mul(20).div(100);
emit Minted(owner, totalSupply);
}
/**
* When token is released to be transferable, enforce no new tokens can be created.
*/
function releaseTokenTransfer() public onlyReleaseAgent {
super.releaseTokenTransfer();
}
/**
* Owner can update token information here.
*
* It is often useful to conceal the actual token association, until
* the token operations, like central issuance or reissuance have been completed.
*
* This function allows the token owner to rename the token after the operations
* have been completed and then point the audience to use the token contract.
*/
function setTokenInformation(string _name, string _symbol) public onlyOwner {
name = _name;
symbol = _symbol;
emit UpdatedTokenInformation(name, symbol);
}
function getTotalSupply() public view returns (uint) {
return totalSupply;
}
function tokenName() public view returns (string _name) {
return name;
}
}
|
This will make the mint transaction apper in EtherScan.io We can remove this after there is a standardized minting event
|
function distributeToDev(address receiver, uint amount) onlyOwner() public returns (uint actual){
require((amount+havedDistDevCoin) < totalDevCoin);
balances[owner] = balances[owner].sub(amount);
balances[receiver] = balances[receiver].plus(amount);
havedDistDevCoin = havedDistDevCoin.plus(amount);
addDeveloper(receiver);
emit Transfer(0, receiver, amount);
return amount;
}
| 12,790,925
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "../utils/AuthorizableU.sol";
import "../token/XJoyToken.sol";
contract JoyPresale is ContextUpgradeable, AuthorizableU {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
////////////////////////////////////////////////////////////////////////
// State variables
////////////////////////////////////////////////////////////////////////
// Info of each coin like USDT, USDC
struct CoinInfo {
address addr;
uint256 rate;
}
// Info of each Vesting
struct VestingInfo {
uint8 initClaimablePercent; // Init Claimable Percent
uint256 lockingDuration; // Locking Duration
uint256 vestingDuration; // Vesting Duration
}
// Info of each Purchaser
struct UserInfo {
uint8 vestingIndex; // Index of VestingInfo
uint256 depositedAmount; // How many Coins amount the user has deposited.
uint256 purchasedAmount; // How many JOY tokens the user has purchased.
uint256 withdrawnAmount; // Withdrawn amount
uint256 firstDepositedTime; // Last Deposited time
uint256 lastWithdrawnTime; // Last Withdrawn time
}
// The JOY Token
IERC20Upgradeable public govToken;
// The xJOY Token
IERC20Upgradeable public xGovToken;
// treasury addresses
address[] public treasuryAddrs;
uint16 public treasuryIndex;
// Coin Info list
CoinInfo[] public coinList;
uint8 public COIN_DECIMALS;
// Vesting Info
VestingInfo[] public vestingList; // 0: Seed, 1: Presale A
uint8 public VESTING_INDEX;
// Sale flag and time.
bool public SALE_FLAG;
uint256 public SALE_START;
uint256 public SALE_DURATION;
// GovToken public flag
bool public GOVTOKEN_PUBLIC_FLAG;
// User address => UserInfo
mapping(address => UserInfo) public userList;
address[] public userAddrs;
// total tokens amounts (all 18 decimals)
uint256 public totalSaleAmount;
uint256 public totalSoldAmount;
uint256 public totalCoinAmount;
////////////////////////////////////////////////////////////////////////
// Events & Modifiers
////////////////////////////////////////////////////////////////////////
// Events.
event TokensPurchased(address indexed purchaser, uint256 coinAmount, uint256 tokenAmount);
event TokensWithdrawed(address indexed purchaser, uint256 tokenAmount);
// Modifiers.
modifier whenSale() {
require(checkSalePeriod(), "This is not sale period.");
_;
}
modifier whenVesting(address userAddr) {
require(checkVestingPeriod(userAddr), "This is not vesting period.");
_;
}
////////////////////////////////////////////////////////////////////////
// Initialization functions
////////////////////////////////////////////////////////////////////////
function initialize(
IERC20Upgradeable _govToken,
IERC20Upgradeable _xGovToken,
uint256 _totalSaleAmount,
CoinInfo[] memory _coinList,
VestingInfo[] memory _vestingList
) public virtual initializer
{
__Context_init();
__Authorizable_init();
addAuthorized(_msgSender());
govToken = _govToken;
xGovToken = _xGovToken;
treasuryAddrs.push(_msgSender());
treasuryIndex = 0;
COIN_DECIMALS = 18;
setCoinList(_coinList);
setVestingList(_vestingList);
VESTING_INDEX = 0;
startSale(false);
updateSaleDuration(60 days);
setGovTokenPublicFlag(false);
updateTotalSaleAmount(_totalSaleAmount);
}
////////////////////////////////////////////////////////////////////////
// External functions
////////////////////////////////////////////////////////////////////////
// Update token
function updateTokens(IERC20Upgradeable _govToken, IERC20Upgradeable _xGovToken) public onlyAuthorized {
govToken = _govToken;
xGovToken = _xGovToken;
}
// Update the treasury address
function updateTreasuryAddrs(address[] memory _treasuryAddrs) public onlyAuthorized {
delete treasuryAddrs;
for (uint i=0; i<_treasuryAddrs.length; i++) {
treasuryAddrs.push(_treasuryAddrs[i]);
}
treasuryIndex = 0;
}
function updateTreasuryIndex(uint16 _treasuryIndex) public onlyAuthorized {
treasuryIndex = _treasuryIndex;
if (treasuryAddrs.length > 0 && treasuryIndex >= treasuryAddrs.length) {
treasuryIndex = 0;
}
}
// Set coin list
function setCoinList(CoinInfo[] memory _coinList) public onlyAuthorized {
delete coinList;
for (uint i=0; i<_coinList.length; i++) {
coinList.push(_coinList[i]);
}
}
// Update coin info
function updateCoinInfo(uint8 index, address addr, uint256 rate) public onlyAuthorized {
coinList[index] = CoinInfo(addr, rate);
}
// Set vesting list
function setVestingList(VestingInfo[] memory _vestingList) public onlyAuthorized {
delete vestingList;
for (uint i=0; i<_vestingList.length; i++) {
vestingList.push(_vestingList[i]);
}
}
function setVestingIndex(uint8 index) public onlyAuthorized {
VESTING_INDEX = index;
}
// Update vesting info
function updateVestingInfo(uint8 index, uint8 _initClaimablePercent, uint256 _lockingDuration, uint256 _vestingDuration) public onlyAuthorized {
vestingList[index] = VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration);
}
// Start stop sale
function startSale(bool bStart) public onlyAuthorized {
SALE_FLAG = bStart;
if (bStart) {
SALE_START = block.timestamp;
}
}
// Set GovToken public flag
function setGovTokenPublicFlag(bool bFlag) public onlyAuthorized {
GOVTOKEN_PUBLIC_FLAG = bFlag;
}
// Update sale duration
function updateSaleDuration(uint256 saleDuration) public onlyAuthorized {
SALE_DURATION = saleDuration;
}
// check sale period
function checkSalePeriod() public view returns (bool) {
return SALE_FLAG && block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(SALE_DURATION);
}
// check locking period
function checkLockingPeriod(address userAddr) public view returns (bool) {
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
// return block.timestamp >= SALE_START && block.timestamp <= SALE_START.add(vestingInfo.lockingDuration);
return block.timestamp >= userInfo.firstDepositedTime && block.timestamp <= userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
}
// check vesting period
function checkVestingPeriod(address userAddr) public view returns (bool) {
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
// uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration);
// return block.timestamp >= VESTING_START;
uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
return GOVTOKEN_PUBLIC_FLAG || block.timestamp >= VESTING_START;
}
// Update total sale amount
function updateTotalSaleAmount(uint256 amount) public onlyAuthorized {
totalSaleAmount = amount;
}
// Get user addrs
function getUserAddrs() public view returns (address[] memory) {
address[] memory returnData = new address[](userAddrs.length);
for (uint i=0; i<userAddrs.length; i++) {
returnData[i] = userAddrs[i];
}
return returnData;
}
// Get user's vesting info
function getUserVestingInfo(address userAddr) public view returns (VestingInfo memory) {
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = vestingList[userInfo.vestingIndex];
return vestingInfo;
}
// Set User Info
function setUserInfo(address _addr, uint8 _vestingIndex, uint256 _depositedAmount, uint256 _purchasedAmount, uint256 _withdrawnAmount) public onlyAuthorized {
UserInfo storage userInfo = userList[_addr];
if (userInfo.depositedAmount == 0) {
userAddrs.push(_addr);
userInfo.vestingIndex = _vestingIndex;
userInfo.firstDepositedTime = block.timestamp;
userInfo.depositedAmount = 0;
userInfo.purchasedAmount = 0;
userInfo.withdrawnAmount = 0;
} else {
totalCoinAmount = totalCoinAmount.sub(Math.min(totalCoinAmount, userInfo.depositedAmount));
totalSoldAmount = totalSoldAmount.sub(Math.min(totalSoldAmount, userInfo.purchasedAmount));
}
totalCoinAmount = totalCoinAmount.add(_depositedAmount);
totalSoldAmount = totalSoldAmount.add(_purchasedAmount);
userInfo.depositedAmount = userInfo.depositedAmount.add(_depositedAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(_purchasedAmount);
userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(_withdrawnAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_addr);
}
// Seed User List
function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner {
for (uint i=0; i<_userAddrs.length; i++) {
setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount);
if (_transferToken) {
xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount);
}
}
}
function seedUser(address _userAddr, uint256 _depositedAmount, uint256 _purchasedAmount, bool _transferToken) public onlyOwner {
setUserInfo(_userAddr, VESTING_INDEX, _depositedAmount, _purchasedAmount, 0);
if (_transferToken) {
xGovToken.safeTransfer(_userAddr, _purchasedAmount);
}
}
// Deposit
// coinAmount (decimals: COIN_DECIMALS)
function deposit(uint256 _coinAmount, uint8 coinIndex) external whenSale {
require( totalSaleAmount >= totalSoldAmount, "totalSaleAmount >= totalSoldAmount");
CoinInfo memory coinInfo = coinList[coinIndex];
IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr);
// calculate token amount to be transferred
(uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex);
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
// if the token amount is less than remaining
if (availableTokenAmount < tokenAmount) {
tokenAmount = availableTokenAmount;
(_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex);
}
// validate purchasing
_preValidatePurchase(_msgSender(), tokenAmount, coinAmount, coinIndex);
// transfer coin and token
coin.safeTransferFrom(_msgSender(), address(this), coinAmount);
xGovToken.safeTransfer(_msgSender(), tokenAmount);
// transfer coin to treasury
if (treasuryAddrs.length != 0) {
coin.safeTransfer(treasuryAddrs[treasuryIndex], coinAmount);
}
// update global state
totalCoinAmount = totalCoinAmount.add(_coinAmount);
totalSoldAmount = totalSoldAmount.add(tokenAmount);
// update purchased token list
UserInfo storage userInfo = userList[_msgSender()];
if (userInfo.depositedAmount == 0) {
userAddrs.push(_msgSender());
userInfo.vestingIndex = VESTING_INDEX;
userInfo.firstDepositedTime = block.timestamp;
}
userInfo.depositedAmount = userInfo.depositedAmount.add(_coinAmount);
userInfo.purchasedAmount = userInfo.purchasedAmount.add(tokenAmount);
emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount);
XJoyToken _xJoyToken = XJoyToken(address(xGovToken));
_xJoyToken.addPurchaser(_msgSender());
}
// Withdraw
function withdraw() external whenVesting(_msgSender()) {
uint256 withdrawalAmount = calcWithdrawalAmount(_msgSender());
uint256 govTokenAmount = govToken.balanceOf(address(this));
uint256 xGovTokenAmount = xGovToken.balanceOf(address(_msgSender()));
uint256 withdrawAmount = Math.min(withdrawalAmount, Math.min(govTokenAmount, xGovTokenAmount));
require(withdrawAmount > 0, "No withdraw amount!");
require(xGovToken.allowance(_msgSender(), address(this)) >= withdrawAmount, "withdraw's allowance is low!");
xGovToken.safeTransferFrom(_msgSender(), address(this), withdrawAmount);
govToken.safeTransfer(_msgSender(), withdrawAmount);
UserInfo storage userInfo = userList[_msgSender()];
userInfo.withdrawnAmount = userInfo.withdrawnAmount.add(withdrawAmount);
userInfo.lastWithdrawnTime = block.timestamp;
emit TokensWithdrawed(_msgSender(), withdrawAmount);
}
// Calc token amount by coin amount
function calcWithdrawalAmount(address userAddr) public view returns (uint256) {
require(checkVestingPeriod(userAddr), "This is not vesting period.");
UserInfo memory userInfo = userList[userAddr];
VestingInfo memory vestingInfo = getUserVestingInfo(userAddr);
// uint256 VESTING_START = SALE_START.add(vestingInfo.lockingDuration);
uint256 VESTING_START = userInfo.firstDepositedTime.add(vestingInfo.lockingDuration);
uint256 totalAmount = 0;
if (block.timestamp <= VESTING_START) {
totalAmount = userInfo.purchasedAmount.mul(vestingInfo.initClaimablePercent).div(100);
} else if (block.timestamp >= VESTING_START.add(vestingInfo.vestingDuration)) {
totalAmount = userInfo.purchasedAmount;
} else {
totalAmount = userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(vestingInfo.vestingDuration);
}
uint256 withdrawalAmount = totalAmount.sub(userInfo.withdrawnAmount);
return withdrawalAmount;
}
// Calc token amount by coin amount
function calcTokenAmount(uint256 _coinAmount, uint8 coinIndex) public view returns (uint256, uint256) {
require( coinList.length > coinIndex, "coinList.length > coinIndex");
CoinInfo memory coinInfo = coinList[coinIndex];
ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr);
uint256 rate = coinInfo.rate;
uint tokenDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS;
uint256 tokenAmount = _coinAmount
.mul(10**tokenDecimal)
.div(rate);
uint coinDecimal = COIN_DECIMALS - coin.decimals();
uint256 coinAmount = _coinAmount
.div(10**coinDecimal);
return (tokenAmount, coinAmount);
}
// Calc coin amount by token amount
function calcCoinAmount(uint256 _tokenAmount, uint8 coinIndex) public view returns (uint256, uint256) {
require( coinList.length > coinIndex, "coinList.length > coinIndex");
CoinInfo memory coinInfo = coinList[coinIndex];
ERC20Upgradeable coin = ERC20Upgradeable(coinInfo.addr);
uint256 rate = coinInfo.rate;
uint _coinDecimal = ERC20Upgradeable(address(xGovToken)).decimals() + coin.decimals() - COIN_DECIMALS;
uint256 _coinAmount = _tokenAmount
.div(10**_coinDecimal)
.mul(rate);
uint coinDecimal = COIN_DECIMALS - coin.decimals();
uint256 coinAmount = _coinAmount
.div(10**coinDecimal);
return (_coinAmount, coinAmount);
}
// Calc max coin amount to be deposit
function calcMaxCoinAmountToBeDeposit(uint8 coinIndex) public view returns (uint256) {
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
(uint256 _coinAmount,) = calcCoinAmount(availableTokenAmount, coinIndex);
return _coinAmount;
}
// Withdraw all coins by owner
function withdrawAllCoins(address treasury) public onlyOwner {
for (uint i=0; i<coinList.length; i++) {
CoinInfo memory coinInfo = coinList[i];
IERC20Upgradeable _coin = IERC20Upgradeable(coinInfo.addr);
uint256 coinAmount = _coin.balanceOf(address(this));
_coin.safeTransfer(treasury, coinAmount);
}
}
// Withdraw all xJOY by owner
function withdrawAllxGovTokens(address treasury) public onlyOwner {
uint256 tokenAmount = xGovToken.balanceOf(address(this));
xGovToken.safeTransfer(treasury, tokenAmount);
}
// Withdraw all $JOY by owner
function withdrawAllGovTokens(address treasury) public onlyOwner {
uint256 tokenAmount = govToken.balanceOf(address(this));
govToken.safeTransfer(treasury, tokenAmount);
}
////////////////////////////////////////////////////////////////////////
// Internal functions
////////////////////////////////////////////////////////////////////////
// Validate purchase
function _preValidatePurchase(address purchaser, uint256 tokenAmount, uint256 coinAmount, uint8 coinIndex) internal view {
require( coinList.length > coinIndex, "coinList.length > coinIndex");
CoinInfo memory coinInfo = coinList[coinIndex];
IERC20Upgradeable coin = IERC20Upgradeable(coinInfo.addr);
require(purchaser != address(0), "Purchaser is the zero address");
require(coinAmount != 0, "Coin amount is 0");
require(tokenAmount != 0, "Token amount is 0");
require(xGovToken.balanceOf(address(this)) >= tokenAmount, "$xJoyToken amount is lack!");
require(coin.balanceOf(msg.sender) >= coinAmount, "Purchaser's coin amount is lack!");
require(coin.allowance(msg.sender, address(this)) >= coinAmount, "Purchaser's allowance is low!");
this;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library 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) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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.6;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract AuthorizableU is OwnableUpgradeable {
////////////////////////////////////////////////////////////////////////
// State variables
////////////////////////////////////////////////////////////////////////
mapping(address => bool) public isAuthorized;
////////////////////////////////////////////////////////////////////////
// Events & Modifiers
////////////////////////////////////////////////////////////////////////
event AddedAuthorized(address _user);
event RemovedAuthorized(address _user);
modifier onlyAuthorized() {
require(isAuthorized[msg.sender] || owner() == msg.sender, "caller is not authorized");
_;
}
////////////////////////////////////////////////////////////////////////
// Initialization functions
////////////////////////////////////////////////////////////////////////
function __Authorizable_init() internal virtual initializer {
__Ownable_init();
}
////////////////////////////////////////////////////////////////////////
// External functions
////////////////////////////////////////////////////////////////////////
function addAuthorized(address _toAdd) public onlyOwner {
isAuthorized[_toAdd] = true;
emit AddedAuthorized(_toAdd);
}
function removeAuthorized(address _toRemove) public onlyOwner {
require(_toRemove != msg.sender);
isAuthorized[_toRemove] = false;
emit RemovedAuthorized(_toRemove);
}
////////////////////////////////////////////////////////////////////////
// Internal functions
////////////////////////////////////////////////////////////////////////
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./BlackListToken.sol";
contract XJoyToken is BlackListToken {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
////////////////////////////////////////////////////////////////////////
// State variables
////////////////////////////////////////////////////////////////////////
uint256 public manualMinted;
////////////////////////////////////////////////////////////////////////
// Events & Modifiers
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Initialization functions
////////////////////////////////////////////////////////////////////////
function initialize(
string memory name,
string memory symbol,
uint256 initialSupply
) public virtual initializer {
__ERC20_init(name, symbol);
__BlackList_init();
_mint(_msgSender(), initialSupply);
addAuthorized(_msgSender());
manualMinted = 0;
}
////////////////////////////////////////////////////////////////////////
// External functions
////////////////////////////////////////////////////////////////////////
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(address _from, uint256 _amount) public onlyOwner {
_burn(_from, _amount);
}
function manualMint(address _to, uint256 _amount) public onlyAuthorized {
_mint(_to, _amount);
manualMinted = manualMinted.add(_amount);
}
// add purchaser
function addPurchaser(address addr) public onlyAuthorized {
addBlackList(addr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
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.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../utils/AuthorizableU.sol";
contract BlackListToken is ERC20Upgradeable, AuthorizableU {
////////////////////////////////////////////////////////////////////////
// State variables
////////////////////////////////////////////////////////////////////////
bool public isBlackListChecking;
mapping (address => bool) public isBlackListed; // for from address
mapping (address => bool) public isWhiteListed; // for to address
////////////////////////////////////////////////////////////////////////
// Events & Modifiers
////////////////////////////////////////////////////////////////////////
event SetBlackList(address[] _users, bool _status);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
event SetWhiteList(address[] _users, bool _status);
event AddedWhiteList(address _user);
event RemovedWhiteList(address _user);
modifier whenTransferable(address _from, address _to) {
require(isTransferable(_from, _to), "[email protected]: transfer isn't allowed");
_;
}
////////////////////////////////////////////////////////////////////////
// Initialization functions
////////////////////////////////////////////////////////////////////////
function __BlackList_init() internal virtual initializer {
__Authorizable_init();
isBlackListChecking = true;
}
////////////////////////////////////////////////////////////////////////
// External functions
////////////////////////////////////////////////////////////////////////
function startBlackList(bool _status) public onlyAuthorized {
isBlackListChecking = _status;
}
// Blacklist
function setBlackList(address[] memory _addrs, bool _status) public onlyAuthorized {
for (uint256 i; i < _addrs.length; ++i) {
isBlackListed[_addrs[i]] = _status;
}
emit SetBlackList(_addrs, _status);
}
function addBlackList(address _toAdd) public onlyAuthorized {
isBlackListed[_toAdd] = true;
emit AddedBlackList(_toAdd);
}
function removeBlackList(address _toRemove) public onlyAuthorized {
isBlackListed[_toRemove] = false;
emit RemovedBlackList(_toRemove);
}
// Whitelist
function setWhiteList(address[] memory _addrs, bool _status) public onlyAuthorized {
for (uint256 i; i < _addrs.length; ++i) {
isWhiteListed[_addrs[i]] = _status;
}
emit SetWhiteList(_addrs, _status);
}
function addWhiteList(address _toAdd) public onlyAuthorized {
isWhiteListed[_toAdd] = true;
emit AddedWhiteList(_toAdd);
}
function removeWhiteList (address _toRemove) public onlyAuthorized {
isWhiteListed[_toRemove] = false;
emit RemovedWhiteList(_toRemove);
}
function isTransferable(address _from, address _to) public view returns (bool) {
if (isBlackListChecking) {
// require(!isBlackListed[_from], "[email protected]: _from is in isBlackListed");
// require(!isBlackListed[_to] || isWhiteListed[_to], "[email protected]: _to is in isBlackListed");
require(!isBlackListed[_from] || isWhiteListed[_to], "[email protected]: _from is in isBlackListed");
}
return true;
}
////////////////////////////////////////////////////////////////////////
// Internal functions
////////////////////////////////////////////////////////////////////////
function _transfer(address _from, address _to, uint256 _amount) internal virtual override whenTransferable(_from, _to) {
super._transfer(_from, _to, _amount);
}
}
|
Update vesting info
|
function updateVestingInfo(uint8 index, uint8 _initClaimablePercent, uint256 _lockingDuration, uint256 _vestingDuration) public onlyAuthorized {
vestingList[index] = VestingInfo(_initClaimablePercent, _lockingDuration, _vestingDuration);
}
| 12,088,044
|
pragma solidity 0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// 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;
}
}
/**
* 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;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
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 exists(uint256 _tokenId) public view returns (bool _exists);
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 _data) public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721Holder is ERC721Receiver {
function onERC721Received(address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor() public {
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool) {
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId) internal {
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public canTransfer(_tokenId) {
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public pendingOwner;
address public manager;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Modifier throws if called by any account other than the manager.
*/
modifier onlyManager() {
require(msg.sender == manager);
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
constructor() public {
owner = msg.sender;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
/**
* @dev Sets the manager address.
* @param _manager The manager address.
*/
function setManager(address _manager) public onlyOwner {
require(_manager != address(0));
manager = _manager;
}
}
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract GeneralSecurityToken is SupportsInterfaceWithLookup, ERC721, ERC721BasicToken, Ownable {
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
// Token name
string public name_ = "GeneralSecurityToken";
// Token symbol
string public symbol_ = "GST";
uint public tokenIDCount = 0;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
struct Data{
string information;
string URL;
}
mapping(uint256 => Data) internal tokenData;
/**
* @dev Constructor function
*/
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev External function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
*/
function mint(address _to) external onlyManager {
_mint(_to, tokenIDCount++);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
function arrayOfTokensByAddress(address _holder) public view returns(uint256[]) {
return ownedTokens[_holder];
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are
// going to be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are
// first swapping the lastToken to the first position, and then dropping the element placed in the last
// position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
*/
function _mint(address _to, uint256 _id) internal {
allTokens.push(_id);
allTokensIndex[_id] = _id;
super._mint(_to, _id);
}
function addTokenData(uint _tokenId, string _information, string _URL) public {
require(ownerOf(_tokenId) == msg.sender);
tokenData[_tokenId].information = _information;
tokenData[_tokenId].URL = _URL;
}
function getTokenData(uint _tokenId) public view returns(string Liscence, string URL){
require(exists(_tokenId));
Liscence = tokenData[_tokenId].information;
URL = tokenData[_tokenId].URL;
}
function() payable{
require(msg.value > 0.16 ether);
_mint(msg.sender, tokenIDCount++);
}
}
|
Safely transfers the ownership of a given token ID to another address If the target address is a contract, it must implement `onERC721Received`, which is called upon a safe transfer, and return the magic value `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, the transfer is reverted. Requires the msg sender to be the owner, approved, or operator _from current owner of the token _to address to receive the ownership of the given token ID _tokenId uint256 ID of the token to be transferred/ solium-disable-next-line arg-overflow
|
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
safeTransferFrom(_from, _to, _tokenId, "");
}
| 7,750,104
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "../interfaces/IComitium.sol";
import "../libraries/LibComitiumStorage.sol";
import "../libraries/LibOwnership.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract ComitiumFacet {
using SafeMath for uint256;
uint256 constant public MAX_LOCK = 365 days;
uint256 constant BASE_MULTIPLIER = 1e18;
event Deposit(address indexed user, uint256 amount, uint256 newBalance);
event Withdraw(address indexed user, uint256 amountWithdrew, uint256 amountLeft);
event Lock(address indexed user, uint256 timestamp);
event Delegate(address indexed from, address indexed to);
event DelegatedPowerIncreased(address indexed from, address indexed to, uint256 amount, uint256 to_newDelegatedPower);
event DelegatedPowerDecreased(address indexed from, address indexed to, uint256 amount, uint256 to_newDelegatedPower);
function initComitium(address _fdt, address _rewards) public {
require(_fdt != address(0), "FDT address must not be 0x0");
LibComitiumStorage.Storage storage ds = LibComitiumStorage.comitiumStorage();
require(!ds.initialized, "Comitium: already initialized");
LibOwnership.enforceIsContractOwner();
ds.initialized = true;
ds.fdt = IERC20(_fdt);
ds.rewards = IRewards(_rewards);
}
// deposit allows a user to add more fdt to his staked balance
function deposit(uint256 amount) public {
require(amount > 0, "Amount must be greater than 0");
LibComitiumStorage.Storage storage ds = LibComitiumStorage.comitiumStorage();
uint256 allowance = ds.fdt.allowance(msg.sender, address(this));
require(allowance >= amount, "Token allowance too small");
// this must be called before the user's balance is updated so the rewards contract can calculate
// the amount owed correctly
if (address(ds.rewards) != address(0)) {
ds.rewards.registerUserAction(msg.sender);
}
uint256 newBalance = balanceOf(msg.sender).add(amount);
_updateUserBalance(ds.userStakeHistory[msg.sender], newBalance);
_updateLockedFdt(fdtStakedAtTs(block.timestamp).add(amount));
address delegatedTo = userDelegatedTo(msg.sender);
if (delegatedTo != address(0)) {
uint256 newDelegatedPower = delegatedPower(delegatedTo).add(amount);
_updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower);
emit DelegatedPowerIncreased(msg.sender, delegatedTo, amount, newDelegatedPower);
}
ds.fdt.transferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, amount, newBalance);
}
// withdraw allows a user to withdraw funds if the balance is not locked
function withdraw(uint256 amount) public {
require(amount > 0, "Amount must be greater than 0");
require(userLockedUntil(msg.sender) <= block.timestamp, "User balance is locked");
uint256 balance = balanceOf(msg.sender);
require(balance >= amount, "Insufficient balance");
LibComitiumStorage.Storage storage ds = LibComitiumStorage.comitiumStorage();
// this must be called before the user's balance is updated so the rewards contract can calculate
// the amount owed correctly
if (address(ds.rewards) != address(0)) {
ds.rewards.registerUserAction(msg.sender);
}
_updateUserBalance(ds.userStakeHistory[msg.sender], balance.sub(amount));
_updateLockedFdt(fdtStakedAtTs(block.timestamp).sub(amount));
address delegatedTo = userDelegatedTo(msg.sender);
if (delegatedTo != address(0)) {
uint256 newDelegatedPower = delegatedPower(delegatedTo).sub(amount);
_updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower);
emit DelegatedPowerDecreased(msg.sender, delegatedTo, amount, newDelegatedPower);
}
ds.fdt.transfer(msg.sender, amount);
emit Withdraw(msg.sender, amount, balance.sub(amount));
}
// lock a user's currently staked balance until timestamp & add the bonus to his voting power
function lock(uint256 timestamp) public {
require(timestamp > block.timestamp, "Timestamp must be in the future");
require(timestamp <= block.timestamp + MAX_LOCK, "Timestamp too big");
require(balanceOf(msg.sender) > 0, "Sender has no balance");
LibComitiumStorage.Storage storage ds = LibComitiumStorage.comitiumStorage();
LibComitiumStorage.Stake[] storage checkpoints = ds.userStakeHistory[msg.sender];
LibComitiumStorage.Stake storage currentStake = checkpoints[checkpoints.length - 1];
require(timestamp > currentStake.expiryTimestamp, "New timestamp lower than current lock timestamp");
_updateUserLock(checkpoints, timestamp);
emit Lock(msg.sender, timestamp);
}
function depositAndLock(uint256 amount, uint256 timestamp) public {
deposit(amount);
lock(timestamp);
}
// delegate allows a user to delegate his voting power to another user
function delegate(address to) public {
require(msg.sender != to, "Can't delegate to self");
uint256 senderBalance = balanceOf(msg.sender);
require(senderBalance > 0, "No balance to delegate");
LibComitiumStorage.Storage storage ds = LibComitiumStorage.comitiumStorage();
emit Delegate(msg.sender, to);
address delegatedTo = userDelegatedTo(msg.sender);
if (delegatedTo != address(0)) {
uint256 newDelegatedPower = delegatedPower(delegatedTo).sub(senderBalance);
_updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower);
emit DelegatedPowerDecreased(msg.sender, delegatedTo, senderBalance, newDelegatedPower);
}
if (to != address(0)) {
uint256 newDelegatedPower = delegatedPower(to).add(senderBalance);
_updateDelegatedPower(ds.delegatedPowerHistory[to], newDelegatedPower);
emit DelegatedPowerIncreased(msg.sender, to, senderBalance, newDelegatedPower);
}
_updateUserDelegatedTo(ds.userStakeHistory[msg.sender], to);
}
// stopDelegate allows a user to take back the delegated voting power
function stopDelegate() public {
return delegate(address(0));
}
// balanceOf returns the current FDT balance of a user (bonus not included)
function balanceOf(address user) public view returns (uint256) {
return balanceAtTs(user, block.timestamp);
}
// balanceAtTs returns the amount of FDT that the user currently staked (bonus NOT included)
function balanceAtTs(address user, uint256 timestamp) public view returns (uint256) {
LibComitiumStorage.Stake memory stake = stakeAtTs(user, timestamp);
return stake.amount;
}
// stakeAtTs returns the Stake object of the user that was valid at `timestamp`
function stakeAtTs(address user, uint256 timestamp) public view returns (LibComitiumStorage.Stake memory) {
LibComitiumStorage.Storage storage ds = LibComitiumStorage.comitiumStorage();
LibComitiumStorage.Stake[] storage stakeHistory = ds.userStakeHistory[user];
if (stakeHistory.length == 0 || timestamp < stakeHistory[0].timestamp) {
return LibComitiumStorage.Stake(block.timestamp, 0, block.timestamp, address(0));
}
uint256 min = 0;
uint256 max = stakeHistory.length - 1;
if (timestamp >= stakeHistory[max].timestamp) {
return stakeHistory[max];
}
// binary search of the value in the array
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (stakeHistory[mid].timestamp <= timestamp) {
min = mid;
} else {
max = mid - 1;
}
}
return stakeHistory[min];
}
// votingPower returns the voting power (bonus included) + delegated voting power for a user at the current block
function votingPower(address user) public view returns (uint256) {
return votingPowerAtTs(user, block.timestamp);
}
// votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time
function votingPowerAtTs(address user, uint256 timestamp) public view returns (uint256) {
LibComitiumStorage.Stake memory stake = stakeAtTs(user, timestamp);
uint256 ownVotingPower;
// if the user delegated his voting power to another user, then he doesn't have any voting power left
if (stake.delegatedTo != address(0)) {
ownVotingPower = 0;
} else {
uint256 balance = stake.amount;
uint256 multiplier = _stakeMultiplier(stake, timestamp);
ownVotingPower = balance.mul(multiplier).div(BASE_MULTIPLIER);
}
uint256 delegatedVotingPower = delegatedPowerAtTs(user, timestamp);
return ownVotingPower.add(delegatedVotingPower);
}
// fdtStaked returns the total raw amount of FDT staked at the current block
function fdtStaked() public view returns (uint256) {
return fdtStakedAtTs(block.timestamp);
}
// fdtStakedAtTs returns the total raw amount of FDT users have deposited into the contract
// it does not include any bonus
function fdtStakedAtTs(uint256 timestamp) public view returns (uint256) {
return _checkpointsBinarySearch(LibComitiumStorage.comitiumStorage().fdtStakedHistory, timestamp);
}
// delegatedPower returns the total voting power that a user received from other users
function delegatedPower(address user) public view returns (uint256) {
return delegatedPowerAtTs(user, block.timestamp);
}
// delegatedPowerAtTs returns the total voting power that a user received from other users at a point in time
function delegatedPowerAtTs(address user, uint256 timestamp) public view returns (uint256) {
return _checkpointsBinarySearch(LibComitiumStorage.comitiumStorage().delegatedPowerHistory[user], timestamp);
}
// same as multiplierAtTs but for the current block timestamp
function multiplierOf(address user) public view returns (uint256) {
return multiplierAtTs(user, block.timestamp);
}
// multiplierAtTs calculates the multiplier at a given timestamp based on the user's stake a the given timestamp
// it includes the decay mechanism
function multiplierAtTs(address user, uint256 timestamp) public view returns (uint256) {
LibComitiumStorage.Stake memory stake = stakeAtTs(user, timestamp);
return _stakeMultiplier(stake, timestamp);
}
// userLockedUntil returns the timestamp until the user's balance is locked
function userLockedUntil(address user) public view returns (uint256) {
LibComitiumStorage.Stake memory c = stakeAtTs(user, block.timestamp);
return c.expiryTimestamp;
}
// userDelegatedTo returns the address to which a user delegated their voting power; address(0) if not delegated
function userDelegatedTo(address user) public view returns (address) {
LibComitiumStorage.Stake memory c = stakeAtTs(user, block.timestamp);
return c.delegatedTo;
}
// _checkpointsBinarySearch executes a binary search on a list of checkpoints that's sorted chronologically
// looking for the closest checkpoint that matches the specified timestamp
function _checkpointsBinarySearch(LibComitiumStorage.Checkpoint[] storage checkpoints, uint256 timestamp) internal view returns (uint256) {
if (checkpoints.length == 0 || timestamp < checkpoints[0].timestamp) {
return 0;
}
uint256 min = 0;
uint256 max = checkpoints.length - 1;
if (timestamp >= checkpoints[max].timestamp) {
return checkpoints[max].amount;
}
// binary search of the value in the array
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].timestamp <= timestamp) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].amount;
}
// _stakeMultiplier calculates the multiplier for the given stake at the given timestamp
function _stakeMultiplier(LibComitiumStorage.Stake memory stake, uint256 timestamp) internal view returns (uint256) {
if (timestamp >= stake.expiryTimestamp) {
return BASE_MULTIPLIER;
}
uint256 diff = stake.expiryTimestamp - timestamp;
if (diff >= MAX_LOCK) {
return BASE_MULTIPLIER.mul(2);
}
return BASE_MULTIPLIER.add(diff.mul(BASE_MULTIPLIER).div(MAX_LOCK));
}
// _updateUserBalance manages an array of checkpoints
// if there's already a checkpoint for the same timestamp, the amount is updated
// otherwise, a new checkpoint is inserted
function _updateUserBalance(LibComitiumStorage.Stake[] storage checkpoints, uint256 amount) internal {
if (checkpoints.length == 0) {
checkpoints.push(LibComitiumStorage.Stake(block.timestamp, amount, block.timestamp, address(0)));
} else {
LibComitiumStorage.Stake storage old = checkpoints[checkpoints.length - 1];
if (old.timestamp == block.timestamp) {
old.amount = amount;
} else {
checkpoints.push(LibComitiumStorage.Stake(block.timestamp, amount, old.expiryTimestamp, old.delegatedTo));
}
}
}
// _updateUserLock updates the expiry timestamp on the user's stake
// it assumes that if the user already has a balance, which is checked for in the lock function
// then there must be at least 1 checkpoint
function _updateUserLock(LibComitiumStorage.Stake[] storage checkpoints, uint256 expiryTimestamp) internal {
LibComitiumStorage.Stake storage old = checkpoints[checkpoints.length - 1];
if (old.timestamp < block.timestamp) {
checkpoints.push(LibComitiumStorage.Stake(block.timestamp, old.amount, expiryTimestamp, old.delegatedTo));
} else {
old.expiryTimestamp = expiryTimestamp;
}
}
// _updateUserDelegatedTo updates the delegateTo property on the user's stake
// it assumes that if the user already has a balance, which is checked for in the delegate function
// then there must be at least 1 checkpoint
function _updateUserDelegatedTo(LibComitiumStorage.Stake[] storage checkpoints, address to) internal {
LibComitiumStorage.Stake storage old = checkpoints[checkpoints.length - 1];
if (old.timestamp < block.timestamp) {
checkpoints.push(LibComitiumStorage.Stake(block.timestamp, old.amount, old.expiryTimestamp, to));
} else {
old.delegatedTo = to;
}
}
// _updateDelegatedPower updates the power delegated TO the user in the checkpoints history
function _updateDelegatedPower(LibComitiumStorage.Checkpoint[] storage checkpoints, uint256 amount) internal {
if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].timestamp < block.timestamp) {
checkpoints.push(LibComitiumStorage.Checkpoint(block.timestamp, amount));
} else {
LibComitiumStorage.Checkpoint storage old = checkpoints[checkpoints.length - 1];
old.amount = amount;
}
}
// _updateLockedFdt stores the new `amount` into the FDT locked history
function _updateLockedFdt(uint256 amount) internal {
LibComitiumStorage.Storage storage ds = LibComitiumStorage.comitiumStorage();
if (ds.fdtStakedHistory.length == 0 || ds.fdtStakedHistory[ds.fdtStakedHistory.length - 1].timestamp < block.timestamp) {
ds.fdtStakedHistory.push(LibComitiumStorage.Checkpoint(block.timestamp, amount));
} else {
LibComitiumStorage.Checkpoint storage old = ds.fdtStakedHistory[ds.fdtStakedHistory.length - 1];
old.amount = amount;
}
}
}
|
balanceAtTs returns the amount of FDT that the user currently staked (bonus NOT included)
|
function balanceAtTs(address user, uint256 timestamp) public view returns (uint256) {
LibComitiumStorage.Stake memory stake = stakeAtTs(user, timestamp);
return stake.amount;
}
| 12,925,483
|
// 솔리디티 버전
pragma solidity ^0.4.24;
// 컨트랙트 생성 (클래스와 비슷한 느낌)
contract HelloWorld {
// 변수 선언(문자열: stirng 정수: uint(양수), int 주소: adress ))
// public 은 외부에서 호출 가능
string public greeting;
// 생성자
constructor(string _greeting) public {
greeting = _greeting;
}
// greeting 값을 지정해주는 메서드
function setGreeting(string _greeting) public {
greeting = _greeting;
}
// greeting 값 리턴해주는 메서드
function say() public constant returns(string) {
return greeting;
}
}
|
greeting 값 리턴해주는 메서드
|
function say() public constant returns(string) {
return greeting;
}
| 12,890,464
|
./partial_match/42/0x8856959E74D00eb21F673C2fB0dcFf16f17453dC/sources/MasterChef.sol
|
update reward vairables for pools. Be careful of gas spending!
|
function massUpdatePools() public{
if(block.number < stageOneDepositEndBlock){
stageOne.massUpdatePools();
}
else{
uint256 poolCountInRank = rankPoolIndex.length;
if(poolCountInRank > 0){
mintNTS(address(this), block.number);
}
for(uint256 i = 0; i < poolCountInRank; i ++){
updatePoolAccumulativeDividend(rankPoolIndex[i], poolCountInRank, block.number);
}
}
}
| 3,336,550
|
./partial_match/1/0xe904e50514C5EF0f4C15C9BA44D358eD38f5a024/sources/Governance.sol
|
Get the info of the updating incentive proposal./
|
function getInfoUpdateIncentive(bytes32 proposeId)
external
view
override
returns (address[] memory incentiveAddresses, uint256[] memory incentiveAllocation)
{
incentiveAddresses = _proposeUpdateIncentive[proposeId].incentiveAddresses;
incentiveAllocation = _proposeUpdateIncentive[proposeId].incentiveAllocation;
}
| 4,039,316
|
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/// @title $CROAK
/// @author @ryeshrimp
contract CROAK is ERC20, Ownable {
/// @notice a mapping from an address to whether or not it can mint / burn
mapping(address => bool) controllers;
/// @notice Mapping of addresses who have claimed tokens
mapping(address => bool) public hasClaimed;
bytes32 public merkleRoot;
bool claimPaused;
constructor(bytes32 _merkleRoot) ERC20("Croakens", "CROAK") {
controllers[msg.sender] = true;
merkleRoot = _merkleRoot;
}
/// @notice mints $CROAK to a recipient
/// @param to the recipient of the $CROAK
/// @param amount the amount of $CROAK to mint
function mint(address to, uint256 amount) external {
require(controllers[msg.sender], "Only controllers can mint");
_mint(to, amount);
}
/// @notice burns $CROAK from a holder
/// @param from the holder of the $CROAK
/// @param amount the amount of $CROAK to burn
function burn(address from, uint256 amount) external {
require(controllers[msg.sender], "Only controllers can burn");
_burn(from, amount);
}
/// @notice Allows claiming tokens if address is part of merkle tree
/// @param to address of claimee
/// @param amount of tokens owed to claimee
/// @param proof merkle proof to prove address and amount are in tree
function claim(address to, uint256 amount, bytes32[] calldata proof) external {
require(claimPaused == false, "Claim is paused");
// Throw if address has already claimed tokens
if (hasClaimed[to]) revert("Already claimed");
// Verify merkle proof, or revert if not in tree
bytes32 leaf = keccak256(abi.encodePacked(to, amount));
bool isValidLeaf = MerkleProof.verify(proof, merkleRoot, leaf);
if (!isValidLeaf) revert("Claim not found");
// Set address to claimed
hasClaimed[to] = true;
// Mint tokens to address
_mint(to, amount);
// Emit claim event
emit Claim(to, amount);
}
/// @notice Adds an address from controller
/// @dev This is used for contracts to burn/mint
function addController(address controller) external onlyOwner {
controllers[controller] = true;
}
/// @notice Removes an address from controller
/// @dev This is used for contracts to burn/mint
function removeController(address controller) external onlyOwner {
controllers[controller] = false;
}
/// @notice Sets the merkel root for token claim
function setRoot(bytes32 _merkleRoot) public onlyOwner {
merkleRoot = _merkleRoot;
}
/// @notice Sets the ability to pause the initial snapshot cliam of token
/// @param _value true or false
function setClaimPause(bool _value) public onlyOwner {
claimPaused = _value;
}
/// @notice Emitted after a successful token claim
/// @param to recipient of claim
/// @param amount of tokens claimed
event Claim(address indexed to, uint256 amount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// 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 (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
|
Allows claiming tokens if address is part of merkle tree to address of claimee amount of tokens owed to claimee proof merkle proof to prove address and amount are in tree Throw if address has already claimed tokens Verify merkle proof, or revert if not in tree Set address to claimed Mint tokens to address Emit claim event
|
function claim(address to, uint256 amount, bytes32[] calldata proof) external {
require(claimPaused == false, "Claim is paused");
if (hasClaimed[to]) revert("Already claimed");
bytes32 leaf = keccak256(abi.encodePacked(to, amount));
bool isValidLeaf = MerkleProof.verify(proof, merkleRoot, leaf);
if (!isValidLeaf) revert("Claim not found");
hasClaimed[to] = true;
_mint(to, amount);
emit Claim(to, amount);
}
| 11,687,860
|
//SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "../interfaces/IEternalFund.sol";
import "../interfaces/IEternalStorage.sol";
import "../interfaces/ITimelock.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title The Eternal Fund contract
* @author Taken from Compound Finance (COMP) and tweaked/detailed by Nobody (me)
* @notice The Eternal Fund serves as the governing body of Eternal
*/
contract EternalFund is IEternalFund, Context {
/////–––««« Variables: Interfaces and Addresses »»»––––\\\\\
// The name of this contract
string public constant name = "Eternal Fund";
// The keccak256 hash of the Eternal Token address
bytes32 public immutable entity;
// The timelock interface
ITimelock public timelock;
// The Eternal token interface
IERC20 public eternal;
// The Eternal storage interface
IEternalStorage public eternalStorage;
// The address of the Governor Guardian
address public guardian;
/////–––««« Variable: Voting »»»––––\\\\\
// The total number of proposals
uint256 public proposalCount;
// Holds all proposal data
struct Proposal {
uint256 id; // Unique id for looking up a proposal
address proposer; // Creator of the proposal
uint256 eta; // The timestamp that the proposal will be available for execution, set once the vote succeeds
address[] targets; // The ordered list of target addresses for calls to be made
uint256[] values; // The ordered list of values (i.e. msg.value) to be passed to the calls to be made
string[] signatures; // The ordered list of function signatures to be called
bytes[] calldatas; // The ordered list of calldata to be passed to each call
uint256 startTime; // The timestamp at which voting begins: holders must delegate their votes prior to this time
uint256 endTime; // The timestamp at which voting ends: votes must be cast prior to this block
uint256 startBlock; // The block at which voting began: holders must have delegated their votes prior to this block
uint256 forVotes; // Current number of votes in favor of this proposal
uint256 againstVotes; // Current number of votes in opposition to this proposal
bool canceled; // Flag marking whether the proposal has been canceled
bool executed; // Flag marking whether the proposal has been executed
mapping (address => Receipt) receipts; // Receipts of ballots for the entire set of voters
}
// Ballot receipt record for a voter
struct Receipt {
bool hasVoted; // Whether or not a vote has been cast
bool support; // Whether or not the voter supports the proposal
uint256 votes; // The number of votes the voter had, which were cast
}
// Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
// The official record of all proposals ever proposed
mapping (uint256 => Proposal) public proposals;
// The latest proposal for each proposer
mapping (address => uint256) public latestProposalIds;
/////–––««« Variables: Voting by signature »»»––––\\\\\
// The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
// The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/////–––««« Events »»»––––\\\\\
// Emitted when a new proposal is created
event ProposalCreated(uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startTime, uint256 endTime, string description);
// Emitted when the first vote is cast in a proposal
event StartBlockSet(uint256 proposalId, uint256 startBlock);
// Emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
// Emitted when a proposal has been canceled
event ProposalCanceled(uint256 id);
// Emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint256 id, uint256 eta);
// Emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint256 id);
/////–––««« Constructor »»»––––\\\\\
constructor (address _guardian, address _eternalStorage, address _eternal, address _timelock) {
guardian = _guardian;
eternalStorage = IEternalStorage(_eternalStorage);
eternal = IERC20(_eternal);
timelock = ITimelock(_timelock);
entity = keccak256(abi.encodePacked(_eternal));
}
/////–––««« Variable state-inspection functions »»»––––\\\\\
/**
* @notice The number of votes required in order for a voter to become a proposer.
* @return 0.5 percent of the initial supply
*/
function proposalThreshold() public pure returns (uint256) {
return 5 * (10 ** 7) * (10 ** 18); // 50 000 000ETRNL = initially 0.5% (increases over time due to deflation)
}
/**
* @notice View the maximum number of operations that can be included in a proposal.
* @return The maximum number of actions per proposal
*/
function proposalMaxOperations() public pure returns (uint256) {
return 15;
}
/**
* @notice View the delay before voting on a proposal may take place, once proposed.
* @return 1 day (in seconds)
*/
function votingDelay() public pure returns (uint256) {
return 1 days;
}
/**
* @notice The duration of voting on a proposal, in blocks.
* @return 3 days (in seconds)
*/
function votingPeriod() public pure returns (uint256) {
return 3 days;
}
/////–––««« Governance logic functions »»»––––\\\\\
/**
* @notice Initiates a proposal.
* @param targets An ordered list of contract addresses used to make the calls
* @param values A list of values passed in each call
* @param signatures A list of function signatures used to make the calls
* @param calldatas A list of function parameter hashes used to make the calls
* @param description A description of the proposal
* @return The current proposal count
*
* Requirements:
*
* - Proposer must have a voting balance equal to at least 0.5 percent of the initial ETRNL supply
* - All lists must have the same length
* - Lists must contain at least one element but no more than 15 elements
* - Proposer can only have one live proposal at a time
*/
function propose(address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint256) {
require(getPriorVotes(msg.sender, block.number - 1) > proposalThreshold(), "Vote balance below threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "Arity mismatch in proposal");
require(targets.length != 0, "Must provide actions");
require(targets.length <= proposalMaxOperations(), "Too many actions");
uint256 latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active && proposersLatestProposalState != ProposalState.Pending, "One live proposal per proposer");
}
uint256 startTime = block.timestamp + votingDelay();
uint256 endTime = block.timestamp + votingPeriod() + votingDelay();
proposalCount += 1;
proposals[proposalCount].id = proposalCount;
proposals[proposalCount].proposer = msg.sender;
proposals[proposalCount].eta = 0;
proposals[proposalCount].targets = targets;
proposals[proposalCount].values = values;
proposals[proposalCount].signatures = signatures;
proposals[proposalCount].calldatas = calldatas;
proposals[proposalCount].startTime = startTime;
proposals[proposalCount].startBlock = 0;
proposals[proposalCount].endTime = endTime;
proposals[proposalCount].forVotes = 0;
proposals[proposalCount].againstVotes = 0;
proposals[proposalCount].canceled = false;
proposals[proposalCount].executed = false;
latestProposalIds[msg.sender] = proposalCount;
emit ProposalCreated(proposalCount, msg.sender, targets, values, signatures, calldatas, startTime, endTime, description);
return proposalCount;
}
/**
* @notice Queues all of a given proposal's actions into the timelock contract.
* @param proposalId The id of the specified proposal
*
* Requirements:
*
* - The proposal needs to have passed
*/
function queue(uint256 proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "Proposal state must be Succeeded");
Proposal storage proposal = proposals[proposalId];
uint256 eta = block.timestamp + timelock.viewDelay();
for (uint256 i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
/**
* @notice Queues an individual proposal action into the timelock contract.
* @param target The address of the contract whose function is being called
* @param value The amount of AVAX being transferred in this transaction
* @param signature The function signature of this proposal's action
* @param data The function parameters of this proposal's action
* @param eta The estimated minimum UNIX time (in seconds) at which this transaction is to be executed
*
* Requirements:
*
* - The transaction should not have been queued
*/
function _queueOrRevert(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) private {
require(!timelock.queuedTransaction(keccak256(abi.encode(target, value, signature, data, eta))), "Proposal action already queued");
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes all of a given's proposal's actions.
* @param proposalId The id of the specified proposal
*
* Requirements:
*
* - The proposal must already be in queue
*/
function execute(uint256 proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "Proposal is not queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value: proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels all of a given proposal's actions.
* @param proposalId The id of the specified proposal
*
* Requirements:
*
* - The proposal should not have been executed
* - The proposer's vote balance should be below the threshold
*/
function cancel(uint proposalId) public {
ProposalState _state = state(proposalId);
require(_state != ProposalState.Executed, "Cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(getPriorVotes(proposal.proposer, block.number - 1) < proposalThreshold(), "Proposer above threshold");
proposal.canceled = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice View a given proposal's lists of actions.
* @param proposalId The id of the specified proposal
* @return targets The proposal's targets
* @return values The proposal's values
* @return signatures The proposal's signatures
* @return calldatas The proposal's calldatas
*/
function getActions(uint256 proposalId) public view returns (address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice View a given proposal's ballot receipt for a given voter.
* @param proposalId The id of the specified proposal
* @param voter The address of the specified voter
* @return The ballot receipt of that voter for the proposal
*/
function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice View the state of a given proposal.
* @param proposalId The id of the specified proposal
* @return The state of the proposal
*
* Requirements:
*
* - Proposal must exist
*/
function state(uint256 proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "Invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.timestamp <= proposal.startTime) {
return ProposalState.Pending;
} else if (block.timestamp <= proposal.endTime) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= proposal.eta + timelock.viewGracePeriod()) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Casts a vote for a given proposal.
* @param proposalId The id of the specified proposal
* @param support Whether the user is in support of the proposal or not
*/
function castVote(uint256 proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
/**
* @notice Casts a vote through signature.
* @param proposalId The id of teh specified proposal
* @param support Whether the user is in support of the proposal or not
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*
* Requirements:
*
* - Must be a valid signature
*/
function castVoteBySig(uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
uint chainId;
// solhint-disable-next-line no-inline-assembly
assembly { chainId := chainid() }
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), chainId, address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Invalid signature");
return _castVote(signatory, proposalId, support);
}
/**
* @notice Casts a vote for a given voter and proposal.
* @param voter The address of the specified voter
* @param proposalId The id of the specified proposal
* @param support Whether the voter is in support of the proposal or not
*
* Requirements:
*
* - Voting period for the proposal needs to be ongoing
* - The voter must not have already voted
*/
function _castVote(address voter, uint256 proposalId, bool support) private {
require(state(proposalId) == ProposalState.Active, "Voting is closed");
Proposal storage proposal = proposals[proposalId];
if (proposal.startBlock == 0) {
proposal.startBlock = block.number - 1;
emit StartBlockSet(proposalId, block.number);
}
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "Voter already voted");
uint256 votes = getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = proposal.forVotes + votes;
} else {
proposal.againstVotes = proposal.againstVotes + votes;
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
/**
* @notice Allow the Eternal Fund to take over control of the timelock contract.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __acceptFund() public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.acceptFund();
}
/**
* @notice Renounce the role of guardianship.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __abdicate() public {
require(msg.sender == guardian, "Caller must be the guardian");
guardian = address(0);
}
/**
* @notice Queues the transaction which will give governing power to the Eternal Fund.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
/**
* @notice Executes the transaction which will give governing power to the Eternal Fund.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
/////–––««« Governance-related functions »»»––––\\\\\
/**
* @notice Gets the current votes balance for a given account.
* @param account The address of the specified account
* @return The current number of votes of the account
*/
function getCurrentVotes(address account) public view override returns (uint256) {
uint256 nCheckpoints = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", account)));
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, nCheckpoints - 1)));
}
/**
* @notice Determine the number of votes of a given account prior to a given block.
* @param account The address of specified account
* @param blockNumber The number of the specified block
* @return The number of votes of the account before/by this block
*
* Requirements:
*
* - The given block must be finalized
*/
function getPriorVotes(address account, uint256 blockNumber) public view override returns (uint256) {
require(blockNumber < block.number, "Block is not yet finalized");
uint256 nCheckpoints = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", account)));
if (nCheckpoints == 0) {
// No checkpoints means no votes
return 0;
} else if (eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", account, nCheckpoints - 1))) <= blockNumber) {
// Votes for the most recent checkpoint
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, nCheckpoints - 1)));
} else if (eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", account, uint256(0)))) > blockNumber) {
// Only having checkpoints after the given block number means no votes
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
uint256 thisBlock = eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", account, center)));
if (thisBlock == blockNumber) {
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, center)));
} else if (thisBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, lower)));
}
/**
* @notice Delegates the message sender's vote balance to a given user.
* @param delegatee The address of the user to whom the vote balance is being added to
*/
function delegate(address delegatee) external override {
bytes32 _delegate = keccak256(abi.encodePacked("delegates", _msgSender()));
address currentDelegate = eternalStorage.getAddress(entity, _delegate);
uint256 delegatorBalance = eternal.balanceOf(_msgSender());
eternalStorage.setAddress(entity, _delegate, delegatee);
emit DelegateChanged(_msgSender(), currentDelegate, delegatee);
moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
/**
* @notice Transfer part of a given delegates' voting balance to another new delegate.
* @param srcRep The delegate from whom we are deducting votes
* @param dstRep The delegate to whom we are transferring votes
* @param amount The specified amount of votes
*/
function moveDelegates(address srcRep, address dstRep, uint256 amount) public override {
require(_msgSender() == address(this) || _msgSender() == address(eternal), "Only callable by Eternal");
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint256 srcRepNum = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", srcRep)));
uint256 srcRepOld = srcRepNum > 0 ? eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", srcRep, srcRepNum - 1))) : 0;
uint256 srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint256 dstRepNum = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", dstRep)));
uint256 dstRepOld = dstRepNum > 0 ? eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", dstRep, dstRepNum - 1))) : 0;
uint256 dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
/**
* @notice Update a given user's voting balance for the current block.
* @param delegatee The address of the specified user
* @param nCheckpoints The number of times the voting balance of the user has been updated
* @param oldVotes The old voting balance of the user
* @param newVotes The new voting balance of the user
*/
function _writeCheckpoint(address delegatee, uint256 nCheckpoints, uint256 oldVotes,uint256 newVotes) private {
if (nCheckpoints > 0 && eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", delegatee, nCheckpoints - 1))) == block.number) {
eternalStorage.setUint(entity, keccak256(abi.encodePacked("votes", delegatee, nCheckpoints - 1)), newVotes);
} else {
eternalStorage.setUint(entity, keccak256(abi.encodePacked("votes", delegatee, nCheckpoints)), newVotes);
eternalStorage.setUint(entity, keccak256(abi.encodePacked("blocks", delegatee, nCheckpoints)), block.number);
eternalStorage.setUint(entity, keccak256(abi.encodePacked("numCheckpoints", delegatee)), nCheckpoints + 1);
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
}
|
Queues the transaction which will give governing power to the Eternal Fund. Requirements: - Only callable by the current guardian/
|
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
| 12,810,518
|
./partial_match/1/0xa4906b8B98e47C3EEB5fa1427e9573bb5C882CA0/sources/ChadsUnite.sol
|
useful for buybacks or to reclaim any ETH on the contract in a way that helps holders. make the swap
|
function buyBackTokens() external payable {
uint256 amountInWei = msg.value;
require(amountInWei >= 0.002 ether, "less than default buyback amount");
address[] memory path = new address[](2);
path[0] = dexRouter.WETH();
path[1] = address(this);
uint256 beforeBal = balanceOf(operationsAddress);
path,
operationsAddress,
block.timestamp
);
uint256 afterBal = balanceOf(operationsAddress);
if (afterBal > beforeBal) {
super._transfer(operationsAddress, address(this), afterBal - beforeBal);
}
emit BuyBackTriggered(amountInWei);
}
| 16,100,427
|
pragma solidity ^0.4.18;
import 'zeppelin-solidity/contracts/token/ERC20.sol';
/***
* @title Channels
* @author Carlos Beltran <imthatcarlos@gmail.com>
*
* @dev Ethereum payment channels allow for off-chain transactions with an on-chain
* settlement. Parties open one channel with a deposit, continue to sign and verify
* transactions off-chain, and close the channel with one final transaction, on-chain.
* This implementation only allows for one active channel between two
* accounts, in one direction (Alice -> Bob && Bob -> Alice)
*/
contract TokenChannels {
//============================================================================
// EVENTS
//============================================================================
event ChannelOpened(bytes32 id);
event ChannelClosed(bytes32 id, uint withChallengePeriod);
event ChannelChallenged(bytes32 id, address by, uint value);
event ChannelFinalized(bytes32 id, address by, uint value);
//============================================================================
// STORAGE
//============================================================================
enum ChannelState { Open, Closing, Closed }
struct Channel {
address sender;
address recipient;
address token;
uint deposit;
uint challenge;
uint nonce;
uint closeTime;
uint value;
ChannelState state;
}
mapping (address => uint) balances;
mapping (bytes32 => Channel) channels;
mapping (address => mapping(address => bytes32)) activeIds;
//============================================================================
// MODIFIERS
//============================================================================
modifier validChannel(bytes32 id) {
require(channels[id].deposit != 0);
_;
}
modifier notClosed(bytes32 id) {
require(channels[id].state != ChannelState.Closed);
_;
}
modifier onlyParties(bytes32 id) {
require(msg.sender == channels[id].sender || msg.sender == channels[id].recipient);
_;
}
//============================================================================
// PUBLIC FUNCTIONS
//============================================================================
/**
* Open a new channel with the recipient. Require a non-zero message
*
* @param token Address of the token contract
* @param recipient Account address of the other party
* @param amount Number of tokens to send
* @param challenge Optional challenge period for either party to close the channel
*/
function openChannel(address token, address recipient, uint amount, uint challenge)
public
payable
{
// sanity checks
require(amount != 0 && amount == msg.value);
require(recipient != msg.sender);
require(activeIds[msg.sender][recipient] == bytes32(0));
// create a channel with the id being a hash of the data
bytes32 id = keccak256(msg.sender, recipient, now);
Channel memory newChannel;
newChannel.deposit = msg.value;
newChannel.sender = msg.sender;
newChannel.recipient = recipient;
newChannel.token = token;
newChannel.challenge = challenge;
newChannel.state = ChannelState.Open;
// make the deposit
ERC20 tokenObject = ERC20(token);
require(tokenObject.transferFrom(msg.sender, address(this), amount));
// add it to storage and lookup
channels[id] = newChannel;
activeIds[msg.sender][recipient] = id;
ChannelOpened(id);
}
/**
* Close a channel. Only the recipient can close it.
* The "value" is sent to the recipient and the rest refunded to the sender
*
* @param h signature with data = [id, message_hash, r, s]
* @param v Component of signature "h" from sender
* @param value Amount in wei to be sent
* @param nonce Number to be hashed with the value to form the message
*/
function closeChannel(bytes32[4] h, uint8 v, uint256 value, uint256 nonce)
public
notClosed(h[0])
{
Channel storage channel = channels[h[0]];
// only recipient may close
require(channel.recipient == msg.sender);
// validate signature data
require(verifyMsg(h, v, value));
if (channel.challenge == 0) {
// if there's no challenge period, close the channel
// pay the recipient and refund the remainder to the sender
ERC20 tokenObject = ERC20(channel.token);
require(tokenObject.transfer(channel.recipient, value));
require(tokenObject.transfer(channel.sender, (channel.deposit - value)));
// close the channel
channel.state = ChannelState.Closed;
// update the final value
channel.value = value;
// remove from lookup
delete activeIds[channel.sender][channel.recipient];
ChannelFinalized(h[0], msg.sender, channel.value);
} else {
// update the channel and allow challenges
channel.nonce = nonce;
channel.value = value;
channel.closeTime = now;
channel.state = ChannelState.Closing;
ChannelClosed(h[0], now + channel.challenge);
}
}
/**
* During the challenge period, either party can submit a proof that contains
* a higher nonce
*
* @param h signature with data = [id, message_hash, r, s]
* @param v Component of signature "h" from sender
* @param value Amount in wei to be sent
* @param nonce Number to be hashed with the value to form the message
*/
function challenge(bytes32[4] h, uint8 v, uint256 value, uint256 nonce)
public
validChannel(h[0])
notClosed(h[0])
onlyParties(h[0])
{
Channel storage channel = channels[h[0]];
// make sure we're in the challenge period
require(channel.closeTime + channel.challenge > now);
// make sure the nonce is higher
require(channel.nonce < nonce);
// validate signature data
require(verifyMsg(h, v, value));
// update the channel
channel.nonce = nonce;
channel.value = value;
ChannelChallenged(h[0], msg.sender, value);
}
/**
* After the challenge period passes, close the channel and disburse the funds
*
* @param id Channel id
*/
function finalize(bytes32 id)
public
validChannel(id)
notClosed(id)
onlyParties(id)
{
Channel storage channel = channels[id];
// make sure the challenge period is over
require(channel.closeTime + channel.challenge > now);
// pay the recipient and refund the remainder to the sender
ERC20 tokenObject = ERC20(channel.token);
require(tokenObject.transfer(channel.recipient, channel.value));
require(tokenObject.transfer(channel.sender, (channel.deposit - channel.value)));
// close the channel
channel.state = ChannelState.Closed;
// remove from lookup
delete activeIds[channel.sender][channel.recipient];
ChannelFinalized(id, msg.sender, channel.value);
}
/**
* Verify that the message sent is valid
* All messages must be signed by the channel sender
*
* @param h signature with data = [id, message_hash, r, s]
* @param v Component of signature "h" from sender
* @param value Amount in wei to be sent
*/
function verifyMsg(bytes32[4] h, uint8 v, uint value)
public
validChannel(h[0])
constant
returns (bool)
{
// testrpc and parity adds prefix when signing
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(prefix, h[1]);
address signer = ecrecover(prefixedHash, v, h[2], h[3]);
if (signer != channels[h[0]].sender) { return false; }
// TODO: can we verify hash message like this?
// validate that the hash is of the channel id and with the right value
/* bytes32 proof = keccak256(h[0], value);
proof = keccak256(prefix, proof);
if (proof != prefixedHash) { return false; } */
if (value > channels[h[0]].deposit) { return false; }
return true;
}
//============================================================================
// EXTERNAL FUNCTIONS
//============================================================================
function getChannelId(address sender, address recipient)
external
view
returns (bytes32)
{
return activeIds[sender][recipient];
}
function getChannel(bytes32 id)
external
validChannel(id)
view
returns (
address sender,
address recipient,
uint deposit,
address token,
ChannelState state,
uint value
)
{
Channel memory channel = channels[id];
sender = channel.sender;
recipient = channel.recipient;
deposit = channel.deposit;
token = channel.token;
state = channel.state;
value = channel.value;
}
function getChannelStatus(bytes32 id)
external
validChannel(id)
constant
returns (ChannelState)
{
return channels[id].state;
}
function getChannelRemainingChallengePeriod(bytes32 id)
external
validChannel(id)
constant
returns (uint)
{
if (channels[id].closeTime == 0) { return 0; }
else if (channels[id].closeTime + channels[id].challenge < now) { return 0; }
else { return (channels[id].closeTime + channels[id].challenge) - now; }
}
}
|
Open a new channel with the recipient. Require a non-zero message token Address of the token contract recipient Account address of the other party amount Number of tokens to send challenge Optional challenge period for either party to close the channel/ sanity checks create a channel with the id being a hash of the data make the deposit add it to storage and lookup
|
function openChannel(address token, address recipient, uint amount, uint challenge)
public
payable
{
require(amount != 0 && amount == msg.value);
require(recipient != msg.sender);
require(activeIds[msg.sender][recipient] == bytes32(0));
bytes32 id = keccak256(msg.sender, recipient, now);
Channel memory newChannel;
newChannel.deposit = msg.value;
newChannel.sender = msg.sender;
newChannel.recipient = recipient;
newChannel.token = token;
newChannel.challenge = challenge;
newChannel.state = ChannelState.Open;
ERC20 tokenObject = ERC20(token);
require(tokenObject.transferFrom(msg.sender, address(this), amount));
channels[id] = newChannel;
activeIds[msg.sender][recipient] = id;
ChannelOpened(id);
}
| 12,731,060
|
./full_match/4/0xa7b92AC2f431E9BDa86AA34bfaECC24ccf3d5468/sources/BancorNetwork.sol
|
allows the owner to register/unregister ether tokens _token ether token contract address _register true to register, false to unregister/
|
function registerEtherToken(IEtherToken _token, bool _register)
public
ownerOnly
validAddress(address(_token))
notThis(address(_token))
{
etherTokens[_token] = _register;
}
| 666,164
|
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY668() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF856(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER590(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE439(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE165(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM946(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER113(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL275(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER204() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA645() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED90(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER204();
emit OWNERSHIPTRANSFERRED90(address(0), _owner);
}
function OWNER726() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER38() { //inject NONSTANDARD NAMING
require(ISOWNER90(), "Ownable: caller is not the owner");
_;
}
function ISOWNER90() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER204() == _owner;
}
function RENOUNCEOWNERSHIP524() public ONLYOWNER38 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED90(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP660(address newOwner) public ONLYOWNER38 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP31(newOwner);
}
function _TRANSFEROWNERSHIP31(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED90(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY668() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF856(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER590(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER132(_MSGSENDER204(), recipient, amount);
return true;
}
function ALLOWANCE439(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE165(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE48(_MSGSENDER204(), spender, amount);
return true;
}
function TRANSFERFROM946(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER132(sender, recipient, amount);
_APPROVE48(sender, _MSGSENDER204(), _allowances[sender][_MSGSENDER204()].SUB641(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE241(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE48(_MSGSENDER204(), spender, _allowances[_MSGSENDER204()][spender].ADD348(addedValue));
return true;
}
function DECREASEALLOWANCE811(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE48(_MSGSENDER204(), spender, _allowances[_MSGSENDER204()][spender].SUB641(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER132(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB641(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD348(amount);
emit TRANSFER113(sender, recipient, amount);
}
function _MINT225(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD348(amount);
_balances[account] = _balances[account].ADD348(amount);
emit TRANSFER113(address(0), account, amount);
}
function _BURN186(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB641(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB641(amount);
emit TRANSFER113(account, address(0), amount);
}
function _APPROVE48(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL275(owner, spender, amount);
}
function _BURNFROM442(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN186(account, amount);
_APPROVE48(account, _MSGSENDER204(), _allowances[account][_MSGSENDER204()].SUB641(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME591() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL151() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS443() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD348(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB641(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB641(a, b, "SafeMath: subtraction overflow");
}
function SUB641(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL714(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV963(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV963(a, b, "SafeMath: division by zero");
}
function DIV963(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD537(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD537(a, b, "SafeMath: modulo by zero");
}
function MOD537(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT792(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE613(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE471(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER595(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.TRANSFER590.selector, to, value));
}
function SAFETRANSFERFROM895(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.TRANSFERFROM946.selector, from, to, value));
}
function SAFEAPPROVE173(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE439(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, value));
}
function SAFEINCREASEALLOWANCE700(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE439(address(this), spender).ADD348(value);
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE390(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE439(address(this), spender).SUB641(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN929(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT792(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface Controller {
function WITHDRAW362(address, uint) external; //inject NONSTANDARD NAMING
function BALANCEOF856(address) external view returns (uint); //inject NONSTANDARD NAMING
function EARN394(address, uint) external; //inject NONSTANDARD NAMING
function WANT709(address) external view returns (address); //inject NONSTANDARD NAMING
}
interface Aave {
function BORROW427(address _reserve, uint _amount, uint _interestRateModel, uint16 _referralCode) external; //inject NONSTANDARD NAMING
function SETUSERUSERESERVEASCOLLATERAL395(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING
function REPAY171(address _reserve, uint _amount, address payable _onBehalfOf) external payable; //inject NONSTANDARD NAMING
function GETUSERACCOUNTDATA396(address _user) //inject NONSTANDARD NAMING
external
view
returns (
uint totalLiquidityETH,
uint totalCollateralETH,
uint totalBorrowsETH,
uint totalFeesETH,
uint availableBorrowsETH,
uint currentLiquidationThreshold,
uint ltv,
uint healthFactor
);
function GETUSERRESERVEDATA201(address _reserve, address _user) //inject NONSTANDARD NAMING
external
view
returns (
uint currentATokenBalance,
uint currentBorrowBalance,
uint principalBorrowBalance,
uint borrowRateMode,
uint borrowRate,
uint liquidityRate,
uint originationFee,
uint variableBorrowIndex,
uint lastUpdateTimestamp,
bool usageAsCollateralEnabled
);
}
interface AaveToken {
function UNDERLYINGASSETADDRESS967() external view returns (address); //inject NONSTANDARD NAMING
}
interface Oracle {
function GETASSETPRICE895(address reserve) external view returns (uint); //inject NONSTANDARD NAMING
function LATESTANSWER820() external view returns (uint); //inject NONSTANDARD NAMING
}
interface LendingPoolAddressesProvider {
function GETLENDINGPOOL689() external view returns (address); //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE785() external view returns (address); //inject NONSTANDARD NAMING
function GETPRICEORACLE709() external view returns (address); //inject NONSTANDARD NAMING
}
contract yDelegatedVault is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
address public governance;
address public controller;
uint public insurance;
uint public healthFactor = 4;
address public constant aave533 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING
constructor (address _token, address _controller) public ERC20Detailed(
string(abi.encodePacked("yearn ", ERC20Detailed(_token).NAME591())),
string(abi.encodePacked("y", ERC20Detailed(_token).SYMBOL151())),
ERC20Detailed(_token).DECIMALS443()
) {
token = IERC20(_token);
governance = msg.sender;
controller = _controller;
}
function DEBT414() public view returns (uint) { //inject NONSTANDARD NAMING
address _reserve = Controller(controller).WANT709(address(this));
(,uint currentBorrowBalance,,,,,,,,) = Aave(GETAAVE93()).GETUSERRESERVEDATA201(_reserve, address(this));
return currentBorrowBalance;
}
function CREDIT327() public view returns (uint) { //inject NONSTANDARD NAMING
return Controller(controller).BALANCEOF856(address(this));
}
// % of tokens locked and cannot be withdrawn per user
// this is impermanent locked, unless the debt out accrues the strategy
function LOCKED694() public view returns (uint) { //inject NONSTANDARD NAMING
return CREDIT327().MUL714(1e18).DIV963(DEBT414());
}
function DEBTSHARE933(address _lp) public view returns (uint) { //inject NONSTANDARD NAMING
return DEBT414().MUL714(BALANCEOF856(_lp)).MUL714(TOTALSUPPLY668());
}
function GETAAVE93() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave533).GETLENDINGPOOL689();
}
function GETAAVECORE229() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave533).GETLENDINGPOOLCORE785();
}
function SETHEALTHFACTOR690(uint _hf) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
healthFactor = _hf;
}
function ACTIVATE169() public { //inject NONSTANDARD NAMING
Aave(GETAAVE93()).SETUSERUSERESERVEASCOLLATERAL395(UNDERLYING289(), true);
}
function REPAY171(address reserve, uint amount) public { //inject NONSTANDARD NAMING
// Required for certain stable coins (USDT for example)
IERC20(reserve).APPROVE165(address(GETAAVECORE229()), 0);
IERC20(reserve).APPROVE165(address(GETAAVECORE229()), amount);
Aave(GETAAVE93()).REPAY171(reserve, amount, address(uint160(address(this))));
}
function REPAYALL522() public { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _amount = IERC20(_reserve).BALANCEOF856(address(this));
REPAY171(_reserve, _amount);
}
// Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
function HARVEST865(address reserve, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(reserve != address(token), "token");
IERC20(reserve).SAFETRANSFER595(controller, amount);
}
// Ignore insurance fund for balance calculations
function BALANCE541() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF856(address(this)).SUB641(insurance);
}
function SETCONTROLLER494(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
function GETAAVEORACLE538() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave533).GETPRICEORACLE709();
}
function GETRESERVEPRICEETH945(address reserve) public view returns (uint) { //inject NONSTANDARD NAMING
return Oracle(GETAAVEORACLE538()).GETASSETPRICE895(reserve);
}
function SHOULDREBALANCE804() external view returns (bool) { //inject NONSTANDARD NAMING
return (OVER549() > 0);
}
function OVER549() public view returns (uint) { //inject NONSTANDARD NAMING
OVER549(0);
}
function GETUNDERLYINGPRICEETH537(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
return _amount.MUL714(GETUNDERLYINGPRICE909()).DIV963(uint(10)**ERC20Detailed(address(token)).DECIMALS443()); // Calculate the amount we are withdrawing in ETH
}
function OVER549(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _eth = GETUNDERLYINGPRICEETH537(_amount);
(uint _maxSafeETH,uint _totalBorrowsETH,) = MAXSAFEETH837();
_maxSafeETH = _maxSafeETH.MUL714(105).DIV963(100); // 5% buffer so we don't go into a earn/rebalance loop
if (_eth > _maxSafeETH) {
_maxSafeETH = 0;
} else {
_maxSafeETH = _maxSafeETH.SUB641(_eth); // Add the ETH we are withdrawing
}
if (_maxSafeETH < _totalBorrowsETH) {
uint _over = _totalBorrowsETH.MUL714(_totalBorrowsETH.SUB641(_maxSafeETH)).DIV963(_totalBorrowsETH);
_over = _over.MUL714(uint(10)**ERC20Detailed(_reserve).DECIMALS443()).DIV963(GETRESERVEPRICE515());
return _over;
} else {
return 0;
}
}
function _REBALANCE677(uint _amount) internal { //inject NONSTANDARD NAMING
uint _over = OVER549(_amount);
if (_over > 0) {
Controller(controller).WITHDRAW362(address(this), _over);
REPAYALL522();
}
}
function REBALANCE176() external { //inject NONSTANDARD NAMING
_REBALANCE677(0);
}
function CLAIMINSURANCE254() external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
token.SAFETRANSFER595(controller, insurance);
insurance = 0;
}
function MAXSAFEETH837() public view returns (uint maxBorrowsETH, uint totalBorrowsETH, uint availableBorrowsETH) { //inject NONSTANDARD NAMING
(,,uint _totalBorrowsETH,,uint _availableBorrowsETH,,,) = Aave(GETAAVE93()).GETUSERACCOUNTDATA396(address(this));
uint _maxBorrowETH = (_totalBorrowsETH.ADD348(_availableBorrowsETH));
return (_maxBorrowETH.DIV963(healthFactor), _totalBorrowsETH, _availableBorrowsETH);
}
function SHOULDBORROW22() external view returns (bool) { //inject NONSTANDARD NAMING
return (AVAILABLETOBORROWRESERVE235() > 0);
}
function AVAILABLETOBORROWETH693() public view returns (uint) { //inject NONSTANDARD NAMING
(uint _maxSafeETH,uint _totalBorrowsETH, uint _availableBorrowsETH) = MAXSAFEETH837();
_maxSafeETH = _maxSafeETH.MUL714(95).DIV963(100); // 5% buffer so we don't go into a earn/rebalance loop
if (_maxSafeETH > _totalBorrowsETH) {
return _availableBorrowsETH.MUL714(_maxSafeETH.SUB641(_totalBorrowsETH)).DIV963(_availableBorrowsETH);
} else {
return 0;
}
}
function AVAILABLETOBORROWRESERVE235() public view returns (uint) { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _available = AVAILABLETOBORROWETH693();
if (_available > 0) {
return _available.MUL714(uint(10)**ERC20Detailed(_reserve).DECIMALS443()).DIV963(GETRESERVEPRICE515());
} else {
return 0;
}
}
function GETRESERVEPRICE515() public view returns (uint) { //inject NONSTANDARD NAMING
return GETRESERVEPRICEETH945(RESERVE164());
}
function GETUNDERLYINGPRICE909() public view returns (uint) { //inject NONSTANDARD NAMING
return GETRESERVEPRICEETH945(UNDERLYING289());
}
function EARN394() external { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _borrow = AVAILABLETOBORROWRESERVE235();
if (_borrow > 0) {
Aave(GETAAVE93()).BORROW427(_reserve, _borrow, 2, 7);
}
//rebalance here
uint _balance = IERC20(_reserve).BALANCEOF856(address(this));
if (_balance > 0) {
IERC20(_reserve).SAFETRANSFER595(controller, _balance);
Controller(controller).EARN394(address(this), _balance);
}
}
function DEPOSITALL399() external { //inject NONSTANDARD NAMING
DEPOSIT764(token.BALANCEOF856(msg.sender));
}
function DEPOSIT764(uint _amount) public { //inject NONSTANDARD NAMING
uint _pool = BALANCE541();
token.SAFETRANSFERFROM895(msg.sender, address(this), _amount);
// 0.5% of deposits go into an insurance fund incase of negative profits to protect withdrawals
// At a 4 health factor, this is a -2% position
uint _insurance = _amount.MUL714(50).DIV963(10000);
_amount = _amount.SUB641(_insurance);
insurance = insurance.ADD348(_insurance);
//Controller can claim insurance to liquidate to cover interest
uint shares = 0;
if (TOTALSUPPLY668() == 0) {
shares = _amount;
ACTIVATE169();
} else {
shares = (_amount.MUL714(TOTALSUPPLY668())).DIV963(_pool);
}
_MINT225(msg.sender, shares);
}
function RESERVE164() public view returns (address) { //inject NONSTANDARD NAMING
return Controller(controller).WANT709(address(this));
}
function UNDERLYING289() public view returns (address) { //inject NONSTANDARD NAMING
return AaveToken(address(token)).UNDERLYINGASSETADDRESS967();
}
function WITHDRAWALL686() public { //inject NONSTANDARD NAMING
WITHDRAW362(BALANCEOF856(msg.sender));
}
// Calculates in impermanent lock due to debt
function MAXWITHDRAWAL697(address account) public view returns (uint) { //inject NONSTANDARD NAMING
uint _balance = BALANCEOF856(account);
uint _safeWithdraw = _balance.MUL714(LOCKED694()).DIV963(1e18);
if (_safeWithdraw > _balance) {
return _balance;
} else {
uint _diff = _balance.SUB641(_safeWithdraw);
return _balance.SUB641(_diff.MUL714(2)); // technically 150%, not 200%, but adding buffer
}
}
function SAFEWITHDRAW954() external { //inject NONSTANDARD NAMING
WITHDRAW362(MAXWITHDRAWAL697(msg.sender));
}
// No rebalance implementation for lower fees and faster swaps
function WITHDRAW362(uint _shares) public { //inject NONSTANDARD NAMING
uint r = (BALANCE541().MUL714(_shares)).DIV963(TOTALSUPPLY668());
_BURN186(msg.sender, _shares);
_REBALANCE677(r);
token.SAFETRANSFER595(msg.sender, r);
}
function GETPRICEPERFULLSHARE836() external view returns (uint) { //inject NONSTANDARD NAMING
return BALANCE541().MUL714(1e18).DIV963(TOTALSUPPLY668());
}
}
|
inject NONSTANDARD NAMING
|
function GETAAVE93() public view returns (address) {
| 12,699,395
|
./partial_match/56/0xC9a83743ed949Ea87250Dd9c30c9A12A45C5653D/sources/KOINToken.sol
|
Forward ERC20 methods to upgraded contract if this one is deprecated
|
function transfer(address _to, uint256 _value) public whenNotPaused returns(bool){
return super.transfer(_to, _value);
}
| 11,134,374
|
pragma solidity 0.4.21;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0);
c = a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b <= a);
c = a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a);
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
function burn(uint256 tokens) public returns (bool success);
function freeze(uint256 tokens) public returns (bool success);
function unfreeze(uint256 tokens) public returns (bool success);
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint tokens);
/* This approve the allowance for the spender */
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 tokens);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 tokens);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 tokens);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial CTC supply
// ----------------------------------------------------------------------------
contract WILLTOKEN is ERC20Interface, Owned {
using SafeMath for uint;
string public name;
string public symbol;
uint8 public decimals;
uint256 public _totalSupply;
address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balances;
mapping(address => mapping(address => uint256)) allowed;
mapping (address => uint256) public freezeOf;
/* Initializes contract with initial supply tokens to the creator of the contract */
function WILLTOKEN (
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) public {
decimals = decimalUnits; // Amount of decimals for display purposes
_totalSupply = initialSupply * 10**uint(decimals); // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purpose
owner = msg.sender; // Set the creator as owner
balances[owner] = _totalSupply; // Give the creator all initial tokens
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
require( tokens > 0 && to != 0x0 );
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(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.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public onlyOwner 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
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require( tokens > 0 && to != 0x0 && from != 0x0 );
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(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 (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Burns the amount of tokens by the owner
// ------------------------------------------------------------------------
function burn(uint256 tokens) public onlyOwner returns (bool success) {
require (balances[msg.sender] >= tokens) ; // Check if the sender has enough
require (tokens > 0) ;
balances[msg.sender] = balances[msg.sender].sub(tokens); // Subtract from the sender
_totalSupply = _totalSupply.sub(tokens); // Updates totalSupply
emit Burn(msg.sender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Freeze the amount of tokens by the owner
// ------------------------------------------------------------------------
function freeze(uint256 tokens) public onlyOwner returns (bool success) {
require (balances[msg.sender] >= tokens) ; // Check if the sender has enough
require (tokens > 0) ;
balances[msg.sender] = balances[msg.sender].sub(tokens); // Subtract from the sender
freezeOf[msg.sender] = freezeOf[msg.sender].add(tokens); // Updates totalSupply
emit Freeze(msg.sender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Unfreeze the amount of tokens by the owner
// ------------------------------------------------------------------------
function unfreeze(uint256 tokens) public onlyOwner returns (bool success) {
require (freezeOf[msg.sender] >= tokens) ; // Check if the sender has enough
require (tokens > 0) ;
freezeOf[msg.sender] = freezeOf[msg.sender].sub(tokens); // Subtract from the sender
balances[msg.sender] = balances[msg.sender].add(tokens);
emit Unfreeze(msg.sender, tokens);
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 https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces ------------------------------------------------------------------------
|
function approve(address spender, uint tokens) public onlyOwner returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| 177,721
|
./full_match/1/0x2D8DAe91dcDC67f88054d0bdC6cb1052862dde4f/sources/contracts/RoyaltySender.sol
|
Adds the given addresses to the firstSell array and executes the royalties for all the addresses that must receive royalties. This function is executed only one time by the contract owner and sets royalties in distribute mode. If it has accumulated funds then it sends royalties to the right addresses FirstSell addresses which are from an smart contract will not receive royalties firstSell_ contains the information used in the first sale/
|
function executeRoyalties(RoyaltyUser[] memory firstSell_)
external
onlyOwner
{
require(!distribute, "Method already executed");
require(
(firstSell_.length + firstSell.length) <= firstSellQuantity,
"First sell quantity are invalid"
);
for (uint256 i = 0; i < firstSell_.length; i++) {
if(!Address.isContract(firstSell_[i].userAddress)) {
firstSell.push(firstSell_[i]);
emit AddressIsContract(firstSell_[i].userAddress);
}
}
distribute = true;
if (sellAmount > 0) {
sendRoyalties(firstSell, sellAmount);
}
}
| 4,886,249
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./libs/IUniRouter02.sol";
import "./libs/IWETH.sol";
interface IToken {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
}
contract BrewlabsStaking is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// Whether it is initialized
bool public isInitialized;
uint256 public duration = 365; // 365 days
// Whether a limit is set for users
bool public hasUserLimit;
// The pool limit (0 if none)
uint256 public poolLimitPerUser;
// The block number when staking starts.
uint256 public startBlock;
// The block number when staking ends.
uint256 public bonusEndBlock;
// tokens created per block.
uint256 public rewardPerBlock;
// The block number of the last pool update
uint256 public lastRewardBlock;
// swap router and path, slipPage
uint256 public slippageFactor = 800; // 20% default slippage tolerance
uint256 public constant slippageFactorUL = 995;
address public uniRouterAddress;
address[] public reflectionToStakedPath;
address[] public earnedToStakedPath;
// The deposit & withdraw fee
uint256 public constant MAX_FEE = 2000;
uint256 public depositFee;
uint256 public withdrawFee;
address public walletA;
address public buyBackWallet = 0xE1f1dd010BBC2860F81c8F90Ea4E38dB949BB16F;
uint256 public performanceFee = 0.00089 ether;
// The precision factor
uint256 public PRECISION_FACTOR;
uint256 public PRECISION_FACTOR_REFLECTION;
// The staked token
IERC20 public stakingToken;
// The earned token
IERC20 public earnedToken;
// The dividend token of staking token
address public dividendToken;
bool public hasDividend;
// Accrued token per share
uint256 public accTokenPerShare;
uint256 public accDividendPerShare;
uint256 public totalStaked;
uint256 private totalEarned;
uint256 private totalReflections;
uint256 private reflectionDebt;
// Info of each user that stakes tokens (stakingToken)
mapping(address => UserInfo) public userInfo;
struct UserInfo {
uint256 amount; // How many staked tokens the user has provided
uint256 rewardDebt; // Reward debt
uint256 reflectionDebt; // Reflection debt
}
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event AdminTokenRecovered(address tokenRecovered, uint256 amount);
event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock);
event NewRewardPerBlock(uint256 rewardPerBlock);
event RewardsStop(uint256 blockNumber);
event UpdatePoolLimit(uint256 poolLimitPerUser, bool hasLimit);
event ServiceInfoUpadted(address _addr, uint256 _fee);
event WalletAUpdated(address _addr);
event DurationUpdated(uint256 _duration);
event SetSettings(
uint256 _depositFee,
uint256 _withdrawFee,
uint256 _slippageFactor,
address _uniRouter,
address[] _path0,
address[] _path1
);
constructor() {}
/*
* @notice Initialize the contract
* @param _stakingToken: staked token address
* @param _earnedToken: earned token address
* @param _dividendToken: reflection token address
* @param _rewardPerBlock: reward per block (in earnedToken)
* @param _depositFee: deposit fee
* @param _withdrawFee: withdraw fee
* @param _uniRouter: uniswap router address for swap tokens
* @param _earnedToStakedPath: swap path to compound (earned -> staking path)
* @param _reflectionToStakedPath: swap path to compound (reflection -> staking path)
*/
function initialize(
IERC20 _stakingToken,
IERC20 _earnedToken,
address _dividendToken,
uint256 _rewardPerBlock,
uint256 _depositFee,
uint256 _withdrawFee,
address _uniRouter,
address[] memory _earnedToStakedPath,
address[] memory _reflectionToStakedPath,
bool _hasDividend
) external onlyOwner {
require(!isInitialized, "Already initialized");
// Make this contract initialized
isInitialized = true;
stakingToken = _stakingToken;
earnedToken = _earnedToken;
dividendToken = _dividendToken;
hasDividend = _hasDividend;
rewardPerBlock = _rewardPerBlock;
require(_depositFee < MAX_FEE, "Invalid deposit fee");
require(_withdrawFee < MAX_FEE, "Invalid withdraw fee");
depositFee = _depositFee;
withdrawFee = _withdrawFee;
walletA = msg.sender;
uint256 decimalsRewardToken = uint256(IToken(address(earnedToken)).decimals());
require(decimalsRewardToken < 30, "Must be inferior to 30");
PRECISION_FACTOR = uint256(10**(40 - decimalsRewardToken));
uint256 decimalsdividendToken = 18;
if(address(dividendToken) != address(0x0)) {
decimalsdividendToken = uint256(IToken(address(dividendToken)).decimals());
require(decimalsdividendToken < 30, "Must be inferior to 30");
}
PRECISION_FACTOR_REFLECTION = uint256(10**(40 - decimalsdividendToken));
uniRouterAddress = _uniRouter;
earnedToStakedPath = _earnedToStakedPath;
reflectionToStakedPath = _reflectionToStakedPath;
}
/*
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param _amount: amount to withdraw (in earnedToken)
*/
function deposit(uint256 _amount) external nonReentrant {
require(startBlock > 0 && startBlock < block.number, "Staking hasn't started yet");
require(_amount > 0, "Amount should be greator than 0");
UserInfo storage user = userInfo[msg.sender];
if (hasUserLimit) {
require(
_amount + user.amount <= poolLimitPerUser,
"User amount above limit"
);
}
_updatePool();
if (user.amount > 0) {
uint256 pending = user.amount * accTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
}
uint256 pendingReflection = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
if (pendingReflection > 0 && hasDividend) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
}
uint256 beforeAmount = stakingToken.balanceOf(address(this));
stakingToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
uint256 afterAmount = stakingToken.balanceOf(address(this));
uint256 realAmount = afterAmount - beforeAmount;
if (depositFee > 0) {
uint256 fee = realAmount * depositFee / 10000;
stakingToken.safeTransfer(walletA, fee);
realAmount = realAmount - fee;
}
user.amount = user.amount + realAmount;
user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR;
user.reflectionDebt = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
totalStaked = totalStaked + realAmount;
emit Deposit(msg.sender, realAmount);
}
/*
* @notice Withdraw staked tokens and collect reward tokens
* @param _amount: amount to withdraw (in earnedToken)
*/
function withdraw(uint256 _amount) external nonReentrant {
require(_amount > 0, "Amount should be greator than 0");
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "Amount to withdraw too high");
_updatePool();
if(user.amount > 0) {
uint256 pending = user.amount * accTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
}
uint256 pendingReflection = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
if (pendingReflection > 0 && hasDividend) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
}
uint256 realAmount = _amount;
if (user.amount < _amount) {
realAmount = user.amount;
}
user.amount = user.amount - realAmount;
totalStaked = totalStaked - realAmount;
if (withdrawFee > 0) {
uint256 fee = realAmount * withdrawFee / 10000;
stakingToken.safeTransfer(walletA, fee);
realAmount = realAmount - fee;
}
stakingToken.safeTransfer(address(msg.sender), realAmount);
user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR;
user.reflectionDebt = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
emit Withdraw(msg.sender, _amount);
}
function claimReward() external payable nonReentrant {
UserInfo storage user = userInfo[msg.sender];
_transferPerformanceFee();
_updatePool();
if (user.amount == 0) return;
uint256 pending = user.amount * accTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
}
user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR;
}
function claimDividend() external payable nonReentrant {
require(hasDividend == true, "No reflections");
UserInfo storage user = userInfo[msg.sender];
_transferPerformanceFee();
_updatePool();
if (user.amount == 0) return;
uint256 pendingReflection = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
if (pendingReflection > 0) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
user.reflectionDebt = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
function compoundReward() external payable nonReentrant {
UserInfo storage user = userInfo[msg.sender];
_transferPerformanceFee();
_updatePool();
if (user.amount == 0) return;
uint256 pending = user.amount * accTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
if(address(stakingToken) != address(earnedToken)) {
uint256 beforeAmount = stakingToken.balanceOf(address(this));
_safeSwap(pending, earnedToStakedPath, address(this));
uint256 afterAmount = stakingToken.balanceOf(address(this));
pending = afterAmount - beforeAmount;
}
if (hasUserLimit) {
require(
pending + user.amount <= poolLimitPerUser,
"User amount above limit"
);
}
totalStaked = totalStaked + pending;
user.amount = user.amount + pending;
user.reflectionDebt = user.reflectionDebt + pending * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
emit Deposit(msg.sender, pending);
}
user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR;
}
function compoundDividend() external payable nonReentrant {
require(hasDividend == true, "No reflections");
UserInfo storage user = userInfo[msg.sender];
_transferPerformanceFee();
_updatePool();
if (user.amount == 0) return;
uint256 pending = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
if (pending > 0) {
totalReflections = totalReflections - pending;
if(address(stakingToken) != address(dividendToken)) {
if(address(dividendToken) == address(0x0)) {
address wethAddress = IUniRouter02(uniRouterAddress).WETH();
IWETH(wethAddress).deposit{ value: pending }();
}
uint256 beforeAmount = stakingToken.balanceOf(address(this));
_safeSwap(pending, reflectionToStakedPath, address(this));
uint256 afterAmount = stakingToken.balanceOf(address(this));
pending = afterAmount - beforeAmount;
}
if (hasUserLimit) {
require(
pending + user.amount <= poolLimitPerUser,
"User amount above limit"
);
}
totalStaked = totalStaked + pending;
user.amount = user.amount + pending;
user.rewardDebt = user.rewardDebt + pending * accTokenPerShare / PRECISION_FACTOR;
emit Deposit(msg.sender, pending);
}
user.reflectionDebt = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
function _transferPerformanceFee() internal {
require(msg.value >= performanceFee, 'should pay small gas to compound or harvest');
payable(buyBackWallet).transfer(performanceFee);
if(msg.value > performanceFee) {
payable(msg.sender).transfer(msg.value - performanceFee);
}
}
/*
* @notice Withdraw staked tokens without caring about rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.reflectionDebt = 0;
if (amountToTransfer > 0) {
stakingToken.safeTransfer(address(msg.sender), amountToTransfer);
totalStaked = totalStaked - amountToTransfer;
}
emit EmergencyWithdraw(msg.sender, user.amount);
}
/**
* @notice Available amount of reward token
*/
function availableRewardTokens() public view returns (uint256) {
if(address(earnedToken) == address(dividendToken)) return totalEarned;
uint256 _amount = earnedToken.balanceOf(address(this));
if (address(earnedToken) == address(stakingToken)) {
if (_amount < totalStaked) return 0;
return _amount - totalStaked;
}
return _amount;
}
/**
* @notice Available amount of reflection token
*/
function availableDividendTokens() public view returns (uint256) {
if(address(dividendToken) == address(0x0)) {
return address(this).balance;
}
uint256 _amount = IERC20(dividendToken).balanceOf(address(this));
if(address(dividendToken) == address(earnedToken)) {
if(_amount < totalEarned) return 0;
_amount = _amount - totalEarned;
}
if(address(dividendToken) == address(stakingToken)) {
if(_amount < totalStaked) return 0;
_amount = _amount - totalStaked;
}
return _amount;
}
/*
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 adjustedTokenPerShare = accTokenPerShare;
if (block.number > lastRewardBlock && totalStaked != 0 && lastRewardBlock > 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 cakeReward = multiplier * rewardPerBlock;
adjustedTokenPerShare = accTokenPerShare + (
cakeReward * PRECISION_FACTOR / totalStaked
);
}
return user.amount * adjustedTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
}
function pendingDividends(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
if(totalStaked == 0) return 0;
uint256 reflectionAmount = availableDividendTokens();
uint256 sTokenBal = stakingToken.balanceOf(address(this));
if(address(stakingToken) == dividendToken) {
sTokenBal = sTokenBal - reflectionAmount;
}
uint256 adjustedReflectionPerShare = accDividendPerShare + (
(reflectionAmount - totalReflections) * PRECISION_FACTOR_REFLECTION / sTokenBal
);
uint256 pendingReflection =
user.amount * adjustedReflectionPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
return pendingReflection;
}
/************************
** Admin Methods
*************************/
function harvest() external onlyOwner {
_updatePool();
uint256 _amount = stakingToken.balanceOf(address(this));
_amount = _amount - totalStaked;
uint256 pendingReflection = _amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - reflectionDebt;
if(pendingReflection > 0) {
if(address(dividendToken) == address(0x0)) {
payable(walletA).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer( walletA, pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
reflectionDebt = _amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
/*
* @notice Deposit reward token
* @dev Only call by owner. Needs to be for deposit of reward token when reflection token is same with reward token.
*/
function depositRewards(uint _amount) external onlyOwner nonReentrant {
require(_amount > 0, "invalid amount");
uint256 beforeAmt = earnedToken.balanceOf(address(this));
earnedToken.safeTransferFrom(msg.sender, address(this), _amount);
uint256 afterAmt = earnedToken.balanceOf(address(this));
totalEarned = totalEarned + afterAmt - beforeAmt;
}
/*
* @notice Withdraw reward token
* @dev Only callable by owner. Needs to be for emergency.
*/
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
require( block.number > bonusEndBlock, "Pool is running");
require(availableRewardTokens() >= _amount, "Insufficient reward tokens");
if(_amount == 0) _amount = availableRewardTokens();
earnedToken.safeTransfer(address(msg.sender), _amount);
if (totalEarned > 0) {
if (_amount > totalEarned) {
totalEarned = 0;
} else {
totalEarned = totalEarned - _amount;
}
}
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of tokens to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
{
require(
_tokenAddress != address(earnedToken),
"Cannot be reward token"
);
if(_tokenAddress == address(stakingToken)) {
uint256 tokenBal = stakingToken.balanceOf(address(this));
require(_tokenAmount <= tokenBal - totalStaked, "Insufficient balance");
}
if(_tokenAddress == address(0x0)) {
payable(msg.sender).transfer(_tokenAmount);
} else {
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
}
emit AdminTokenRecovered(_tokenAddress, _tokenAmount);
}
function startReward() external onlyOwner {
require(startBlock == 0, "Pool was already started");
startBlock = block.number + 100;
bonusEndBlock = startBlock + duration * 6426;
lastRewardBlock = startBlock;
emit NewStartAndEndBlocks(startBlock, bonusEndBlock);
}
function stopReward() external onlyOwner {
bonusEndBlock = block.number;
emit RewardsStop(bonusEndBlock);
}
/*
* @notice Update pool limit per user
* @dev Only callable by owner.
* @param _hasUserLimit: whether the limit remains forced
* @param _poolLimitPerUser: new pool limit per user
*/
function updatePoolLimitPerUser( bool _hasUserLimit, uint256 _poolLimitPerUser) external onlyOwner {
if (_hasUserLimit) {
require(
_poolLimitPerUser > poolLimitPerUser,
"New limit must be higher"
);
poolLimitPerUser = _poolLimitPerUser;
} else {
poolLimitPerUser = 0;
}
hasUserLimit = _hasUserLimit;
emit UpdatePoolLimit(poolLimitPerUser, hasUserLimit);
}
/*
* @notice Update reward per block
* @dev Only callable by owner.
* @param _rewardPerBlock: the reward per block
*/
function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
// require(block.number < startBlock, "Pool was already started");
rewardPerBlock = _rewardPerBlock;
emit NewRewardPerBlock(_rewardPerBlock);
}
function setServiceInfo(address _buyBackWallet, uint256 _fee) external {
require(msg.sender == buyBackWallet, "setServiceInfo: FORBIDDEN");
require(_buyBackWallet != address(0x0), "Invalid address");
require(_fee < 0.05 ether, "fee cannot exceed 0.05 ether");
buyBackWallet = _buyBackWallet;
performanceFee = _fee;
emit ServiceInfoUpadted(_buyBackWallet, _fee);
}
function updateWalletA(address _walletA) external onlyOwner {
require(_walletA != address(0x0) || _walletA != walletA, "Invalid address");
walletA = _walletA;
emit WalletAUpdated(_walletA);
}
function setDuration(uint256 _duration) external onlyOwner {
require(_duration >= 30, "lower limit reached");
duration = _duration;
if(startBlock > 0) {
bonusEndBlock = startBlock + duration * 6426;
require(bonusEndBlock > block.number, "invalid duration");
}
emit DurationUpdated(_duration);
}
function setSettings(
uint256 _depositFee,
uint256 _withdrawFee,
uint256 _slippageFactor,
address _uniRouter,
address[] memory _earnedToStakedPath,
address[] memory _reflectionToStakedPath
) external onlyOwner {
require(_depositFee < MAX_FEE, "Invalid deposit fee");
require(_withdrawFee < MAX_FEE, "Invalid withdraw fee");
require(_slippageFactor <= slippageFactorUL, "_slippageFactor too high");
depositFee = _depositFee;
withdrawFee = _withdrawFee;
slippageFactor = _slippageFactor;
uniRouterAddress = _uniRouter;
reflectionToStakedPath = _reflectionToStakedPath;
earnedToStakedPath = _earnedToStakedPath;
emit SetSettings(_depositFee, _withdrawFee, _slippageFactor, _uniRouter, _earnedToStakedPath, _reflectionToStakedPath);
}
/************************
** Internal Methods
*************************/
/*
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool() internal {
// calc reflection rate
if(totalStaked > 0 && hasDividend) {
uint256 reflectionAmount = availableDividendTokens();
uint256 sTokenBal = stakingToken.balanceOf(address(this));
if(address(stakingToken) == dividendToken) {
sTokenBal = sTokenBal - reflectionAmount;
}
accDividendPerShare = accDividendPerShare + (
(reflectionAmount - totalReflections) * PRECISION_FACTOR_REFLECTION / sTokenBal
);
totalReflections = reflectionAmount;
}
if (block.number <= lastRewardBlock || lastRewardBlock == 0) {
return;
}
if (totalStaked == 0) {
lastRewardBlock = block.number;
return;
}
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 _reward = multiplier * rewardPerBlock;
accTokenPerShare = accTokenPerShare + (
_reward * PRECISION_FACTOR / totalStaked
);
lastRewardBlock = block.number;
}
/*
* @notice Return reward multiplier over the given _from to _to block.
* @param _from: block to start
* @param _to: block to finish
*/
function _getMultiplier(uint256 _from, uint256 _to)
internal
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to - _from;
} else if (_from >= bonusEndBlock) {
return 0;
} else {
return bonusEndBlock - _from;
}
}
function _safeSwap(
uint256 _amountIn,
address[] memory _path,
address _to
) internal {
uint256[] memory amounts = IUniRouter02(uniRouterAddress).getAmountsOut(_amountIn, _path);
uint256 amountOut = amounts[amounts.length - 1];
IERC20(_path[0]).safeApprove(uniRouterAddress, _amountIn);
IUniRouter02(uniRouterAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(
_amountIn,
amountOut * slippageFactor / 1000,
_path,
_to,
block.timestamp + 600
);
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IUniRouter01.sol";
interface IUniRouter02 is IUniRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IUniRouter01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
|
Deposit staked tokens and collect reward tokens (if any) _amount: amount to withdraw (in earnedToken)/
|
function deposit(uint256 _amount) external nonReentrant {
require(startBlock > 0 && startBlock < block.number, "Staking hasn't started yet");
require(_amount > 0, "Amount should be greator than 0");
UserInfo storage user = userInfo[msg.sender];
if (hasUserLimit) {
require(
_amount + user.amount <= poolLimitPerUser,
"User amount above limit"
);
}
_updatePool();
if (user.amount > 0) {
uint256 pending = user.amount * accTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
totalEarned = 0;
}
}
uint256 pendingReflection = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
if (pendingReflection > 0 && hasDividend) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
}
uint256 beforeAmount = stakingToken.balanceOf(address(this));
stakingToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
uint256 afterAmount = stakingToken.balanceOf(address(this));
uint256 realAmount = afterAmount - beforeAmount;
if (depositFee > 0) {
uint256 fee = realAmount * depositFee / 10000;
stakingToken.safeTransfer(walletA, fee);
realAmount = realAmount - fee;
}
user.amount = user.amount + realAmount;
user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR;
user.reflectionDebt = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
totalStaked = totalStaked + realAmount;
emit Deposit(msg.sender, realAmount);
}
| 14,648,877
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.12;
interface Erc20 {
function approve(address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
}
interface CErc20 {
function mint(uint256) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function supplyRatePerBlock() external returns (uint256);
function redeem(uint) external returns (uint);
function redeemUnderlying(uint) external returns (uint);
}
interface CEth {
function mint() external payable;
function exchangeRateCurrent() external returns (uint256);
function supplyRatePerBlock() external returns (uint256);
function redeem(uint) external returns (uint);
function redeemUnderlying(uint) external returns (uint);
function approve(address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
}
/**
* @title SalesTogether
* @dev implements share signals to one sales campaign
*/
contract SalesTogether {
event MyLog(string, uint256);
struct Signal {
string title;
string description;
address payable provaider;
bool pay;
}
Signal[] private _signals;
address payable public _manager;
uint public _signalPrice;
uint public _fundCampaign;
uint public _revealCount;
string _title;
string _description;
address[] public signalsSender;
modifier restricted() {
require(msg.sender == _manager);
_;
}
constructor(uint signalPrice, address payable creator, string memory title, string memory description) public {
_manager = creator;
_signalPrice = signalPrice;
_title = title;
_description = description;
}
function fundCampaign() public payable {
_fundCampaign = msg.value;
}
//create Signal to share in the campaign
function createSignal(string memory title, string memory description, address payable provaider) public {
Signal memory newSignal = Signal({
title: title,
description: description,
provaider: provaider,
pay : false
});
_signals.push(newSignal);
}
//approve signal to see compete message. It will pay the price to the signal address (sender)
function approveSignal(uint index, address payable _cEtherContract) public restricted {
// Create a reference to the corresponding cToken contract
CEth cToken = CEth(_cEtherContract);
Signal storage mysignal = _signals[index];
require( mysignal.pay != true);
mysignal.pay = true;
//mysignal.provaider.transfer(_signalPrice);
// Approve transfer on the ERC20 contract
cToken.approve(_cEtherContract, _signalPrice);
cToken.transferFrom(address(this), mysignal.provaider, _signalPrice);
_revealCount++;
}
//show the details of one signal that was paid before
function revealSignal(uint index) public view returns (string memory, string memory, address, bool) {
Signal storage mysignal = _signals[index];
if(mysignal.pay == true){
return (
mysignal.title,
mysignal.description,
mysignal.provaider,
mysignal.pay
);
}
else
{
return (
mysignal.title,
"Must to pay first to see data",
mysignal.provaider,
mysignal.pay
);
}
}
//get signals without description
function getSignals(uint index) public view returns (string memory, address, bool) {
Signal storage mysignal = _signals[index];
return (
mysignal.title,
mysignal.provaider,
mysignal.pay
);
}
//get summary of this sales campaign
function getSummary() public view returns (uint, uint, uint, uint, address) {
return (
_fundCampaign,
address(this).balance,
_signals.length,
_revealCount,
_manager
);
}
//get amount of signals send
function getSignalsCount() public view returns (uint) {
return _signals.length;
}
function supplyEthToCompound(address payable _cEtherContract)
public
payable
returns (bool)
{
// Create a reference to the corresponding cToken contract
CEth cToken = CEth(_cEtherContract);
// Amount of current exchange rate from cToken to underlying
uint256 exchangeRateMantissa = cToken.exchangeRateCurrent();
emit MyLog("Exchange Rate (scaled up by 1e18): ", exchangeRateMantissa);
// Amount added to you supply balance this block
uint256 supplyRateMantissa = cToken.supplyRatePerBlock();
emit MyLog("Supply Rate: (scaled up by 1e18)", supplyRateMantissa);
cToken.mint.value(msg.value).gas(250000)();
return true;
}
function supplyErc20ToCompound(
address _erc20Contract,
address _cErc20Contract,
uint256 _numTokensToSupply
) public returns (uint) {
// Create a reference to the underlying asset contract, like DAI.
Erc20 underlying = Erc20(_erc20Contract);
// Create a reference to the corresponding cToken contract, like cDAI
CErc20 cToken = CErc20(_cErc20Contract);
// Amount of current exchange rate from cToken to underlying
uint256 exchangeRateMantissa = cToken.exchangeRateCurrent();
emit MyLog("Exchange Rate (scaled up by 1e18): ", exchangeRateMantissa);
// Amount added to you supply balance this block
uint256 supplyRateMantissa = cToken.supplyRatePerBlock();
emit MyLog("Supply Rate: (scaled up by 1e18)", supplyRateMantissa);
// Approve transfer on the ERC20 contract
underlying.approve(_cErc20Contract, _numTokensToSupply);
// Mint cTokens
uint mintResult = cToken.mint(_numTokensToSupply);
return mintResult;
}
function redeemCErc20Tokens(
uint256 amount,
bool redeemType,
address _cErc20Contract
) public returns (bool) {
// Create a reference to the corresponding cToken contract, like cDAI
CErc20 cToken = CErc20(_cErc20Contract);
// `amount` is scaled up by 1e18 to avoid decimals
uint256 redeemResult;
if (redeemType == true) {
// Retrieve your asset based on a cToken amount
redeemResult = cToken.redeem(amount);
} else {
// Retrieve your asset based on an amount of the asset
redeemResult = cToken.redeemUnderlying(amount);
}
// Error codes are listed here:
// https://compound.finance/developers/ctokens#ctoken-error-codes
emit MyLog("If this is not 0, there was an error", redeemResult);
return true;
}
function redeemCEth(
uint256 amount,
bool redeemType,
address _cEtherContract
) public returns (bool) {
// Create a reference to the corresponding cToken contract
CEth cToken = CEth(_cEtherContract);
// `amount` is scaled up by 1e18 to avoid decimals
uint256 redeemResult;
if (redeemType == true) {
// Retrieve your asset based on a cToken amount
redeemResult = cToken.redeem(amount);
} else {
// Retrieve your asset based on an amount of the asset
redeemResult = cToken.redeemUnderlying(amount);
}
// Error codes are listed here:
// https://compound.finance/docs/ctokens#ctoken-error-codes
emit MyLog("If this is not 0, there was an error", redeemResult);
_manager.transfer(address(this).balance);
return true;
}
// This is needed to receive ETH when calling `redeemCEth`
function() external payable {}
}
|
Create a reference to the underlying asset contract, like DAI. Create a reference to the corresponding cToken contract, like cDAI Amount of current exchange rate from cToken to underlying Amount added to you supply balance this block Approve transfer on the ERC20 contract Mint cTokens
|
function supplyErc20ToCompound(
address _erc20Contract,
address _cErc20Contract,
uint256 _numTokensToSupply
) public returns (uint) {
Erc20 underlying = Erc20(_erc20Contract);
CErc20 cToken = CErc20(_cErc20Contract);
uint256 exchangeRateMantissa = cToken.exchangeRateCurrent();
emit MyLog("Exchange Rate (scaled up by 1e18): ", exchangeRateMantissa);
uint256 supplyRateMantissa = cToken.supplyRatePerBlock();
emit MyLog("Supply Rate: (scaled up by 1e18)", supplyRateMantissa);
underlying.approve(_cErc20Contract, _numTokensToSupply);
uint mintResult = cToken.mint(_numTokensToSupply);
return mintResult;
}
| 2,500,600
|
// SPDX-License-Identifier: MIT
//
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
//
pragma solidity ^0.8.9;
import "./RandomBeacon.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Keep Random Beacon Governance
/// @notice Owns the `RandomBeacon` contract and is responsible for updating its
/// governable parameters in respect to governance delay individual
/// for each parameter.
contract RandomBeaconGovernance is Ownable {
uint256 public newRelayRequestFee;
uint256 public relayRequestFeeChangeInitiated;
uint256 public newRelayEntrySubmissionEligibilityDelay;
uint256 public relayEntrySubmissionEligibilityDelayChangeInitiated;
uint256 public newRelayEntryHardTimeout;
uint256 public relayEntryHardTimeoutChangeInitiated;
uint256 public newCallbackGasLimit;
uint256 public callbackGasLimitChangeInitiated;
uint256 public newGroupCreationFrequency;
uint256 public groupCreationFrequencyChangeInitiated;
uint256 public newGroupLifetime;
uint256 public groupLifetimeChangeInitiated;
uint256 public newDkgResultChallengePeriodLength;
uint256 public dkgResultChallengePeriodLengthChangeInitiated;
uint256 public newDkgResultSubmissionEligibilityDelay;
uint256 public dkgResultSubmissionEligibilityDelayChangeInitiated;
uint256 public newDkgResultSubmissionReward;
uint256 public dkgResultSubmissionRewardChangeInitiated;
uint256 public newSortitionPoolUnlockingReward;
uint256 public sortitionPoolUnlockingRewardChangeInitiated;
uint256 public newIneligibleOperatorNotifierReward;
uint256 public ineligibleOperatorNotifierRewardChangeInitiated;
uint256 public newRelayEntrySubmissionFailureSlashingAmount;
uint256 public relayEntrySubmissionFailureSlashingAmountChangeInitiated;
uint256 public newMaliciousDkgResultSlashingAmount;
uint256 public maliciousDkgResultSlashingAmountChangeInitiated;
uint256 public newUnauthorizedSigningSlashingAmount;
uint256 public unauthorizedSigningSlashingAmountChangeInitiated;
uint256 public newSortitionPoolRewardsBanDuration;
uint256 public sortitionPoolRewardsBanDurationChangeInitiated;
uint256 public newRelayEntryTimeoutNotificationRewardMultiplier;
uint256 public relayEntryTimeoutNotificationRewardMultiplierChangeInitiated;
uint256 public newUnauthorizedSigningNotificationRewardMultiplier;
uint256
public unauthorizedSigningNotificationRewardMultiplierChangeInitiated;
uint96 public newMinimumAuthorization;
uint256 public minimumAuthorizationChangeInitiated;
uint64 public newAuthorizationDecreaseDelay;
uint256 public authorizationDecreaseDelayChangeInitiated;
uint256 public newDkgMaliciousResultNotificationRewardMultiplier;
uint256
public dkgMaliciousResultNotificationRewardMultiplierChangeInitiated;
RandomBeacon public randomBeacon;
// Long governance delay used for critical parameters giving a chance for
// stakers to opt out before the change is finalized in case they do not
// agree with that change. The maximum group lifetime must not be longer
// than this delay.
//
// The full list of parameters protected by this delay:
// - relay entry hard timeout
// - callback gas limit
// - group lifetime
// - relay entry submission failure slashing amount
// - minimum authorization
// - authorization decrease delay
uint256 internal constant CRITICAL_PARAMETER_GOVERNANCE_DELAY = 2 weeks;
// Short governance delay for non-critical parameters. Honest stakers should
// not be severely affected by any change of these parameters.
//
// The full list of parameters protected by this delay:
// - relay request fee
// - group creation frequency
// - relay entry submission eligibility delay
// - DKG result challenge period length
// - DKG result submission eligibility delay
// - DKG result submission reward
// - sortition pool rewards ban duration
// - malicious DKG result slashing amount
// - sortition pool unlocking reward
// - ineligible operator notifier reward
// - relay entry timeout notification reward multiplier
// - DKG malicious result notification reward multiplier
uint256 internal constant STANDARD_PARAMETER_GOVERNANCE_DELAY = 12 hours;
event RelayRequestFeeUpdateStarted(
uint256 relayRequestFee,
uint256 timestamp
);
event RelayRequestFeeUpdated(uint256 relayRequestFee);
event RelayEntrySubmissionEligibilityDelayUpdateStarted(
uint256 relayEntrySubmissionEligibilityDelay,
uint256 timestamp
);
event RelayEntrySubmissionEligibilityDelayUpdated(
uint256 relayEntrySubmissionEligibilityDelay
);
event RelayEntryHardTimeoutUpdateStarted(
uint256 relayEntryHardTimeout,
uint256 timestamp
);
event RelayEntryHardTimeoutUpdated(uint256 relayEntryHardTimeout);
event CallbackGasLimitUpdateStarted(
uint256 callbackGasLimit,
uint256 timestamp
);
event CallbackGasLimitUpdated(uint256 callbackGasLimit);
event GroupCreationFrequencyUpdateStarted(
uint256 groupCreationFrequency,
uint256 timestamp
);
event GroupCreationFrequencyUpdated(uint256 groupCreationFrequency);
event GroupLifetimeUpdateStarted(uint256 groupLifetime, uint256 timestamp);
event GroupLifetimeUpdated(uint256 groupLifetime);
event DkgResultChallengePeriodLengthUpdateStarted(
uint256 dkgResultChallengePeriodLength,
uint256 timestamp
);
event DkgResultChallengePeriodLengthUpdated(
uint256 dkgResultChallengePeriodLength
);
event DkgResultSubmissionEligibilityDelayUpdateStarted(
uint256 dkgResultSubmissionEligibilityDelay,
uint256 timestamp
);
event DkgResultSubmissionEligibilityDelayUpdated(
uint256 dkgResultSubmissionEligibilityDelay
);
event DkgResultSubmissionRewardUpdateStarted(
uint256 dkgResultSubmissionReward,
uint256 timestamp
);
event DkgResultSubmissionRewardUpdated(uint256 dkgResultSubmissionReward);
event SortitionPoolUnlockingRewardUpdateStarted(
uint256 sortitionPoolUnlockingReward,
uint256 timestamp
);
event SortitionPoolUnlockingRewardUpdated(
uint256 sortitionPoolUnlockingReward
);
event IneligibleOperatorNotifierRewardUpdateStarted(
uint256 ineligibleOperatorNotifierReward,
uint256 timestamp
);
event IneligibleOperatorNotifierRewardUpdated(
uint256 ineligibleOperatorNotifierReward
);
event RelayEntrySubmissionFailureSlashingAmountUpdateStarted(
uint256 relayEntrySubmissionFailureSlashingAmount,
uint256 timestamp
);
event RelayEntrySubmissionFailureSlashingAmountUpdated(
uint256 relayEntrySubmissionFailureSlashingAmount
);
event MaliciousDkgResultSlashingAmountUpdateStarted(
uint256 maliciousDkgResultSlashingAmount,
uint256 timestamp
);
event MaliciousDkgResultSlashingAmountUpdated(
uint256 maliciousDkgResultSlashingAmount
);
event UnauthorizedSigningSlashingAmountUpdateStarted(
uint256 unauthorizedSigningSlashingAmount,
uint256 timestamp
);
event UnauthorizedSigningSlashingAmountUpdated(
uint256 unauthorizedSigningSlashingAmount
);
event SortitionPoolRewardsBanDurationUpdateStarted(
uint256 sortitionPoolRewardsBanDuration,
uint256 timestamp
);
event SortitionPoolRewardsBanDurationUpdated(
uint256 sortitionPoolRewardsBanDuration
);
event RelayEntryTimeoutNotificationRewardMultiplierUpdateStarted(
uint256 relayEntryTimeoutNotificationRewardMultiplier,
uint256 timestamp
);
event RelayEntryTimeoutNotificationRewardMultiplierUpdated(
uint256 relayEntryTimeoutNotificationRewardMultiplier
);
event UnauthorizedSigningNotificationRewardMultiplierUpdateStarted(
uint256 unauthorizedSigningTimeoutNotificationRewardMultiplier,
uint256 timestamp
);
event UnauthorizedSigningNotificationRewardMultiplierUpdated(
uint256 unauthorizedSigningTimeoutNotificationRewardMultiplier
);
event MinimumAuthorizationUpdateStarted(
uint96 minimumAuthorization,
uint256 timestamp
);
event MinimumAuthorizationUpdated(uint96 minimumAuthorization);
event AuthorizationDecreaseDelayUpdateStarted(
uint64 authorizationDecreaseDelay,
uint256 timestamp
);
event AuthorizationDecreaseDelayUpdated(uint64 authorizationDecreaseDelay);
event DkgMaliciousResultNotificationRewardMultiplierUpdateStarted(
uint256 dkgMaliciousResultNotificationRewardMultiplier,
uint256 timestamp
);
event DkgMaliciousResultNotificationRewardMultiplierUpdated(
uint256 dkgMaliciousResultNotificationRewardMultiplier
);
/// @notice Reverts if called before the governance delay elapses.
/// @param changeInitiatedTimestamp Timestamp indicating the beginning
/// of the change.
modifier onlyAfterGovernanceDelay(
uint256 changeInitiatedTimestamp,
uint256 delay
) {
/* solhint-disable not-rely-on-time */
require(changeInitiatedTimestamp > 0, "Change not initiated");
require(
block.timestamp - changeInitiatedTimestamp >= delay,
"Governance delay has not elapsed"
);
_;
/* solhint-enable not-rely-on-time */
}
constructor(RandomBeacon _randomBeacon) {
randomBeacon = _randomBeacon;
}
/// @notice Begins the relay request fee update process.
/// @dev Can be called only by the contract owner.
/// @param _newRelayRequestFee New relay request fee
function beginRelayRequestFeeUpdate(uint256 _newRelayRequestFee)
external
onlyOwner
{
/* solhint-disable not-rely-on-time */
newRelayRequestFee = _newRelayRequestFee;
relayRequestFeeChangeInitiated = block.timestamp;
emit RelayRequestFeeUpdateStarted(_newRelayRequestFee, block.timestamp);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the relay request fee update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeRelayRequestFeeUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
relayRequestFeeChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit RelayRequestFeeUpdated(newRelayRequestFee);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRelayEntryParameters(
newRelayRequestFee,
randomBeacon.relayEntrySubmissionEligibilityDelay(),
randomBeacon.relayEntryHardTimeout(),
randomBeacon.callbackGasLimit()
);
relayRequestFeeChangeInitiated = 0;
newRelayRequestFee = 0;
}
/// @notice Begins the relay entry submission eligibility delay update
/// process.
/// @dev Can be called only by the contract owner.
/// @param _newRelayEntrySubmissionEligibilityDelay New relay entry
/// submission eligibility delay in blocks
function beginRelayEntrySubmissionEligibilityDelayUpdate(
uint256 _newRelayEntrySubmissionEligibilityDelay
) external onlyOwner {
/* solhint-disable not-rely-on-time */
require(
_newRelayEntrySubmissionEligibilityDelay > 0,
"Relay entry submission eligibility delay must be > 0"
);
newRelayEntrySubmissionEligibilityDelay = _newRelayEntrySubmissionEligibilityDelay;
relayEntrySubmissionEligibilityDelayChangeInitiated = block.timestamp;
emit RelayEntrySubmissionEligibilityDelayUpdateStarted(
_newRelayEntrySubmissionEligibilityDelay,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the relay entry submission eligibility delay update
//// process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeRelayEntrySubmissionEligibilityDelayUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
relayEntrySubmissionEligibilityDelayChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit RelayEntrySubmissionEligibilityDelayUpdated(
newRelayEntrySubmissionEligibilityDelay
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRelayEntryParameters(
randomBeacon.relayRequestFee(),
newRelayEntrySubmissionEligibilityDelay,
randomBeacon.relayEntryHardTimeout(),
randomBeacon.callbackGasLimit()
);
relayEntrySubmissionEligibilityDelayChangeInitiated = 0;
newRelayEntrySubmissionEligibilityDelay = 0;
}
/// @notice Begins the relay entry hard timeout update process.
/// @dev Can be called only by the contract owner.
/// @param _newRelayEntryHardTimeout New relay entry hard timeout in blocks
function beginRelayEntryHardTimeoutUpdate(uint256 _newRelayEntryHardTimeout)
external
onlyOwner
{
/* solhint-disable not-rely-on-time */
newRelayEntryHardTimeout = _newRelayEntryHardTimeout;
relayEntryHardTimeoutChangeInitiated = block.timestamp;
emit RelayEntryHardTimeoutUpdateStarted(
_newRelayEntryHardTimeout,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the relay entry hard timeout update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeRelayEntryHardTimeoutUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
relayEntryHardTimeoutChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
)
{
emit RelayEntryHardTimeoutUpdated(newRelayEntryHardTimeout);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRelayEntryParameters(
randomBeacon.relayRequestFee(),
randomBeacon.relayEntrySubmissionEligibilityDelay(),
newRelayEntryHardTimeout,
randomBeacon.callbackGasLimit()
);
relayEntryHardTimeoutChangeInitiated = 0;
newRelayEntryHardTimeout = 0;
}
/// @notice Begins the callback gas limit update process.
/// @dev Can be called only by the contract owner.
/// @param _newCallbackGasLimit New callback gas limit
function beginCallbackGasLimitUpdate(uint256 _newCallbackGasLimit)
external
onlyOwner
{
/* solhint-disable not-rely-on-time */
// slither-disable-next-line too-many-digits
require(
_newCallbackGasLimit > 0 && _newCallbackGasLimit <= 1e6,
"Callback gas limit must be > 0 and <= 1000000"
);
newCallbackGasLimit = _newCallbackGasLimit;
callbackGasLimitChangeInitiated = block.timestamp;
emit CallbackGasLimitUpdateStarted(
_newCallbackGasLimit,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the callback gas limit update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeCallbackGasLimitUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
callbackGasLimitChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
)
{
emit CallbackGasLimitUpdated(newCallbackGasLimit);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRelayEntryParameters(
randomBeacon.relayRequestFee(),
randomBeacon.relayEntrySubmissionEligibilityDelay(),
randomBeacon.relayEntryHardTimeout(),
newCallbackGasLimit
);
callbackGasLimitChangeInitiated = 0;
newCallbackGasLimit = 0;
}
/// @notice Begins the group creation frequency update process.
/// @dev Can be called only by the contract owner.
/// @param _newGroupCreationFrequency New group creation frequency
function beginGroupCreationFrequencyUpdate(
uint256 _newGroupCreationFrequency
) external onlyOwner {
/* solhint-disable not-rely-on-time */
require(
_newGroupCreationFrequency > 0,
"Group creation frequency must be > 0"
);
newGroupCreationFrequency = _newGroupCreationFrequency;
groupCreationFrequencyChangeInitiated = block.timestamp;
emit GroupCreationFrequencyUpdateStarted(
_newGroupCreationFrequency,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the group creation frequency update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeGroupCreationFrequencyUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
groupCreationFrequencyChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit GroupCreationFrequencyUpdated(newGroupCreationFrequency);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateGroupCreationParameters(
newGroupCreationFrequency,
randomBeacon.groupLifetime()
);
groupCreationFrequencyChangeInitiated = 0;
newGroupCreationFrequency = 0;
}
/// @notice Begins the group lifetime update process.
/// @dev Can be called only by the contract owner.
/// @param _newGroupLifetime New group lifetime in blocks
function beginGroupLifetimeUpdate(uint256 _newGroupLifetime)
external
onlyOwner
{
/* solhint-disable not-rely-on-time */
require(
_newGroupLifetime >= 1 days && _newGroupLifetime <= 2 weeks,
"Group lifetime must be >= 1 day and <= 2 weeks"
);
newGroupLifetime = _newGroupLifetime;
groupLifetimeChangeInitiated = block.timestamp;
emit GroupLifetimeUpdateStarted(_newGroupLifetime, block.timestamp);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the group creation frequency update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeGroupLifetimeUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
groupLifetimeChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
)
{
emit GroupLifetimeUpdated(newGroupLifetime);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateGroupCreationParameters(
randomBeacon.groupCreationFrequency(),
newGroupLifetime
);
groupLifetimeChangeInitiated = 0;
newGroupLifetime = 0;
}
/// @notice Begins the DKG result challenge period length update process.
/// @dev Can be called only by the contract owner.
/// @param _newDkgResultChallengePeriodLength New DKG result challenge
/// period length in blocks
function beginDkgResultChallengePeriodLengthUpdate(
uint256 _newDkgResultChallengePeriodLength
) external onlyOwner {
/* solhint-disable not-rely-on-time */
require(
_newDkgResultChallengePeriodLength >= 10,
"DKG result challenge period length must be >= 10"
);
newDkgResultChallengePeriodLength = _newDkgResultChallengePeriodLength;
dkgResultChallengePeriodLengthChangeInitiated = block.timestamp;
emit DkgResultChallengePeriodLengthUpdateStarted(
_newDkgResultChallengePeriodLength,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the DKG result challenge period length update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeDkgResultChallengePeriodLengthUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
dkgResultChallengePeriodLengthChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit DkgResultChallengePeriodLengthUpdated(
newDkgResultChallengePeriodLength
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateDkgParameters(
newDkgResultChallengePeriodLength,
randomBeacon.dkgResultSubmissionEligibilityDelay()
);
dkgResultChallengePeriodLengthChangeInitiated = 0;
newDkgResultChallengePeriodLength = 0;
}
/// @notice Begins the DKG result submission eligibility delay update
/// process.
/// @dev Can be called only by the contract owner.
/// @param _newDkgResultSubmissionEligibilityDelay New DKG result submission
/// eligibility delay in blocks
function beginDkgResultSubmissionEligibilityDelayUpdate(
uint256 _newDkgResultSubmissionEligibilityDelay
) external onlyOwner {
/* solhint-disable not-rely-on-time */
require(
_newDkgResultSubmissionEligibilityDelay > 0,
"DKG result submission eligibility delay must be > 0"
);
newDkgResultSubmissionEligibilityDelay = _newDkgResultSubmissionEligibilityDelay;
dkgResultSubmissionEligibilityDelayChangeInitiated = block.timestamp;
emit DkgResultSubmissionEligibilityDelayUpdateStarted(
_newDkgResultSubmissionEligibilityDelay,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the DKG result submission eligibility delay update
/// process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeDkgResultSubmissionEligibilityDelayUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
dkgResultSubmissionEligibilityDelayChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit DkgResultSubmissionEligibilityDelayUpdated(
newDkgResultSubmissionEligibilityDelay
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateDkgParameters(
randomBeacon.dkgResultChallengePeriodLength(),
newDkgResultSubmissionEligibilityDelay
);
dkgResultSubmissionEligibilityDelayChangeInitiated = 0;
newDkgResultSubmissionEligibilityDelay = 0;
}
/// @notice Begins the DKG result submission reward update process.
/// @dev Can be called only by the contract owner.
/// @param _newDkgResultSubmissionReward New DKG result submission reward
function beginDkgResultSubmissionRewardUpdate(
uint256 _newDkgResultSubmissionReward
) external onlyOwner {
/* solhint-disable not-rely-on-time */
newDkgResultSubmissionReward = _newDkgResultSubmissionReward;
dkgResultSubmissionRewardChangeInitiated = block.timestamp;
emit DkgResultSubmissionRewardUpdateStarted(
_newDkgResultSubmissionReward,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the DKG result submission reward update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeDkgResultSubmissionRewardUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
dkgResultSubmissionRewardChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit DkgResultSubmissionRewardUpdated(newDkgResultSubmissionReward);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRewardParameters(
newDkgResultSubmissionReward,
randomBeacon.sortitionPoolUnlockingReward(),
randomBeacon.ineligibleOperatorNotifierReward(),
randomBeacon.sortitionPoolRewardsBanDuration(),
randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(),
randomBeacon.unauthorizedSigningNotificationRewardMultiplier(),
randomBeacon.dkgMaliciousResultNotificationRewardMultiplier()
);
dkgResultSubmissionRewardChangeInitiated = 0;
newDkgResultSubmissionReward = 0;
}
/// @notice Begins the sortition pool unlocking reward update process.
/// @dev Can be called only by the contract owner.
/// @param _newSortitionPoolUnlockingReward New sortition pool unlocking reward
function beginSortitionPoolUnlockingRewardUpdate(
uint256 _newSortitionPoolUnlockingReward
) external onlyOwner {
/* solhint-disable not-rely-on-time */
newSortitionPoolUnlockingReward = _newSortitionPoolUnlockingReward;
sortitionPoolUnlockingRewardChangeInitiated = block.timestamp;
emit SortitionPoolUnlockingRewardUpdateStarted(
_newSortitionPoolUnlockingReward,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the sortition pool unlocking reward update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeSortitionPoolUnlockingRewardUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
sortitionPoolUnlockingRewardChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit SortitionPoolUnlockingRewardUpdated(
newSortitionPoolUnlockingReward
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRewardParameters(
randomBeacon.dkgResultSubmissionReward(),
newSortitionPoolUnlockingReward,
randomBeacon.ineligibleOperatorNotifierReward(),
randomBeacon.sortitionPoolRewardsBanDuration(),
randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(),
randomBeacon.unauthorizedSigningNotificationRewardMultiplier(),
randomBeacon.dkgMaliciousResultNotificationRewardMultiplier()
);
sortitionPoolUnlockingRewardChangeInitiated = 0;
newSortitionPoolUnlockingReward = 0;
}
/// @notice Begins the ineligible operator notifier reward update process.
/// @dev Can be called only by the contract owner.
/// @param _newIneligibleOperatorNotifierReward New ineligible operator
/// notifier reward.
function beginIneligibleOperatorNotifierRewardUpdate(
uint256 _newIneligibleOperatorNotifierReward
) external onlyOwner {
/* solhint-disable not-rely-on-time */
newIneligibleOperatorNotifierReward = _newIneligibleOperatorNotifierReward;
ineligibleOperatorNotifierRewardChangeInitiated = block.timestamp;
emit IneligibleOperatorNotifierRewardUpdateStarted(
_newIneligibleOperatorNotifierReward,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the ineligible operator notifier reward update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeIneligibleOperatorNotifierRewardUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
ineligibleOperatorNotifierRewardChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit IneligibleOperatorNotifierRewardUpdated(
newIneligibleOperatorNotifierReward
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRewardParameters(
randomBeacon.dkgResultSubmissionReward(),
randomBeacon.sortitionPoolUnlockingReward(),
newIneligibleOperatorNotifierReward,
randomBeacon.sortitionPoolRewardsBanDuration(),
randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(),
randomBeacon.unauthorizedSigningNotificationRewardMultiplier(),
randomBeacon.dkgMaliciousResultNotificationRewardMultiplier()
);
ineligibleOperatorNotifierRewardChangeInitiated = 0;
newIneligibleOperatorNotifierReward = 0;
}
/// @notice Begins the sortition pool rewards ban duration update process.
/// @dev Can be called only by the contract owner.
/// @param _newSortitionPoolRewardsBanDuration New sortition pool rewards
/// ban duration.
function beginSortitionPoolRewardsBanDurationUpdate(
uint256 _newSortitionPoolRewardsBanDuration
) external onlyOwner {
/* solhint-disable not-rely-on-time */
newSortitionPoolRewardsBanDuration = _newSortitionPoolRewardsBanDuration;
sortitionPoolRewardsBanDurationChangeInitiated = block.timestamp;
emit SortitionPoolRewardsBanDurationUpdateStarted(
_newSortitionPoolRewardsBanDuration,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the sortition pool rewards ban duration update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeSortitionPoolRewardsBanDurationUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
sortitionPoolRewardsBanDurationChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit SortitionPoolRewardsBanDurationUpdated(
newSortitionPoolRewardsBanDuration
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRewardParameters(
randomBeacon.dkgResultSubmissionReward(),
randomBeacon.sortitionPoolUnlockingReward(),
randomBeacon.ineligibleOperatorNotifierReward(),
newSortitionPoolRewardsBanDuration,
randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(),
randomBeacon.unauthorizedSigningNotificationRewardMultiplier(),
randomBeacon.dkgMaliciousResultNotificationRewardMultiplier()
);
sortitionPoolRewardsBanDurationChangeInitiated = 0;
newSortitionPoolRewardsBanDuration = 0;
}
/// @notice Begins the relay entry timeout notification reward multiplier
/// update process.
/// @dev Can be called only by the contract owner.
/// @param _newRelayEntryTimeoutNotificationRewardMultiplier New relay
/// entry timeout notification reward multiplier.
function beginRelayEntryTimeoutNotificationRewardMultiplierUpdate(
uint256 _newRelayEntryTimeoutNotificationRewardMultiplier
) external onlyOwner {
/* solhint-disable not-rely-on-time */
require(
_newRelayEntryTimeoutNotificationRewardMultiplier <= 100,
"Maximum value is 100"
);
newRelayEntryTimeoutNotificationRewardMultiplier = _newRelayEntryTimeoutNotificationRewardMultiplier;
relayEntryTimeoutNotificationRewardMultiplierChangeInitiated = block
.timestamp;
emit RelayEntryTimeoutNotificationRewardMultiplierUpdateStarted(
_newRelayEntryTimeoutNotificationRewardMultiplier,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Begins the unauthorized signing notification reward multiplier
/// update process.
/// @dev Can be called only by the contract owner.
/// @param _newUnauthorizedSigningNotificationRewardMultiplier New unauthorized
/// signing notification reward multiplier.
function beginUnauthorizedSigningNotificationRewardMultiplierUpdate(
uint256 _newUnauthorizedSigningNotificationRewardMultiplier
) external onlyOwner {
/* solhint-disable not-rely-on-time */
require(
_newUnauthorizedSigningNotificationRewardMultiplier <= 100,
"Maximum value is 100"
);
newUnauthorizedSigningNotificationRewardMultiplier = _newUnauthorizedSigningNotificationRewardMultiplier;
unauthorizedSigningNotificationRewardMultiplierChangeInitiated = block
.timestamp;
emit UnauthorizedSigningNotificationRewardMultiplierUpdateStarted(
_newUnauthorizedSigningNotificationRewardMultiplier,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the unauthorized signing notification reward
/// multiplier update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeUnauthorizedSigningNotificationRewardMultiplierUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
unauthorizedSigningNotificationRewardMultiplierChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit UnauthorizedSigningNotificationRewardMultiplierUpdated(
newUnauthorizedSigningNotificationRewardMultiplier
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRewardParameters(
randomBeacon.dkgResultSubmissionReward(),
randomBeacon.sortitionPoolUnlockingReward(),
randomBeacon.ineligibleOperatorNotifierReward(),
randomBeacon.sortitionPoolRewardsBanDuration(),
randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(),
newUnauthorizedSigningNotificationRewardMultiplier,
randomBeacon.dkgMaliciousResultNotificationRewardMultiplier()
);
unauthorizedSigningNotificationRewardMultiplierChangeInitiated = 0;
newUnauthorizedSigningNotificationRewardMultiplier = 0;
}
/// @notice Finalizes the relay entry timeout notification reward
/// multiplier update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeRelayEntryTimeoutNotificationRewardMultiplierUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
relayEntryTimeoutNotificationRewardMultiplierChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit RelayEntryTimeoutNotificationRewardMultiplierUpdated(
newRelayEntryTimeoutNotificationRewardMultiplier
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRewardParameters(
randomBeacon.dkgResultSubmissionReward(),
randomBeacon.sortitionPoolUnlockingReward(),
randomBeacon.ineligibleOperatorNotifierReward(),
randomBeacon.sortitionPoolRewardsBanDuration(),
newRelayEntryTimeoutNotificationRewardMultiplier,
randomBeacon.unauthorizedSigningNotificationRewardMultiplier(),
randomBeacon.dkgMaliciousResultNotificationRewardMultiplier()
);
relayEntryTimeoutNotificationRewardMultiplierChangeInitiated = 0;
newRelayEntryTimeoutNotificationRewardMultiplier = 0;
}
/// @notice Begins the DKG malicious result notification reward multiplier
/// update process.
/// @dev Can be called only by the contract owner.
/// @param _newDkgMaliciousResultNotificationRewardMultiplier New DKG
/// malicious result notification reward multiplier.
function beginDkgMaliciousResultNotificationRewardMultiplierUpdate(
uint256 _newDkgMaliciousResultNotificationRewardMultiplier
) external onlyOwner {
/* solhint-disable not-rely-on-time */
require(
_newDkgMaliciousResultNotificationRewardMultiplier <= 100,
"Maximum value is 100"
);
newDkgMaliciousResultNotificationRewardMultiplier = _newDkgMaliciousResultNotificationRewardMultiplier;
dkgMaliciousResultNotificationRewardMultiplierChangeInitiated = block
.timestamp;
emit DkgMaliciousResultNotificationRewardMultiplierUpdateStarted(
_newDkgMaliciousResultNotificationRewardMultiplier,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the DKG malicious result notification reward
/// multiplier update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeDkgMaliciousResultNotificationRewardMultiplierUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
dkgMaliciousResultNotificationRewardMultiplierChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit DkgMaliciousResultNotificationRewardMultiplierUpdated(
newDkgMaliciousResultNotificationRewardMultiplier
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateRewardParameters(
randomBeacon.dkgResultSubmissionReward(),
randomBeacon.sortitionPoolUnlockingReward(),
randomBeacon.ineligibleOperatorNotifierReward(),
randomBeacon.sortitionPoolRewardsBanDuration(),
randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(),
randomBeacon.unauthorizedSigningNotificationRewardMultiplier(),
newDkgMaliciousResultNotificationRewardMultiplier
);
dkgMaliciousResultNotificationRewardMultiplierChangeInitiated = 0;
newDkgMaliciousResultNotificationRewardMultiplier = 0;
}
/// @notice Begins the relay entry submission failure slashing amount update
/// process.
/// @dev Can be called only by the contract owner.
/// @param _newRelayEntrySubmissionFailureSlashingAmount New relay entry
/// submission failure slashing amount
function beginRelayEntrySubmissionFailureSlashingAmountUpdate(
uint256 _newRelayEntrySubmissionFailureSlashingAmount
) external onlyOwner {
/* solhint-disable not-rely-on-time */
newRelayEntrySubmissionFailureSlashingAmount = _newRelayEntrySubmissionFailureSlashingAmount;
relayEntrySubmissionFailureSlashingAmountChangeInitiated = block
.timestamp;
emit RelayEntrySubmissionFailureSlashingAmountUpdateStarted(
_newRelayEntrySubmissionFailureSlashingAmount,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the relay entry submission failure slashing amount
/// update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeRelayEntrySubmissionFailureSlashingAmountUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
relayEntrySubmissionFailureSlashingAmountChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
)
{
emit RelayEntrySubmissionFailureSlashingAmountUpdated(
newRelayEntrySubmissionFailureSlashingAmount
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateSlashingParameters(
newRelayEntrySubmissionFailureSlashingAmount,
randomBeacon.maliciousDkgResultSlashingAmount(),
randomBeacon.unauthorizedSigningSlashingAmount()
);
relayEntrySubmissionFailureSlashingAmountChangeInitiated = 0;
newRelayEntrySubmissionFailureSlashingAmount = 0;
}
/// @notice Begins the malicious DKG result slashing amount update process.
/// @dev Can be called only by the contract owner.
/// @param _newMaliciousDkgResultSlashingAmount New malicious DKG result
/// slashing amount
function beginMaliciousDkgResultSlashingAmountUpdate(
uint256 _newMaliciousDkgResultSlashingAmount
) external onlyOwner {
/* solhint-disable not-rely-on-time */
newMaliciousDkgResultSlashingAmount = _newMaliciousDkgResultSlashingAmount;
maliciousDkgResultSlashingAmountChangeInitiated = block.timestamp;
emit MaliciousDkgResultSlashingAmountUpdateStarted(
_newMaliciousDkgResultSlashingAmount,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the malicious DKG result slashing amount update
/// process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeMaliciousDkgResultSlashingAmountUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
maliciousDkgResultSlashingAmountChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit MaliciousDkgResultSlashingAmountUpdated(
newMaliciousDkgResultSlashingAmount
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateSlashingParameters(
randomBeacon.relayEntrySubmissionFailureSlashingAmount(),
newMaliciousDkgResultSlashingAmount,
randomBeacon.unauthorizedSigningSlashingAmount()
);
maliciousDkgResultSlashingAmountChangeInitiated = 0;
newMaliciousDkgResultSlashingAmount = 0;
}
/// @notice Begins the unauthorized signing slashing amount update process.
/// @dev Can be called only by the contract owner.
/// @param _newUnauthorizedSigningSlashingAmount New unauthorized signing
/// slashing amount
function beginUnauthorizedSigningSlashingAmountUpdate(
uint256 _newUnauthorizedSigningSlashingAmount
) external onlyOwner {
/* solhint-disable not-rely-on-time */
newUnauthorizedSigningSlashingAmount = _newUnauthorizedSigningSlashingAmount;
unauthorizedSigningSlashingAmountChangeInitiated = block.timestamp;
emit UnauthorizedSigningSlashingAmountUpdateStarted(
_newUnauthorizedSigningSlashingAmount,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the unauthorized signing slashing amount update
/// process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeUnauthorizedSigningSlashingAmountUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
unauthorizedSigningSlashingAmountChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
)
{
emit UnauthorizedSigningSlashingAmountUpdated(
newUnauthorizedSigningSlashingAmount
);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateSlashingParameters(
randomBeacon.relayEntrySubmissionFailureSlashingAmount(),
randomBeacon.maliciousDkgResultSlashingAmount(),
newUnauthorizedSigningSlashingAmount
);
unauthorizedSigningSlashingAmountChangeInitiated = 0;
newUnauthorizedSigningSlashingAmount = 0;
}
/// @notice Begins the minimum authorization amount update process.
/// @dev Can be called only by the contract owner.
/// @param _newMinimumAuthorization New minimum authorization amount.
function beginMinimumAuthorizationUpdate(uint96 _newMinimumAuthorization)
external
onlyOwner
{
/* solhint-disable not-rely-on-time */
newMinimumAuthorization = _newMinimumAuthorization;
minimumAuthorizationChangeInitiated = block.timestamp;
emit MinimumAuthorizationUpdateStarted(
_newMinimumAuthorization,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the minimum authorization amount update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeMinimumAuthorizationUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
minimumAuthorizationChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
)
{
emit MinimumAuthorizationUpdated(newMinimumAuthorization);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateAuthorizationParameters(
newMinimumAuthorization,
randomBeacon.authorizationDecreaseDelay()
);
minimumAuthorizationChangeInitiated = 0;
newMinimumAuthorization = 0;
}
/// @notice Begins the authorization decrease delay update process.
/// @dev Can be called only by the contract owner.
/// @param _newAuthorizationDecreaseDelay New authorization decrease delay
function beginAuthorizationDecreaseDelayUpdate(
uint64 _newAuthorizationDecreaseDelay
) external onlyOwner {
/* solhint-disable not-rely-on-time */
newAuthorizationDecreaseDelay = _newAuthorizationDecreaseDelay;
authorizationDecreaseDelayChangeInitiated = block.timestamp;
emit AuthorizationDecreaseDelayUpdateStarted(
_newAuthorizationDecreaseDelay,
block.timestamp
);
/* solhint-enable not-rely-on-time */
}
/// @notice Finalizes the authorization decrease delay update process.
/// @dev Can be called only by the contract owner, after the governance
/// delay elapses.
function finalizeAuthorizationDecreaseDelayUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
authorizationDecreaseDelayChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
)
{
emit AuthorizationDecreaseDelayUpdated(newAuthorizationDecreaseDelay);
// slither-disable-next-line reentrancy-no-eth
randomBeacon.updateAuthorizationParameters(
randomBeacon.minimumAuthorization(),
newAuthorizationDecreaseDelay
);
authorizationDecreaseDelayChangeInitiated = 0;
newAuthorizationDecreaseDelay = 0;
}
/// @notice Withdraws rewards belonging to operators marked as ineligible
/// for sortition pool rewards.
/// @dev Can be called only by the contract owner.
/// @param recipient Recipient of withdrawn rewards.
function withdrawIneligibleRewards(address recipient) external onlyOwner {
randomBeacon.withdrawIneligibleRewards(recipient);
}
/// @notice Get the time remaining until the relay request fee can be
/// updated.
/// @return Remaining time in seconds.
function getRemainingRelayRequestFeeUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
relayRequestFeeChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the relay entry submission
/// eligibility delay can be updated.
/// @return Remaining time in seconds.
function getRemainingRelayEntrySubmissionEligibilityDelayUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
relayEntrySubmissionEligibilityDelayChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the relay entry hard timeout can be
/// updated.
/// @return Remaining time in seconds.
function getRemainingRelayEntryHardTimeoutUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
relayEntryHardTimeoutChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the callback gas limit can be
/// updated.
/// @return Remaining time in seconds.
function getRemainingCallbackGasLimitUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
callbackGasLimitChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the group creation frequency can be
/// updated.
/// @return Remaining time in seconds.
function getRemainingGroupCreationFrequencyUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
groupCreationFrequencyChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the group lifetime can be updated.
/// @return Remaining time in seconds.
function getRemainingGroupLifetimeUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
groupLifetimeChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the DKG result challenge period
/// length can be updated.
/// @return Remaining time in seconds.
function getRemainingDkgResultChallengePeriodLengthUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
dkgResultChallengePeriodLengthChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the DKG result submission
/// eligibility delay can be updated.
/// @return Remaining time in seconds.
function getRemainingDkgResultSubmissionEligibilityDelayUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
dkgResultSubmissionEligibilityDelayChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the DKG result submission reward
/// can be updated.
/// @return Remaining time in seconds.
function getRemainingDkgResultSubmissionRewardUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
dkgResultSubmissionRewardChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the sortition pool unlocking reward
/// can be updated.
/// @return Remaining time in seconds.
function getRemainingSortitionPoolUnlockingRewardUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
sortitionPoolUnlockingRewardChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the ineligible operator notifier
/// reward can be updated.
/// @return Remaining time in seconds.
function getRemainingIneligibleOperatorNotifierRewardUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
ineligibleOperatorNotifierRewardChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the relay entry submission failure
/// slashing amount can be updated.
/// @return Remaining time in seconds.
function getRemainingRelayEntrySubmissionFailureSlashingAmountUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
relayEntrySubmissionFailureSlashingAmountChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the malicious DKG result
/// slashing amount can be updated.
/// @return Remaining time in seconds.
function getRemainingMaliciousDkgResultSlashingAmountUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
maliciousDkgResultSlashingAmountChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the unauthorized signing
/// slashing amount can be updated.
/// @return Remaining time in seconds.
function getRemainingUnauthorizedSigningSlashingAmountUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
unauthorizedSigningSlashingAmountChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the minimum authorization amount
/// can be updated.
/// @return Remaining time in seconds.
function getRemainingMimimumAuthorizationUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
minimumAuthorizationChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
);
}
function getRemainingAuthorizationDecreaseDelayUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
authorizationDecreaseDelayChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the sortition pool rewards ban
/// duration can be updated.
/// @return Remaining time in seconds.
function getRemainingSortitionPoolRewardsBanDurationUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
sortitionPoolRewardsBanDurationChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the relay entry timeout
/// notification reward multiplier duration can be updated.
/// @return Remaining time in seconds.
function getRemainingRelayEntryTimeoutNotificationRewardMultiplierUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
relayEntryTimeoutNotificationRewardMultiplierChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the unauthorized signing
/// notification reward multiplier duration can be updated.
/// @return Remaining time in seconds.
function getRemainingUnauthorizedSigningNotificationRewardMultiplierUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
unauthorizedSigningNotificationRewardMultiplierChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Get the time remaining until the DKG malicious result
/// notification reward multiplier duration can be updated.
/// @return Remaining time in seconds.
function getRemainingDkgMaliciousResultNotificationRewardMultiplierUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
dkgMaliciousResultNotificationRewardMultiplierChangeInitiated,
STANDARD_PARAMETER_GOVERNANCE_DELAY
);
}
/// @notice Gets the time remaining until the governable parameter update
/// can be committed.
/// @param changeTimestamp Timestamp indicating the beginning of the change.
/// @param delay Governance delay.
/// @return Remaining time in seconds.
function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay)
internal
view
returns (uint256)
{
require(changeTimestamp > 0, "Change not initiated");
/* solhint-disable-next-line not-rely-on-time */
uint256 elapsed = block.timestamp - changeTimestamp;
if (elapsed >= delay) {
return 0;
} else {
return delay - elapsed;
}
}
}
|
Get the time remaining until the relay entry hard timeout can be updated. return Remaining time in seconds.
|
function getRemainingRelayEntryHardTimeoutUpdateTime()
external
view
returns (uint256)
{
return
getRemainingChangeTime(
relayEntryHardTimeoutChangeInitiated,
CRITICAL_PARAMETER_GOVERNANCE_DELAY
);
}
| 12,899,162
|
./partial_match/1/0xCC0dFf3BDEA5aE9d48B682c2dE2014dBd0f3b3A3/sources/ROSIE.sol
|
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
|
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;
}
| 9,225,828
|
./full_match/1/0x025030BdAa159f281cAe63873E68313a703725A5/sources/contracts/libraries/GelatoUserProxySet.sol
|
Add a proxy to a set. O(1). Returns false if the proxy was already in the set./ The element is stored at length-1, but we add 1 to all indexes and use 0 as a sentinel proxy
|
function add(Set storage set, GelatoUserProxy proxy)
internal
returns (bool)
{
if (!contains(set, proxy)) {
set.gelatoUserProxies.push(proxy);
set.index[proxy] = set.gelatoUserProxies.length;
return true;
return false;
}
}
| 9,651,585
|
pragma solidity ^0.5.8;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "solidity-bytes-utils/contracts/BytesLib.sol";
import "./UsingLockedGold.sol";
import "./interfaces/IValidators.sol";
import "../common/Initializable.sol";
import "../common/FixidityLib.sol";
import "../common/linkedlists/AddressLinkedList.sol";
import "../common/linkedlists/AddressSortedLinkedList.sol";
/**
* @title A contract for registering and electing Validator Groups and Validators.
*/
contract Validators is IValidators, Ownable, ReentrancyGuard, Initializable, UsingLockedGold {
using FixidityLib for FixidityLib.Fraction;
using AddressLinkedList for LinkedList.List;
using AddressSortedLinkedList for SortedLinkedList.List;
using SafeMath for uint256;
using BytesLib for bytes;
// TODO(asa): These strings should be modifiable
struct ValidatorGroup {
string identifier;
string name;
string url;
LinkedList.List members;
}
// TODO(asa): These strings should be modifiable
struct Validator {
string identifier;
string name;
string url;
bytes publicKeysData;
address affiliation;
}
struct LockedGoldCommitment {
uint256 noticePeriod;
uint256 value;
}
mapping(address => ValidatorGroup) private groups;
mapping(address => Validator) private validators;
// TODO(asa): Implement abstaining
mapping(address => address) public voters;
address[] private _groups;
address[] private _validators;
SortedLinkedList.List private votes;
// TODO(asa): Support different requirements for groups vs. validators.
LockedGoldCommitment private registrationRequirement;
uint256 public minElectableValidators;
uint256 public maxElectableValidators;
address constant PROOF_OF_POSSESSION = address(0xff - 4);
event MinElectableValidatorsSet(
uint256 minElectableValidators
);
event MaxElectableValidatorsSet(
uint256 maxElectableValidators
);
event RegistrationRequirementSet(
uint256 value,
uint256 noticePeriod
);
event ValidatorRegistered(
address indexed validator,
string identifier,
string name,
string url,
bytes publicKeysData
);
event ValidatorDeregistered(
address indexed validator
);
event ValidatorAffiliated(
address indexed validator,
address indexed group
);
event ValidatorDeaffiliated(
address indexed validator,
address indexed group
);
event ValidatorGroupRegistered(
address indexed group,
string identifier,
string name,
string url
);
event ValidatorGroupDeregistered(
address indexed group
);
event ValidatorGroupMemberAdded(
address indexed group,
address indexed validator
);
event ValidatorGroupMemberRemoved(
address indexed group,
address indexed validator
);
event ValidatorGroupMemberReordered(
address indexed group,
address indexed validator
);
event ValidatorGroupEmptied(
address indexed group
);
event ValidatorGroupVoteCast(
address indexed account,
address indexed group,
uint256 weight
);
event ValidatorGroupVoteRevoked(
address indexed account,
address indexed group,
uint256 weight
);
/**
* @notice Initializes critical variables.
* @param registryAddress The address of the registry contract.
* @param _minElectableValidators The minimum number of validators that can be elected.
* @param _maxElectableValidators The maximum number of validators that can be elected.
* @param requirementValue The minimum Locked Gold commitment value to register a group or
validator.
* @param requirementNoticePeriod The minimum Locked Gold commitment notice period to register
* a group or validator.
* @dev Should be called only once.
*/
function initialize(
address registryAddress,
uint256 _minElectableValidators,
uint256 _maxElectableValidators,
uint256 requirementValue,
uint256 requirementNoticePeriod
)
external
initializer
{
require(_minElectableValidators > 0 && _maxElectableValidators >= _minElectableValidators);
_transferOwnership(msg.sender);
setRegistry(registryAddress);
minElectableValidators = _minElectableValidators;
maxElectableValidators = _maxElectableValidators;
registrationRequirement.value = requirementValue;
registrationRequirement.noticePeriod = requirementNoticePeriod;
}
/**
* @notice Updates the minimum number of validators that can be elected.
* @param _minElectableValidators The minimum number of validators that can be elected.
* @return True upon success.
*/
function setMinElectableValidators(
uint256 _minElectableValidators
)
external
onlyOwner
returns (bool)
{
require(
_minElectableValidators > 0 &&
_minElectableValidators != minElectableValidators &&
_minElectableValidators <= maxElectableValidators
);
minElectableValidators = _minElectableValidators;
emit MinElectableValidatorsSet(_minElectableValidators);
return true;
}
/**
* @notice Updates the maximum number of validators that can be elected.
* @param _maxElectableValidators The maximum number of validators that can be elected.
* @return True upon success.
*/
function setMaxElectableValidators(
uint256 _maxElectableValidators
)
external
onlyOwner
returns (bool)
{
require(
_maxElectableValidators != maxElectableValidators &&
_maxElectableValidators >= minElectableValidators
);
maxElectableValidators = _maxElectableValidators;
emit MaxElectableValidatorsSet(_maxElectableValidators);
return true;
}
/**
* @notice Updates the minimum bonding requirements to register a validator group or validator.
* @param value The minimum Locked Gold commitment value to register a group or validator.
* @param noticePeriod The minimum Locked Gold commitment notice period to register a group or
* validator.
* @return True upon success.
* @dev The new requirement is only enforced for future validator or group registrations.
*/
function setRegistrationRequirement(
uint256 value,
uint256 noticePeriod
)
external
onlyOwner
returns (bool)
{
require(
value != registrationRequirement.value ||
noticePeriod != registrationRequirement.noticePeriod
);
registrationRequirement.value = value;
registrationRequirement.noticePeriod = noticePeriod;
emit RegistrationRequirementSet(value, noticePeriod);
return true;
}
/**
* @notice Registers a validator unaffiliated with any validator group.
* @param identifier An identifier for this validator.
* @param name A name for the validator.
* @param url A URL for the validator.
* @param noticePeriod The notice period of the Locked Gold commitment that meets the
* requirements for validator registration.
* @param publicKeysData Comprised of three tightly-packed elements:
* - publicKey - The public key that the validator is using for consensus, should match
* msg.sender. 64 bytes.
* - blsPublicKey - The BLS public key that the validator is using for consensus, should pass
* proof of possession. 48 bytes.
* - blsPoP - The BLS public key proof of possession. 96 bytes.
* @return True upon success.
* @dev Fails if the account is already a validator or validator group.
* @dev Fails if the account does not have sufficient weight.
*/
function registerValidator(
string calldata identifier,
string calldata name,
string calldata url,
bytes calldata publicKeysData,
uint256 noticePeriod
)
external
nonReentrant
returns (bool)
{
require(
bytes(identifier).length > 0 &&
bytes(name).length > 0 &&
bytes(url).length > 0 &&
// secp256k1 public key + BLS public key + BLS proof of possession
publicKeysData.length == (64 + 48 + 96)
);
bytes memory proofOfPossessionBytes = publicKeysData.slice(64, 48 + 96);
require(checkProofOfPossession(proofOfPossessionBytes));
address account = getAccountFromValidator(msg.sender);
require(!isValidator(account) && !isValidatorGroup(account));
require(meetsRegistrationRequirements(account, noticePeriod));
Validator memory validator = Validator(identifier, name, url, publicKeysData, address(0));
validators[account] = validator;
_validators.push(account);
emit ValidatorRegistered(account, identifier, name, url, publicKeysData);
return true;
}
/**
* @notice Checks a BLS proof of possession.
* @param proofOfPossessionBytes The public key and signature of the proof of possession.
* @return True upon success.
*/
function checkProofOfPossession(bytes memory proofOfPossessionBytes) private returns (bool) {
bool success;
(success, ) = PROOF_OF_POSSESSION.call.value(0).gas(gasleft())(proofOfPossessionBytes);
return success;
}
/**
* @notice De-registers a validator, removing it from the group for which it is a member.
* @param index The index of this validator in the list of all validators.
* @return True upon success.
* @dev Fails if the account is not a validator.
*/
function deregisterValidator(uint256 index) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidator(account));
Validator storage validator = validators[account];
if (validator.affiliation != address(0)) {
_deaffiliate(validator, account);
}
delete validators[account];
deleteElement(_validators, account, index);
emit ValidatorDeregistered(account);
return true;
}
/**
* @notice Affiliates a validator with a group, allowing it to be added as a member.
* @param group The validator group with which to affiliate.
* @return True upon success.
* @dev De-affiliates with the previously affiliated group if present.
*/
function affiliate(address group) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidator(account) && isValidatorGroup(group));
Validator storage validator = validators[account];
if (validator.affiliation != address(0)) {
_deaffiliate(validator, account);
}
validator.affiliation = group;
emit ValidatorAffiliated(account, group);
return true;
}
/**
* @notice De-affiliates a validator, removing it from the group for which it is a member.
* @return True upon success.
* @dev Fails if the account is not a validator with non-zero affiliation.
*/
function deaffiliate() external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidator(account));
Validator storage validator = validators[account];
require(validator.affiliation != address(0));
_deaffiliate(validator, account);
return true;
}
/**
* @notice Registers a validator group with no member validators.
* @param identifier A identifier for this validator group.
* @param name A name for the validator group.
* @param url A URL for the validator group.
* @param noticePeriod The notice period of the Locked Gold commitment that meets the
* requirements for validator registration.
* @return True upon success.
* @dev Fails if the account is already a validator or validator group.
* @dev Fails if the account does not have sufficient weight.
*/
function registerValidatorGroup(
string calldata identifier,
string calldata name,
string calldata url,
uint256 noticePeriod
)
external
nonReentrant
returns (bool)
{
require(bytes(identifier).length > 0 && bytes(name).length > 0 && bytes(url).length > 0);
address account = getAccountFromValidator(msg.sender);
require(!isValidator(account) && !isValidatorGroup(account));
require(meetsRegistrationRequirements(account, noticePeriod));
ValidatorGroup storage group = groups[account];
group.identifier = identifier;
group.name = name;
group.url = url;
_groups.push(account);
emit ValidatorGroupRegistered(account, identifier, name, url);
return true;
}
/**
* @notice De-registers a validator group.
* @param index The index of this validator group in the list of all validator groups.
* @return True upon success.
* @dev Fails if the account is not a validator group with no members.
*/
function deregisterValidatorGroup(uint256 index) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
// Only empty Validator Groups can be deregistered.
require(isValidatorGroup(account) && groups[account].members.numElements == 0);
delete groups[account];
deleteElement(_groups, account, index);
emit ValidatorGroupDeregistered(account);
return true;
}
/**
* @notice Adds a member to the end of a validator group's list of members.
* @param validator The validator to add to the group
* @return True upon success.
* @dev Fails if `validator` has not set their affiliation to this account.
*/
function addMember(address validator) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidatorGroup(account) && isValidator(validator));
ValidatorGroup storage group = groups[account];
require(validators[validator].affiliation == account && !group.members.contains(validator));
group.members.push(validator);
emit ValidatorGroupMemberAdded(account, validator);
return true;
}
/**
* @notice Removes a member from a validator group.
* @param validator The validator to remove from the group
* @return True upon success.
* @dev Fails if `validator` is not a member of the account's group.
*/
function removeMember(address validator) external nonReentrant returns (bool) {
address account = getAccountFromValidator(msg.sender);
require(isValidatorGroup(account) && isValidator(validator));
return _removeMember(account, validator);
}
/**
* @notice Reorders a member within a validator group.
* @param validator The validator to reorder.
* @param lesserMember The member who will be behind `validator`, or 0 if `validator` will be the
* last member.
* @param greaterMember The member who will be ahead of `validator`, or 0 if `validator` will be
* the first member.
* @return True upon success.
* @dev Fails if `validator` is not a member of the account's validator group.
*/
function reorderMember(
address validator,
address lesserMember,
address greaterMember
)
external
nonReentrant
returns (bool)
{
address account = getAccountFromValidator(msg.sender);
require(isValidatorGroup(account) && isValidator(validator));
ValidatorGroup storage group = groups[account];
require(group.members.contains(validator));
group.members.update(validator, lesserMember, greaterMember);
emit ValidatorGroupMemberReordered(account, validator);
return true;
}
/**
* @notice Casts a vote for a validator group.
* @param group The validator group to vote for.
* @param lesser The group receiving fewer votes than `group`, or 0 if `group` has the
* fewest votes of any validator group.
* @param greater The group receiving more votes than `group`, or 0 if `group` has the
* most votes of any validator group.
* @return True upon success.
* @dev Fails if `group` is empty or not a validator group.
* @dev Fails if the account is frozen.
*/
function vote(
address group,
address lesser,
address greater
)
external
nonReentrant
returns (bool)
{
// Empty validator groups are not electable.
require(isValidatorGroup(group) && groups[group].members.numElements > 0);
address account = getAccountFromVoter(msg.sender);
require(!isVotingFrozen(account));
require(voters[account] == address(0));
uint256 weight = getAccountWeight(account);
require(weight > 0);
if (votes.contains(group)) {
votes.update(
group,
votes.getValue(group).add(uint256(weight)),
lesser,
greater
);
} else {
votes.insert(
group,
weight,
lesser,
greater
);
}
voters[account] = group;
emit ValidatorGroupVoteCast(account, group, weight);
return true;
}
/**
* @notice Revokes an outstanding vote for a validator group.
* @param lesser The group receiving fewer votes than the group for which the vote was revoked,
* or 0 if that group has the fewest votes of any validator group.
* @param greater The group receiving more votes than the group for which the vote was revoked,
* or 0 if that group has the most votes of any validator group.
* @return True upon success.
* @dev Fails if the account has not voted on a validator group.
*/
function revokeVote(
address lesser,
address greater
)
external
nonReentrant
returns (bool)
{
address account = getAccountFromVoter(msg.sender);
address group = voters[account];
require(group != address(0));
uint256 weight = getAccountWeight(account);
// If the group we had previously voted on removed all its members it is no longer eligible
// to receive votes and we don't have to worry about removing our vote.
if (votes.contains(group)) {
require(weight > 0);
uint256 newVoteTotal = votes.getValue(group).sub(uint256(weight));
if (newVoteTotal > 0) {
votes.update(
group,
newVoteTotal,
lesser,
greater
);
} else {
// Groups receiving no votes are not electable.
votes.remove(group);
}
}
voters[account] = address(0);
emit ValidatorGroupVoteRevoked(account, group, weight);
return true;
}
/**
* @notice Returns validator information.
* @param account The account that registered the validator.
* @return The unpacked validator struct.
*/
function getValidator(
address account
)
external
view
returns (
string memory identifier,
string memory name,
string memory url,
bytes memory publicKeysData,
address affiliation
)
{
require(isValidator(account));
Validator storage validator = validators[account];
return (
validator.identifier,
validator.name,
validator.url,
validator.publicKeysData,
validator.affiliation
);
}
/**
* @notice Returns validator group information.
* @param account The account that registered the validator group.
* @return The unpacked validator group struct.
*/
function getValidatorGroup(
address account
)
external
view
returns (string memory, string memory, string memory, address[] memory)
{
require(isValidatorGroup(account));
ValidatorGroup storage group = groups[account];
return (group.identifier, group.name, group.url, group.members.getKeys());
}
/**
* @notice Returns electable validator group addresses and their vote totals.
* @return Electable validator group addresses and their vote totals.
*/
function getValidatorGroupVotes() external view returns (address[] memory, uint256[] memory) {
return votes.getElements();
}
/**
* @notice Returns the number of votes a particular validator group has received.
* @param group The account that registered the validator group.
* @return The number of votes a particular validator group has received.
*/
function getVotesReceived(address group) external view returns (uint256) {
return votes.getValue(group);
}
/**
* @notice Returns the Locked Gold commitment requirements to register a validator or group.
* @return The minimum value and notice period for the Locked Gold commitment.
*/
function getRegistrationRequirement() external view returns (uint256, uint256) {
return (registrationRequirement.value, registrationRequirement.noticePeriod);
}
/**
* @notice Returns the list of registered validator accounts.
* @return The list of registered validator accounts.
*/
function getRegisteredValidators() external view returns (address[] memory) {
return _validators;
}
/**
* @notice Returns the list of registered validator group accounts.
* @return The list of registered validator group addresses.
*/
function getRegisteredValidatorGroups() external view returns (address[] memory) {
return _groups;
}
/**
* @notice Returns whether a particular account is a registered validator or validator group.
* @param account The account.
* @return Whether a particular account is a registered validator or validator group.
*/
function isValidating(address account) external view returns (bool) {
return isValidator(account) || isValidatorGroup(account);
}
/**
* @notice Returns whether a particular account is voting for a validator group.
* @param account The account.
* @return Whether a particular account is voting for a validator group.
*/
function isVoting(address account) external view returns (bool) {
return (voters[account] != address(0));
}
/**
* @notice Returns a list of elected validators with seats allocated to groups via the D'Hondt
* method.
* @return The list of elected validators.
* @dev See https://en.wikipedia.org/wiki/D%27Hondt_method#Allocation for more information.
*/
/* solhint-disable code-complexity */
function getValidators() external view returns (address[] memory) {
// Only members of these validator groups are eligible for election.
uint256 numElectionGroups = maxElectableValidators;
if (numElectionGroups > votes.list.numElements) {
numElectionGroups = votes.list.numElements;
}
address[] memory electionGroups = votes.list.headN(numElectionGroups);
// Holds the number of members elected for each of the eligible validator groups.
uint256[] memory numMembersElected = new uint256[](electionGroups.length);
uint256 totalNumMembersElected = 0;
bool memberElectedInRound = true;
// Assign a number of seats to each validator group.
while (totalNumMembersElected < maxElectableValidators && memberElectedInRound) {
memberElectedInRound = false;
uint256 groupIndex = 0;
FixidityLib.Fraction memory maxN = FixidityLib.wrap(0);
for (uint256 i = 0; i < electionGroups.length; i = i.add(1)) {
bool isWinningestGroupInRound = false;
(maxN, isWinningestGroupInRound) = dHondt(maxN, electionGroups[i], numMembersElected[i]);
if (isWinningestGroupInRound) {
memberElectedInRound = true;
groupIndex = i;
}
}
if (memberElectedInRound) {
numMembersElected[groupIndex] = numMembersElected[groupIndex].add(1);
totalNumMembersElected = totalNumMembersElected.add(1);
}
}
require(totalNumMembersElected >= minElectableValidators);
// Grab the top validators from each group that won seats.
address[] memory electedValidators = new address[](totalNumMembersElected);
totalNumMembersElected = 0;
for (uint256 i = 0; i < electionGroups.length; i = i.add(1)) {
address[] memory electedGroupMembers = groups[electionGroups[i]].members.headN(
numMembersElected[i]
);
for (uint256 j = 0; j < electedGroupMembers.length; j = j.add(1)) {
// We use the validating delegate if one is set.
electedValidators[totalNumMembersElected] = getValidatorFromAccount(electedGroupMembers[j]);
totalNumMembersElected = totalNumMembersElected.add(1);
}
}
return electedValidators;
}
/* solhint-enable code-complexity */
/**
* @notice Returns whether a particular account has a registered validator group.
* @param account The account.
* @return Whether a particular address is a registered validator group.
*/
function isValidatorGroup(address account) public view returns (bool) {
return bytes(groups[account].identifier).length > 0;
}
/**
* @notice Returns whether a particular account has a registered validator.
* @param account The account.
* @return Whether a particular address is a registered validator.
*/
function isValidator(address account) public view returns (bool) {
return bytes(validators[account].identifier).length > 0;
}
/**
* @notice Returns whether an account meets the requirements to register a validator or group.
* @param account The account.
* @param noticePeriod The notice period of the Locked Gold commitment that meets the
* requirements.
* @return Whether an account meets the requirements to register a validator or group.
*/
function meetsRegistrationRequirements(
address account,
uint256 noticePeriod
)
public
view
returns (bool)
{
uint256 value = getLockedCommitmentValue(account, noticePeriod);
return (
value >= registrationRequirement.value &&
noticePeriod >= registrationRequirement.noticePeriod
);
}
/**
* @notice Deletes an element from a list of addresses.
* @param list The list of addresses.
* @param element The address to delete.
* @param index The index of `element` in the list.
*/
function deleteElement(address[] storage list, address element, uint256 index) private {
require(index < list.length && list[index] == element);
uint256 lastIndex = list.length.sub(1);
list[index] = list[lastIndex];
list[lastIndex] = address(0);
list.length = lastIndex;
}
/**
* @notice Removes a member from a validator group.
* @param group The group from which the member should be removed.
* @param validator The validator to remove from the group.
* @return True upon success.
* @dev If `validator` was the only member of `group`, `group` becomes unelectable.
* @dev Fails if `validator` is not a member of `group`.
*/
function _removeMember(address group, address validator) private returns (bool) {
ValidatorGroup storage _group = groups[group];
require(validators[validator].affiliation == group && _group.members.contains(validator));
_group.members.remove(validator);
emit ValidatorGroupMemberRemoved(group, validator);
// Empty validator groups are not electable.
if (groups[group].members.numElements == 0) {
if (votes.contains(group)) {
votes.remove(group);
}
emit ValidatorGroupEmptied(group);
}
return true;
}
/**
* @notice De-affiliates a validator, removing it from the group for which it is a member.
* @param validator The validator to deaffiliate from their affiliated validator group.
* @param validatorAccount The LockedGold account of the validator.
* @return True upon success.
*/
function _deaffiliate(
Validator storage validator,
address validatorAccount
)
private
returns (bool)
{
address affiliation = validator.affiliation;
ValidatorGroup storage group = groups[affiliation];
if (group.members.contains(validatorAccount)) {
_removeMember(affiliation, validatorAccount);
}
emit ValidatorDeaffiliated(validatorAccount, affiliation);
validator.affiliation = address(0);
return true;
}
/**
* @notice Runs D'Hondt for a validator group.
* @param maxN The maximum number of votes per elected seat for a group in this round.
* @param groupAddress The address of the validator group.
* @param numMembersElected The number of members elected so far for this group.
* @dev See https://en.wikipedia.org/wiki/D%27Hondt_method#Allocation for more information.
* @return The new `maxN` and whether or not the group should win a seat in this round thus far.
*/
function dHondt(
FixidityLib.Fraction memory maxN,
address groupAddress,
uint256 numMembersElected
)
private
view
returns (FixidityLib.Fraction memory, bool)
{
ValidatorGroup storage group = groups[groupAddress];
// Only consider groups with members left to be elected.
if (group.members.numElements > numMembersElected) {
FixidityLib.Fraction memory n = FixidityLib.newFixed(votes.getValue(groupAddress)).divide(
FixidityLib.newFixed(numMembersElected.add(1))
);
if (n.gt(maxN)) {
return (n, true);
}
}
return (maxN, false);
}
}
|
Returns a list of elected validators with seats allocated to groups via the D'Hondt method. return The list of elected validators./ solhint-disable code-complexity / Only members of these validator groups are eligible for election. Assign a number of seats to each validator group. We use the validating delegate if one is set.
|
function getValidators() external view returns (address[] memory) {
uint256 numElectionGroups = maxElectableValidators;
if (numElectionGroups > votes.list.numElements) {
numElectionGroups = votes.list.numElements;
}
address[] memory electionGroups = votes.list.headN(numElectionGroups);
uint256 totalNumMembersElected = 0;
bool memberElectedInRound = true;
while (totalNumMembersElected < maxElectableValidators && memberElectedInRound) {
memberElectedInRound = false;
uint256 groupIndex = 0;
FixidityLib.Fraction memory maxN = FixidityLib.wrap(0);
for (uint256 i = 0; i < electionGroups.length; i = i.add(1)) {
bool isWinningestGroupInRound = false;
(maxN, isWinningestGroupInRound) = dHondt(maxN, electionGroups[i], numMembersElected[i]);
if (isWinningestGroupInRound) {
memberElectedInRound = true;
groupIndex = i;
}
}
if (memberElectedInRound) {
numMembersElected[groupIndex] = numMembersElected[groupIndex].add(1);
totalNumMembersElected = totalNumMembersElected.add(1);
}
}
require(totalNumMembersElected >= minElectableValidators);
totalNumMembersElected = 0;
for (uint256 i = 0; i < electionGroups.length; i = i.add(1)) {
address[] memory electedGroupMembers = groups[electionGroups[i]].members.headN(
numMembersElected[i]
);
for (uint256 j = 0; j < electedGroupMembers.length; j = j.add(1)) {
electedValidators[totalNumMembersElected] = getValidatorFromAccount(electedGroupMembers[j]);
totalNumMembersElected = totalNumMembersElected.add(1);
}
}
return electedValidators;
}
| 5,467,127
|
pragma solidity ^0.4.23;
import "./ownable.sol";
import "./SplitPayment.sol";
contract HdisContent is Ownable {
using SafeMath for uint256;
struct Content {
uint mediaId;
uint mediaType;
address creator;
uint weiPrice;
address[] contributors;
}
// This could be useful for a copyright watchtower
event addContentEvent(Content indexed content);
event purchaseContentEvent(Content indexed content, address buyer);
mapping (uint => Content) private contents;
uint[] private contentIds;
mapping (address => uint[]) private purchases;
mapping (uint256 => uint256) public totalShares;
mapping (uint256 => uint256) public totalReleased;
mapping(uint256 => mapping(address => uint256)) public shares;
mapping(uint256 => mapping(address => uint256)) public released;
mapping(uint256 => address[]) public payees;
/**
* @dev Constructor
*/
constructor() Ownable() public payable {
}
/**
* @dev payable fallback
*/
function () public payable {}
/**
* @dev Claim your share of the balance.
*/
function claim(uint _content) public {
address payee = msg.sender;
payTo(_content, payee);
}
function payTo(uint _content, address _payee) internal {
require(shares[_content][_payee] > 0);
uint256 totalReceived = address(this).balance.add(totalReleased[_content]);
uint256 payment = totalReceived.mul(shares[_content][_payee]).div(totalShares[_content]).sub(released[_content][_payee]);
require(payment != 0);
require(address(this).balance >= payment);
released[_content][_payee] = released[_content][_payee].add(payment);
totalReleased[_content] = totalReleased[_content].add(payment);
_payee.transfer(payment);
}
function distribute(uint _content) internal {
for (uint256 i = 0; i < payees[_content].length; i++) {
payTo(_content, payees[_content][i]);
}
}
/**
* @dev Add a new payee to the contract.
* @param _payee The address of the payee to add.
* @param _shares The number of shares owned by the payee.
*/
function addPayee(uint _content, address _payee, uint256 _shares) internal {
require(_payee != address(0));
require(_shares > 0);
require(shares[_content][_payee] == 0);
payees[_content].push(_payee);
addShares(_content, _payee, _shares);
}
function addShares(uint _content, address _payee, uint256 _shares) internal {
shares[_content][_payee] = _shares;
totalShares[_content] = totalShares[_content].add(_shares);
}
function generateId(string _name, address _creator) private pure
returns (uint) {
return uint(keccak256(_name) ^ keccak256(_creator));
}
function getContentById(uint _id) public view
returns (uint, uint, address, uint, address[]) {
Content memory content = contents[_id];
return (content.mediaId, content.mediaType, content.creator, content.weiPrice, content.contributors);
}
function getContentByName(string _name, address _creator) public view
returns (uint, uint, address, uint, address[]) {
return getContentById(generateId(_name, _creator));
}
function getContentIds() public view returns (uint[]) {
return contentIds;
}
function addContent(string _name, uint _mediaId, uint _mediaType, address _creator, uint _price) public
returns (uint) {
uint id = generateId(_name, _creator);
address[] memory emptyArray;
Content memory _content = Content(_mediaId, _mediaType, _creator, _price, emptyArray);
contents[id] = _content;
contentIds.push(id);
emit addContentEvent(_content);
return id;
}
function addContributor(uint _id, address _contributor) public onlyOwner {
contents[_id].contributors.push(_contributor);
if(shares[_id][_contributor] == 0) {
addPayee(_id, _contributor, 1);
}
else {
addShares(_id, _contributor, 1);
}
}
// TODO: limit num of purchases to make
// the array traversable in a reasonable time
function purchaseContent(uint _contentId) public payable {
uint fee = msg.value;
Content memory content = contents[_contentId];
require(fee >= content.weiPrice);
address buyer = msg.sender;
purchases[buyer].push(_contentId);
emit purchaseContentEvent(content, buyer);
distribute(_contentId);
}
}
|
Add a new payee to the contract. _payee The address of the payee to add. _shares The number of shares owned by the payee./
|
function addPayee(uint _content, address _payee, uint256 _shares) internal {
require(_payee != address(0));
require(_shares > 0);
require(shares[_content][_payee] == 0);
payees[_content].push(_payee);
addShares(_content, _payee, _shares);
}
| 12,744,115
|
./partial_match/1/0xE457D48c9B25C1B210d041Ff5FE162aBd87E5e41/sources/AGStakingEnterprise.sol
|
Deposit AG token _amount amount to be locked _duration lock duration (possible 3,6,12 months)/
|
function deposit(uint256 _amount, uint256 _duration) external {
require(block.timestamp < depositEndTime, "Deposit not allowed");
require(_amount >= MIN_DEPOSIT_AMOUNT, "Amount too low");
require(
_duration == MONTH_3 || _duration == MONTH_6 || _duration == MONTH_12,
"Invalid duration"
);
uint256 reward;
if (_duration == MONTH_3) {
}
lockedData[msg.sender].push(Lock({
amount: _amount,
reward: reward,
depositTime: block.timestamp,
maturityTime: block.timestamp + _duration,
status: Status.Active
}));
token.safeTransferFrom(msg.sender, address(this), _amount);
emit Deposit(msg.sender, _amount, _duration);
}
| 4,470,719
|
./full_match/1/0xD3f53dDA37e606A78bC1B45F27B3D3A05A1FA07b/sources/src/shares/Shares.sol
|
Transfers _amount tokens to the company and burns them. The meaning of this operation depends on the circumstances and the fate of the shares does not necessarily follow the fate of the tokens. For example, the company itself might call this function to implement a formal decision to destroy some of the outstanding shares. Also, this function might be called by an owner to return the shares to the company and get them back in another form under an according agreement (e.g. printed certificates or tokens on a different blockchain). It is not recommended to call this function without having agreed with the company on the further fate of the shares in question./
|
function burn(uint256 _amount) override external {
_transfer(msg.sender, address(this), _amount);
_burn(address(this), _amount);
}
| 4,891,145
|
./full_match/137/0x7B458DBE4E7a693BE2e691DEdDff4607104f1266/sources/project_/contracts/bridges/UPoolBridgeAdapter.sol
|
updates accepted tokens
|
function updateAcceptedTokens(address[] calldata tokens, bool accepted) external onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
if (accepted) {
_acceptedTokens[tokens[i]] = true;
delete _acceptedTokens[tokens[i]];
}
emit AcceptedTokenChanged(tokens[i], accepted);
}
}
| 4,752,726
|
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "./CToken.sol";
interface CompLike {
function delegate(address delegatee) external;
}
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @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
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @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 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) override external returns (uint) {
mintInternal(mintAmount);
return NO_ERROR;
}
/**
* @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) override external returns (uint) {
redeemInternal(redeemTokens);
return NO_ERROR;
}
/**
* @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) override external returns (uint) {
redeemUnderlyingInternal(redeemAmount);
return 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 borrow(uint borrowAmount) override external returns (uint) {
borrowInternal(borrowAmount);
return NO_ERROR;
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) override external returns (uint) {
repayBorrowInternal(repayAmount);
return NO_ERROR;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) override external returns (uint) {
repayBorrowBehalfInternal(borrower, repayAmount);
return NO_ERROR;
}
/**
* @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 repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) override external returns (uint) {
liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return NO_ERROR;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20NonStandardInterface token) override external {
require(msg.sender == admin, "CErc20::sweepToken: only admin can sweep tokens");
require(address(token) != underlying, "CErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.transfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) override external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** 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 tokens owned by this contract
*/
function getCashPrior() virtual override internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) virtual override internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of override external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) virtual override internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of override external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
/**
* @notice Admin call to delegate the votes of the COMP-like underlying
* @param compLikeDelegatee The address to delegate votes to
* @dev CTokens whose underlying are not CompLike should revert here
*/
function _delegateCompLikeTo(address compLikeDelegatee) external {
require(msg.sender == admin, "only the admin may set the comp-like delegate");
CompLike(underlying).delegate(compLikeDelegatee);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "./CErc20.sol";
/**
* @title Compound's CErc20Delegate Contract
* @notice CTokens which wrap an EIP-20 underlying and are delegated to
* @author Compound
*/
contract CErc20Delegate is CErc20, CDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) virtual override public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() virtual override public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _resignImplementation");
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./EIP20Interface.sol";
import "./InterestRateModel.sol";
import "./ExponentialNoError.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
abstract contract CToken is CTokenInterface, ExponentialNoError, 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 == 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 == 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 0 if the transfer succeeded, else revert
*/
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) {
revert TransferComptrollerRejection(allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
revert TransferNotAllowed();
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = type(uint).max;
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
uint allowanceNew = startingAllowance - tokens;
uint srcTokensNew = accountTokens[src] - tokens;
uint dstTokensNew = accountTokens[dst] + tokens;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != type(uint).max) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return 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) override external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == 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) override external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == 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) override 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) override 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) override 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) override external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);
}
/**
* @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) override external view returns (uint, uint, uint, uint) {
return (
NO_ERROR,
accountTokens[account],
borrowBalanceStoredInternal(account),
exchangeRateStoredInternal()
);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() virtual 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() override 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() override 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() override external nonReentrant returns (uint) {
require(accrueInterest() == 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) override external nonReentrant returns (uint) {
require(accrueInterest() == 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) override public view returns (uint) {
return borrowBalanceStoredInternal(account);
}
/**
* @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 (uint) {
/* 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 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
uint principalTimesIndex = borrowSnapshot.principal * borrowIndex;
return principalTimesIndex / borrowSnapshot.interestIndex;
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() override public nonReentrant returns (uint) {
require(accrueInterest() == 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() override public view returns (uint) {
return exchangeRateStoredInternal();
}
/**
* @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() virtual internal view returns (uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return initialExchangeRateMantissa;
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves;
Exp memory exchangeRate = Exp({mantissa: cashPlusBorrowsMinusReserves * expScale / _totalSupply});
return 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() override 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() virtual override public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return 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 */
uint blockDelta = currentBlockNumber - accrualBlockNumberPrior;
/*
* 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 = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta);
uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);
uint totalBorrowsNew = interestAccumulated + borrowsPrior;
uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
/////////////////////////
// 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 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
*/
function mintInternal(uint mintAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
revert MintAccrueInterestFailed(error);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
mintFresh(msg.sender, mintAmount);
}
/**
* @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
*/
function mintFresh(address minter, uint mintAmount) internal {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
revert MintComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert MintFreshnessCheck();
}
Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()});
/////////////////////////
// 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.
*/
uint actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
uint mintTokens = div_(actualMintAmount, exchangeRate);
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
* And write them into storage
*/
totalSupply = totalSupply + mintTokens;
accountTokens[minter] = accountTokens[minter] + mintTokens;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, actualMintAmount, mintTokens);
emit Transfer(address(this), minter, mintTokens);
/* We call the defense hook */
// unused function
// comptroller.mintVerify(address(this), minter, actualMintAmount, mintTokens);
}
/**
* @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
*/
function redeemInternal(uint redeemTokens) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
revert RedeemAccrueInterestFailed(error);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
redeemFresh(payable(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
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
revert RedeemAccrueInterestFailed(error);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
redeemFresh(payable(msg.sender), 0, redeemAmount);
}
/**
* @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)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
/* exchangeRate = invoke Exchange Rate Stored() */
Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal() });
uint redeemTokens;
uint redeemAmount;
/* 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
*/
redeemTokens = redeemTokensIn;
redeemAmount = mul_ScalarTruncate(exchangeRate, redeemTokensIn);
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
redeemTokens = div_(redeemAmountIn, exchangeRate);
redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, redeemTokens);
if (allowed != 0) {
revert RedeemComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert RedeemFreshnessCheck();
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < redeemAmount) {
revert RedeemTransferOutNotPossible();
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We write the previously calculated values into storage.
* Note: Avoid token reentrancy attacks by writing reduced supply before external transfer.
*/
totalSupply = totalSupply - redeemTokens;
accountTokens[redeemer] = accountTokens[redeemer] - redeemTokens;
/*
* 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, redeemAmount);
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), redeemTokens);
emit Redeem(redeemer, redeemAmount, redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, redeemAmount, redeemTokens);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
*/
function borrowInternal(uint borrowAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
revert BorrowAccrueInterestFailed(error);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
borrowFresh(payable(msg.sender), borrowAmount);
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
revert BorrowComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert BorrowFreshnessCheck();
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
revert BorrowCashNotAvailable();
}
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowNew = accountBorrow + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
uint accountBorrowsPrev = borrowBalanceStoredInternal(borrower);
uint accountBorrowsNew = accountBorrowsPrev + borrowAmount;
uint totalBorrowsNew = totalBorrows + borrowAmount;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We write the previously calculated values into storage.
* Note: Avoid token reentrancy attacks by writing increased borrow before external transfer.
`*/
accountBorrows[borrower].principal = accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = totalBorrowsNew;
/*
* 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 emit a Borrow event */
emit Borrow(borrower, borrowAmount, accountBorrowsNew, totalBorrowsNew);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
revert RepayBorrowAccrueInterestFailed(error);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
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, or -1 for the full outstanding amount
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
revert RepayBehalfAccrueInterestFailed(error);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
repayBorrowFresh(msg.sender, borrower, repayAmount);
}
/**
* @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 underlying tokens being returned, or -1 for the full outstanding amount
* @return (uint) the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
revert RepayBorrowComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert RepayBorrowFreshnessCheck();
}
/* We fetch the amount the borrower owes, with accumulated interest */
uint accountBorrowsPrev = borrowBalanceStoredInternal(borrower);
/* If repayAmount == -1, repayAmount = accountBorrows */
uint repayAmountFinal = repayAmount == type(uint).max ? accountBorrowsPrev : 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.
*/
uint actualRepayAmount = doTransferIn(payer, repayAmountFinal);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
uint accountBorrowsNew = accountBorrowsPrev - actualRepayAmount;
uint totalBorrowsNew = totalBorrows - actualRepayAmount;
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, actualRepayAmount, accountBorrowsNew, totalBorrowsNew);
return 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
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
revert LiquidateAccrueBorrowInterestFailed(error);
}
error = cTokenCollateral.accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
revert LiquidateAccrueCollateralInterestFailed(error);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
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
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
revert LiquidateComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert LiquidateFreshnessCheck();
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
revert LiquidateCollateralFreshnessCheck();
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
revert LiquidateLiquidatorIsBorrower();
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
revert LiquidateCloseAmountIsZero();
}
/* Fail if repayAmount = -1 */
if (repayAmount == type(uint).max) {
revert LiquidateCloseAmountIsUintMax();
}
/* Fail if repayBorrow fails */
uint actualRepayAmount = repayBorrowFresh(liquidator, borrower, repayAmount);
/////////////////////////
// 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 == 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
if (address(cTokenCollateral) == address(this)) {
seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
require(cTokenCollateral.seize(liquidator, borrower, seizeTokens) == NO_ERROR, "token seizure failed");
}
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
}
/**
* @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) override external nonReentrant returns (uint) {
seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
return NO_ERROR;
}
/**
* @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
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
revert LiquidateSeizeComptrollerRejection(allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
revert LiquidateSeizeLiquidatorIsBorrower();
}
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
uint protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}));
uint liquidatorSeizeTokens = seizeTokens - protocolSeizeTokens;
Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()});
uint protocolSeizeAmount = mul_ScalarTruncate(exchangeRate, protocolSeizeTokens);
uint totalReservesNew = totalReserves + protocolSeizeAmount;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the calculated values into storage */
totalReserves = totalReservesNew;
totalSupply = totalSupply - protocolSeizeTokens;
accountTokens[borrower] = accountTokens[borrower] - seizeTokens;
accountTokens[liquidator] = accountTokens[liquidator] + liquidatorSeizeTokens;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, liquidatorSeizeTokens);
emit Transfer(borrower, address(this), protocolSeizeTokens);
emit ReservesAdded(address(this), protocolSeizeAmount, totalReservesNew);
}
/*** 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) override external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
revert SetPendingAdminOwnerCheck();
}
// 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 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() override external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
revert AcceptAdminPendingAdminCheck();
}
// 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 = payable(address(0));
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return 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) override public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
revert SetComptrollerOwnerCheck();
}
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 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) override external nonReentrant returns (uint) {
uint error = accrueInterest();
if (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.
revert SetReserveFactorAccrueInterestFailed(error);
}
// _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) {
revert SetReserveFactorAdminCheck();
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert SetReserveFactorFreshCheck();
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
revert SetReserveFactorBoundsCheck();
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return 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 != NO_ERROR) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
revert AddReservesAccrueInterestFailed(error);
}
// _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()) {
revert AddReservesFactorFreshCheck(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;
// 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 (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) override external nonReentrant returns (uint) {
uint error = accrueInterest();
if (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.
revert ReduceReservesAccrueInterestFailed(error);
}
// _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) {
revert ReduceReservesAdminCheck();
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert ReduceReservesFreshCheck();
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
revert ReduceReservesCashNotAvailable();
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
revert ReduceReservesCashValidation();
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// 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 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) override public returns (uint) {
uint error = accrueInterest();
if (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
revert SetInterestRateModelAccrueInterestFailed(error);
}
// _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) {
revert SetInterestRateModelOwnerCheck();
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert SetInterestRateModelFreshCheck();
}
// 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 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() virtual 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) virtual 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) virtual 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
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
import "./EIP20NonStandardInterface.sol";
import "./ErrorReporter.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;
// Maximum borrow rate that can ever be applied (.0005% / block)
uint internal constant borrowRateMaxMantissa = 0.0005e16;
// 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;
// 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;
// Official record of token balances for each account
mapping (address => uint) internal accountTokens;
// 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;
}
// Mapping of account addresses to outstanding borrow balances
mapping(address => BorrowSnapshot) internal accountBorrows;
/**
* @notice Share of seized collateral that is added to reserves
*/
uint public constant protocolSeizeShareMantissa = 2.8e16; //2.8%
}
abstract 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);
/*** User Interface ***/
function transfer(address dst, uint amount) virtual external returns (bool);
function transferFrom(address src, address dst, uint amount) virtual external returns (bool);
function approve(address spender, uint amount) virtual external returns (bool);
function allowance(address owner, address spender) virtual external view returns (uint);
function balanceOf(address owner) virtual external view returns (uint);
function balanceOfUnderlying(address owner) virtual external returns (uint);
function getAccountSnapshot(address account) virtual external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() virtual external view returns (uint);
function supplyRatePerBlock() virtual external view returns (uint);
function totalBorrowsCurrent() virtual external returns (uint);
function borrowBalanceCurrent(address account) virtual external returns (uint);
function borrowBalanceStored(address account) virtual external view returns (uint);
function exchangeRateCurrent() virtual external returns (uint);
function exchangeRateStored() virtual external view returns (uint);
function getCash() virtual external view returns (uint);
function accrueInterest() virtual external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) virtual external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) virtual external returns (uint);
function _acceptAdmin() virtual external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) virtual external returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) virtual external returns (uint);
function _reduceReserves(uint reduceAmount) virtual external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) virtual external returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
abstract contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) virtual external returns (uint);
function redeem(uint redeemTokens) virtual external returns (uint);
function redeemUnderlying(uint redeemAmount) virtual external returns (uint);
function borrow(uint borrowAmount) virtual external returns (uint);
function repayBorrow(uint repayAmount) virtual external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) virtual external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) virtual external returns (uint);
function sweepToken(EIP20NonStandardInterface token) virtual external;
/*** Admin Functions ***/
function _addReserves(uint addAmount) virtual external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
abstract 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) virtual external;
}
abstract 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) virtual external;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() virtual external;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
abstract 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) virtual external returns (uint[] memory);
function exitMarket(address cToken) virtual external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) virtual external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) virtual external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) virtual external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) virtual external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) virtual external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) virtual external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) virtual external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) virtual external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) virtual external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) virtual external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) virtual external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) virtual external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) virtual external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) virtual external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) virtual external view returns (uint, uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
/**
* @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 balance 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 success 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 success 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 success 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 remaining 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);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
/**
* @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 balance 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 success 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 remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
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 {
uint public constant NO_ERROR = 0; // support legacy return codes
error TransferComptrollerRejection(uint256 errorCode);
error TransferNotAllowed();
error TransferNotEnough();
error TransferTooMuch();
error MintComptrollerRejection(uint256 errorCode);
error MintFreshnessCheck();
error MintAccrueInterestFailed(uint256 errorCode);
error RedeemComptrollerRejection(uint256 errorCode);
error RedeemFreshnessCheck();
error RedeemAccrueInterestFailed(uint256 errorCode);
error RedeemTransferOutNotPossible();
error BorrowComptrollerRejection(uint256 errorCode);
error BorrowFreshnessCheck();
error BorrowAccrueInterestFailed(uint256 errorCode);
error BorrowCashNotAvailable();
error RepayBorrowComptrollerRejection(uint256 errorCode);
error RepayBorrowFreshnessCheck();
error RepayBorrowAccrueInterestFailed(uint256 errorCode);
error RepayBehalfAccrueInterestFailed(uint256 errorCode);
error LiquidateComptrollerRejection(uint256 errorCode);
error LiquidateFreshnessCheck();
error LiquidateCollateralFreshnessCheck();
error LiquidateAccrueBorrowInterestFailed(uint256 errorCode);
error LiquidateAccrueCollateralInterestFailed(uint256 errorCode);
error LiquidateLiquidatorIsBorrower();
error LiquidateCloseAmountIsZero();
error LiquidateCloseAmountIsUintMax();
error LiquidateRepayBorrowFreshFailed(uint256 errorCode);
error LiquidateSeizeComptrollerRejection(uint256 errorCode);
error LiquidateSeizeLiquidatorIsBorrower();
error AcceptAdminPendingAdminCheck();
error SetComptrollerOwnerCheck();
error SetPendingAdminOwnerCheck();
error SetReserveFactorAccrueInterestFailed(uint256 errorCode);
error SetReserveFactorAdminCheck();
error SetReserveFactorFreshCheck();
error SetReserveFactorBoundsCheck();
error AddReservesAccrueInterestFailed(uint256 errorCode);
error AddReservesFactorFreshCheck(uint256 actualAddAmount);
error ReduceReservesAccrueInterestFailed(uint256 errorCode);
error ReduceReservesAdminCheck();
error ReduceReservesFreshCheck();
error ReduceReservesCashNotAvailable();
error ReduceReservesCashValidation();
error SetInterestRateModelAccrueInterestFailed(uint256 errorCode);
error SetInterestRateModelOwnerCheck();
error SetInterestRateModelFreshCheck();
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
/**
* @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 a + b;
}
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 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 a * b;
}
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 a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
abstract 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) virtual 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) virtual external view returns (uint);
}
|
Sets a new reserve factor for the protocol (requires fresh interest accrual) Admin function to set a new reserve factor return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller is admin Verify market's block number equals current block number Check newReserveFactor ≤ maxReserveFactor
|
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
if (msg.sender != admin) {
revert SetReserveFactorAdminCheck();
}
if (accrualBlockNumber != getBlockNumber()) {
revert SetReserveFactorFreshCheck();
}
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
revert SetReserveFactorBoundsCheck();
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return NO_ERROR;
}
| 1,632,603
|
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
interface IERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
abstract contract IWETH {
function allowance(address, address) public virtual view returns (uint256);
function balanceOf(address) public virtual view returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(
address,
address,
uint256
) public virtual returns (bool);
function deposit() public payable virtual;
function withdraw(uint256) public virtual;
}
library Address {
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);
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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 Edited so it always first approves 0 and then the value, because of non standard tokens
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_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)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
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 TokenUtils {
using SafeERC20 for IERC20;
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function approveToken(
address _tokenAddr,
address _to,
uint256 _amount
) internal {
if (_tokenAddr == ETH_ADDR) return;
if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) {
IERC20(_tokenAddr).safeApprove(_to, _amount);
}
}
function pullTokensIfNeeded(
address _token,
address _from,
uint256 _amount
) internal returns (uint256) {
// handle max uint amount
if (_amount == type(uint256).max) {
_amount = getBalance(_token, _from);
}
if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) {
IERC20(_token).safeTransferFrom(_from, address(this), _amount);
}
return _amount;
}
function withdrawTokens(
address _token,
address _to,
uint256 _amount
) internal returns (uint256) {
if (_amount == type(uint256).max) {
_amount = getBalance(_token, address(this));
}
if (_to != address(0) && _to != address(this) && _amount != 0) {
if (_token != ETH_ADDR) {
IERC20(_token).safeTransfer(_to, _amount);
} else {
payable(_to).transfer(_amount);
}
}
return _amount;
}
function depositWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).deposit{value: _amount}();
}
function withdrawWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).withdraw(_amount);
}
function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) {
if (_tokenAddr == ETH_ADDR) {
return _acc.balance;
} else {
return IERC20(_tokenAddr).balanceOf(_acc);
}
}
function getTokenDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return IERC20(_token).decimals();
}
}
// Common interface for the Trove Manager.
interface ITroveManager {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LQTYTokenAddressChanged(address _lqtyTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation);
event Redemption(uint _attemptedLUSDAmount, uint _actualLUSDAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
function getTroveOwnersCount() external view returns (uint);
function getTroveFromTroveOwnersArray(uint _index) external view returns (address);
function getNominalICR(address _borrower) external view returns (uint);
function getCurrentICR(address _borrower, uint _price) external view returns (uint);
function liquidate(address _borrower) external;
function liquidateTroves(uint _n) external;
function batchLiquidateTroves(address[] calldata _troveArray) external;
function redeemCollateral(
uint _LUSDAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFee
) external;
function updateStakeAndTotalStakes(address _borrower) external returns (uint);
function updateTroveRewardSnapshots(address _borrower) external;
function addTroveOwnerToArray(address _borrower) external returns (uint index);
function applyPendingRewards(address _borrower) external;
function getPendingETHReward(address _borrower) external view returns (uint);
function getPendingLUSDDebtReward(address _borrower) external view returns (uint);
function hasPendingRewards(address _borrower) external view returns (bool);
function getEntireDebtAndColl(address _borrower) external view returns (
uint debt,
uint coll,
uint pendingLUSDDebtReward,
uint pendingETHReward
);
function closeTrove(address _borrower) external;
function removeStake(address _borrower) external;
function getRedemptionRate() external view returns (uint);
function getRedemptionRateWithDecay() external view returns (uint);
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint);
function getBorrowingRate() external view returns (uint);
function getBorrowingRateWithDecay() external view returns (uint);
function getBorrowingFee(uint LUSDDebt) external view returns (uint);
function getBorrowingFeeWithDecay(uint _LUSDDebt) external view returns (uint);
function decayBaseRateFromBorrowing() external;
function getTroveStatus(address _borrower) external view returns (uint);
function getTroveStake(address _borrower) external view returns (uint);
function getTroveDebt(address _borrower) external view returns (uint);
function getTroveColl(address _borrower) external view returns (uint);
function setTroveStatus(address _borrower, uint num) external;
function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint);
function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint);
function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint);
function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint);
function getTCR(uint _price) external view returns (uint);
function checkRecoveryMode(uint _price) external view returns (bool);
}
// Common interface for the Trove Manager.
interface IBorrowerOperations {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LUSDTokenAddressChanged(address _lusdTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event TroveCreated(address indexed _borrower, uint arrayIndex);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event LUSDBorrowingFeePaid(address indexed _borrower, uint _LUSDFee);
// --- Functions ---
function openTrove(uint _maxFee, uint _LUSDAmount, address _upperHint, address _lowerHint) external payable;
function addColl(address _upperHint, address _lowerHint) external payable;
function moveETHGainToTrove(address _user, address _upperHint, address _lowerHint) external payable;
function withdrawColl(uint _amount, address _upperHint, address _lowerHint) external;
function withdrawLUSD(uint _maxFee, uint _amount, address _upperHint, address _lowerHint) external;
function repayLUSD(uint _amount, address _upperHint, address _lowerHint) external;
function closeTrove() external;
function adjustTrove(uint _maxFee, uint _collWithdrawal, uint _debtChange, bool isDebtIncrease, address _upperHint, address _lowerHint) external payable;
function claimCollateral() external;
function getCompositeDebt(uint _debt) external pure returns (uint);
}
interface IPriceFeed {
function lastGoodPrice() external pure returns (uint256);
}
interface IHintHelpers {
function getRedemptionHints(
uint _LUSDamount,
uint _price,
uint _maxIterations
)
external
view
returns (
address firstRedemptionHint,
uint partialRedemptionHintNICR,
uint truncatedLUSDamount
);
function getApproxHint(uint _CR, uint _numTrials, uint _inputRandomSeed)
external
view
returns (address hintAddress, uint diff, uint latestRandomSeed);
function computeNominalCR(uint _coll, uint _debt) external pure returns (uint);
function computeCR(uint _coll, uint _debt, uint _price) external pure returns (uint);
}
// Common interface for the SortedTroves Doubly Linked List.
interface ISortedTroves {
// --- Events ---
event SortedTrovesAddressChanged(address _sortedDoublyLLAddress);
event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
event NodeAdded(address _id, uint _NICR);
event NodeRemoved(address _id);
// --- Functions ---
function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external;
function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external;
function remove(address _id) external;
function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external;
function contains(address _id) external view returns (bool);
function isFull() external view returns (bool);
function isEmpty() external view returns (bool);
function getSize() external view returns (uint256);
function getMaxSize() external view returns (uint256);
function getFirst() external view returns (address);
function getLast() external view returns (address);
function getNext(address _id) external view returns (address);
function getPrev(address _id) external view returns (address);
function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool);
function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address);
}
interface ICollSurplusPool {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event CollBalanceUpdated(address indexed _account, uint _newBalance);
event EtherSent(address _to, uint _amount);
// --- Contract setters ---
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress
) external;
function getETH() external view returns (uint);
function getCollateral(address _account) external view returns (uint);
function accountSurplus(address _account, uint _amount) external;
function claimColl(address _account) external;
}
interface IStabilityPool {
// --- Events ---
event StabilityPoolETHBalanceUpdated(uint _newBalance);
event StabilityPoolLUSDBalanceUpdated(uint _newBalance);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress);
event P_Updated(uint _P);
event S_Updated(uint _S, uint128 _epoch, uint128 _scale);
event G_Updated(uint _G, uint128 _epoch, uint128 _scale);
event EpochUpdated(uint128 _currentEpoch);
event ScaleUpdated(uint128 _currentScale);
event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate);
event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd);
event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G);
event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G);
event UserDepositChanged(address indexed _depositor, uint _newDeposit);
event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor);
event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _LUSDLoss);
event LQTYPaidToDepositor(address indexed _depositor, uint _LQTY);
event LQTYPaidToFrontEnd(address indexed _frontEnd, uint _LQTY);
event EtherSent(address _to, uint _amount);
// --- Functions ---
/*
* Called only once on init, to set addresses of other Liquity contracts
* Callable only by owner, renounces ownership at the end
*/
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _priceFeedAddress,
address _communityIssuanceAddress
) external;
/*
* Initial checks:
* - Frontend is registered or zero address
* - Sender is not a registered frontend
* - _amount is not zero
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Tags the deposit with the provided front end tag param, if it's a new deposit
* - Sends depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Increases deposit and tagged front end's stake, and takes new snapshots for each.
*/
function provideToSP(uint _amount, address _frontEndTag) external;
/*
* Initial checks:
* - _amount is zero or there are no under collateralized troves left in the system
* - User has a non zero deposit
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Removes the deposit's front end tag if it is a full withdrawal
* - Sends all depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Decreases deposit and tagged front end's stake, and takes new snapshots for each.
*
* If _amount > userDeposit, the user withdraws all of their compounded deposit.
*/
function withdrawFromSP(uint _amount) external;
/*
* Initial checks:
* - User has a non zero deposit
* - User has an open trove
* - User has some ETH gain
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Sends all depositor's LQTY gain to depositor
* - Sends all tagged front end's LQTY gain to the tagged front end
* - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove
* - Leaves their compounded deposit in the Stability Pool
* - Updates snapshots for deposit and tagged front end stake
*/
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external;
/*
* Initial checks:
* - Frontend (sender) not already registered
* - User (sender) has no deposit
* - _kickbackRate is in the range [0, 100%]
* ---
* Front end makes a one-time selection of kickback rate upon registering
*/
function registerFrontEnd(uint _kickbackRate) external;
/*
* Initial checks:
* - Caller is TroveManager
* ---
* Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible)
* and transfers the Trove's ETH collateral from ActivePool to StabilityPool.
* Only called by liquidation functions in the TroveManager.
*/
function offset(uint _debt, uint _coll) external;
/*
* Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`,
* to exclude edge cases like ETH received from a self-destruct.
*/
function getETH() external view returns (uint);
/*
* Returns LUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
*/
function getTotalLUSDDeposits() external view returns (uint);
/*
* Calculates the ETH gain earned by the deposit since its last snapshots were taken.
*/
function getDepositorETHGain(address _depositor) external view returns (uint);
/*
* Calculate the LQTY gain earned by a deposit since its last snapshots were taken.
* If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned.
* Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through
* which they made their deposit.
*/
function getDepositorLQTYGain(address _depositor) external view returns (uint);
/*
* Return the LQTY gain earned by the front end.
*/
function getFrontEndLQTYGain(address _frontEnd) external view returns (uint);
/*
* Return the user's compounded deposit.
*/
function getCompoundedLUSDDeposit(address _depositor) external view returns (uint);
/*
* Return the front end's compounded stake.
*
* The front end's compounded stake is equal to the sum of its depositors' compounded deposits.
*/
function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint);
// function deposits(address) external view returns ()
}
interface ILQTYStaking {
// --- Events --
event LQTYTokenAddressSet(address _lqtyTokenAddress);
event LUSDTokenAddressSet(address _lusdTokenAddress);
event TroveManagerAddressSet(address _troveManager);
event BorrowerOperationsAddressSet(address _borrowerOperationsAddress);
event ActivePoolAddressSet(address _activePoolAddress);
event StakeChanged(address indexed staker, uint newStake);
event StakingGainsWithdrawn(address indexed staker, uint LUSDGain, uint ETHGain);
event F_ETHUpdated(uint _F_ETH);
event F_LUSDUpdated(uint _F_LUSD);
event TotalLQTYStakedUpdated(uint _totalLQTYStaked);
event EtherSent(address _account, uint _amount);
event StakerSnapshotsUpdated(address _staker, uint _F_ETH, uint _F_LUSD);
// --- Functions ---
function setAddresses
(
address _lqtyTokenAddress,
address _lusdTokenAddress,
address _troveManagerAddress,
address _borrowerOperationsAddress,
address _activePoolAddress
) external;
function stake(uint _LQTYamount) external;
function unstake(uint _LQTYamount) external;
function increaseF_ETH(uint _ETHFee) external;
function increaseF_LUSD(uint _LQTYFee) external;
function getPendingETHGain(address _user) external view returns (uint);
function getPendingLUSDGain(address _user) external view returns (uint);
function stakes(address) external view returns (uint256);
}
contract LiquityHelper {
using TokenUtils for address;
uint constant public LUSD_GAS_COMPENSATION = 200e18;
address constant public LUSDTokenAddr = 0x5f98805A4E8be255a32880FDeC7F6728C6568bA0;
address constant public LQTYTokenAddr = 0x6DEA81C8171D0bA574754EF6F8b412F2Ed88c54D;
address constant public PriceFeedAddr = 0x4c517D4e2C851CA76d7eC94B805269Df0f2201De;
address constant public BorrowerOperationsAddr = 0x24179CD81c9e782A4096035f7eC97fB8B783e007;
address constant public TroveManagerAddr = 0xA39739EF8b0231DbFA0DcdA07d7e29faAbCf4bb2;
address constant public SortedTrovesAddr = 0x8FdD3fbFEb32b28fb73555518f8b361bCeA741A6;
address constant public HintHelpersAddr = 0xE84251b93D9524E0d2e621Ba7dc7cb3579F997C0;
address constant public CollSurplusPoolAddr = 0x3D32e8b97Ed5881324241Cf03b2DA5E2EBcE5521;
address constant public StabilityPoolAddr = 0x66017D22b0f8556afDd19FC67041899Eb65a21bb;
address constant public LQTYStakingAddr = 0x4f9Fbb3f1E99B56e0Fe2892e623Ed36A76Fc605d;
IPriceFeed constant public PriceFeed = IPriceFeed(PriceFeedAddr);
IBorrowerOperations constant public BorrowerOperations = IBorrowerOperations(BorrowerOperationsAddr);
ITroveManager constant public TroveManager = ITroveManager(TroveManagerAddr);
ISortedTroves constant public SortedTroves = ISortedTroves(SortedTrovesAddr);
IHintHelpers constant public HintHelpers = IHintHelpers(HintHelpersAddr);
ICollSurplusPool constant public CollSurplusPool = ICollSurplusPool(CollSurplusPoolAddr);
IStabilityPool constant public StabilityPool = IStabilityPool(StabilityPoolAddr);
ILQTYStaking constant public LQTYStaking = ILQTYStaking(LQTYStakingAddr);
function withdrawStaking(uint256 _ethGain, uint256 _lusdGain, address _wethTo, address _lusdTo) internal {
if (_ethGain > 0) {
TokenUtils.depositWeth(_ethGain);
TokenUtils.WETH_ADDR.withdrawTokens(_wethTo, _ethGain);
}
if (_lusdGain > 0) {
LUSDTokenAddr.withdrawTokens(_lusdTo, _lusdGain);
}
}
function withdrawStabilityGains(uint256 _ethGain, uint256 _lqtyGain, address _wethTo, address _lqtyTo) internal {
if (_ethGain > 0) {
TokenUtils.depositWeth(_ethGain);
TokenUtils.WETH_ADDR.withdrawTokens(_wethTo, _ethGain);
}
if (_lqtyGain > 0) {
LQTYTokenAddr.withdrawTokens(_lqtyTo, _lqtyGain);
}
}
}
abstract contract IDFSRegistry {
function getAddr(bytes32 _id) public view virtual returns (address);
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public virtual;
function startContractChange(bytes32 _id, address _newContractAddr) public virtual;
function approveContractChange(bytes32 _id) public virtual;
function cancelContractChange(bytes32 _id) public virtual;
function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual;
}
/// @title A stateful contract that holds and can change owner/admin
contract AdminVault {
address public owner;
address public admin;
constructor() {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function changeOwner(address _owner) public {
require(admin == msg.sender, "msg.sender not admin");
owner = _owner;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function changeAdmin(address _admin) public {
require(admin == msg.sender, "msg.sender not admin");
admin = _admin;
}
}
/// @title AdminAuth Handles owner/admin privileges over smart contracts
contract AdminAuth {
using SafeERC20 for IERC20;
address public constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD;
AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR);
modifier onlyOwner() {
require(adminVault.owner() == msg.sender, "msg.sender not owner");
_;
}
modifier onlyAdmin() {
require(adminVault.admin() == msg.sender, "msg.sender not admin");
_;
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(_receiver).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
/// @notice Destroy the contract
function kill() public onlyAdmin {
selfdestruct(payable(msg.sender));
}
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(
address _contract,
address _caller,
string memory _logName,
bytes memory _data
) public {
emit LogEvent(_contract, _caller, _logName, _data);
}
}
/// @title Stores all the important DFS addresses and can be changed (timelock)
contract DFSRegistry is AdminAuth {
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists";
string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists";
string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process";
string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger";
string public constant ERR_CHANGE_NOT_READY = "Change not ready yet";
string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0";
string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change";
string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change";
struct Entry {
address contractAddr;
uint256 waitPeriod;
uint256 changeStartTime;
bool inContractChange;
bool inWaitPeriodChange;
bool exists;
}
mapping(bytes32 => Entry) public entries;
mapping(bytes32 => address) public previousAddresses;
mapping(bytes32 => address) public pendingAddresses;
mapping(bytes32 => uint256) public pendingWaitTimes;
/// @notice Given an contract id returns the registered address
/// @dev Id is keccak256 of the contract name
/// @param _id Id of contract
function getAddr(bytes32 _id) public view returns (address) {
return entries[_id].contractAddr;
}
/// @notice Helper function to easily query if id is registered
/// @param _id Id of contract
function isRegistered(bytes32 _id) public view returns (bool) {
return entries[_id].exists;
}
/////////////////////////// OWNER ONLY FUNCTIONS ///////////////////////////
/// @notice Adds a new contract to the registry
/// @param _id Id of contract
/// @param _contractAddr Address of the contract
/// @param _waitPeriod Amount of time to wait before a contract address can be changed
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public onlyOwner {
require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS);
entries[_id] = Entry({
contractAddr: _contractAddr,
waitPeriod: _waitPeriod,
changeStartTime: 0,
inContractChange: false,
inWaitPeriodChange: false,
exists: true
});
// Remember tha address so we can revert back to old addr if needed
previousAddresses[_id] = _contractAddr;
logger.Log(
address(this),
msg.sender,
"AddNewContract",
abi.encode(_id, _contractAddr, _waitPeriod)
);
}
/// @notice Reverts to the previous address immediately
/// @dev In case the new version has a fault, a quick way to fallback to the old contract
/// @param _id Id of contract
function revertToPreviousAddress(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR);
address currentAddr = entries[_id].contractAddr;
entries[_id].contractAddr = previousAddresses[_id];
logger.Log(
address(this),
msg.sender,
"RevertToPreviousAddress",
abi.encode(_id, currentAddr, previousAddresses[_id])
);
}
/// @notice Starts an address change for an existing entry
/// @dev Can override a change that is currently in progress
/// @param _id Id of contract
/// @param _newContractAddr Address of the new contract
function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE);
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inContractChange = true;
pendingAddresses[_id] = _newContractAddr;
logger.Log(
address(this),
msg.sender,
"StartContractChange",
abi.encode(_id, entries[_id].contractAddr, _newContractAddr)
);
}
/// @notice Changes new contract address, correct time must have passed
/// @param _id Id of contract
function approveContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
address oldContractAddr = entries[_id].contractAddr;
entries[_id].contractAddr = pendingAddresses[_id];
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
pendingAddresses[_id] = address(0);
previousAddresses[_id] = oldContractAddr;
logger.Log(
address(this),
msg.sender,
"ApproveContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Cancel pending change
/// @param _id Id of contract
function cancelContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
address oldContractAddr = pendingAddresses[_id];
pendingAddresses[_id] = address(0);
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Starts the change for waitPeriod
/// @param _id Id of contract
/// @param _newWaitPeriod New wait time
function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE);
pendingWaitTimes[_id] = _newWaitPeriod;
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inWaitPeriodChange = true;
logger.Log(
address(this),
msg.sender,
"StartWaitPeriodChange",
abi.encode(_id, _newWaitPeriod)
);
}
/// @notice Changes new wait period, correct time must have passed
/// @param _id Id of contract
function approveWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
uint256 oldWaitTime = entries[_id].waitPeriod;
entries[_id].waitPeriod = pendingWaitTimes[_id];
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
pendingWaitTimes[_id] = 0;
logger.Log(
address(this),
msg.sender,
"ApproveWaitPeriodChange",
abi.encode(_id, oldWaitTime, entries[_id].waitPeriod)
);
}
/// @notice Cancel wait period change
/// @param _id Id of contract
function cancelWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
uint256 oldWaitPeriod = pendingWaitTimes[_id];
pendingWaitTimes[_id] = 0;
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelWaitPeriodChange",
abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod)
);
}
}
/// @title Implements Action interface and common helpers for passing inputs
abstract contract ActionBase is AdminAuth {
address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C;
DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR);
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value";
string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value";
/// @dev Subscription params index range [128, 255]
uint8 public constant SUB_MIN_INDEX_VALUE = 128;
uint8 public constant SUB_MAX_INDEX_VALUE = 255;
/// @dev Return params index range [1, 127]
uint8 public constant RETURN_MIN_INDEX_VALUE = 1;
uint8 public constant RETURN_MAX_INDEX_VALUE = 127;
/// @dev If the input value should not be replaced
uint8 public constant NO_PARAM_MAPPING = 0;
/// @dev We need to parse Flash loan actions in a different way
enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION }
/// @notice Parses inputs and runs the implemented action through a proxy
/// @dev Is called by the TaskExecutor chaining actions together
/// @param _callData Array of input values each value encoded as bytes
/// @param _subData Array of subscribed vales, replaces input values if specified
/// @param _paramMapping Array that specifies how return and subscribed values are mapped in input
/// @param _returnValues Returns values from actions before, which can be injected in inputs
/// @return Returns a bytes32 value through DSProxy, each actions implements what that value is
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual returns (bytes32);
/// @notice Parses inputs and runs the single implemented action through a proxy
/// @dev Used to save gas when executing a single action directly
function executeActionDirect(bytes[] memory _callData) public virtual payable;
/// @notice Returns the type of action we are implementing
function actionType() public pure virtual returns (uint8);
//////////////////////////// HELPER METHODS ////////////////////////////
/// @notice Given an uint256 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamUint(
uint _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (uint) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = uint(_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (uint));
}
}
return _param;
}
/// @notice Given an addr input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamAddr(
address _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (address) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = address(bytes20((_returnValues[getReturnIndex(_mapType)])));
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (address));
}
}
return _param;
}
/// @notice Given an bytes32 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamABytes32(
bytes32 _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (bytes32) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = (_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32));
}
}
return _param;
}
/// @notice Checks if the paramMapping value indicated that we need to inject values
/// @param _type Indicated the type of the input
function isReplaceable(uint8 _type) internal pure returns (bool) {
return _type != NO_PARAM_MAPPING;
}
/// @notice Checks if the paramMapping value is in the return value range
/// @param _type Indicated the type of the input
function isReturnInjection(uint8 _type) internal pure returns (bool) {
return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in return array value
/// @param _type Indicated the type of the input
function getReturnIndex(uint8 _type) internal pure returns (uint8) {
require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE);
return (_type - RETURN_MIN_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in sub array value
/// @param _type Indicated the type of the input
function getSubIndex(uint8 _type) internal pure returns (uint8) {
require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE);
return (_type - SUB_MIN_INDEX_VALUE);
}
}
contract LiquitySPWithdraw is ActionBase, LiquityHelper {
using TokenUtils for address;
struct Params {
uint256 lusdAmount; // Amount of LUSD tokens to withdraw
address to; // Address that will receive the tokens
address wethTo; // Address that will receive ETH(wrapped) gains
address lqtyTo; // Address that will receive LQTY token gains
}
/// @inheritdoc ActionBase
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
Params memory params = parseInputs(_callData);
params.lusdAmount = _parseParamUint(params.lusdAmount, _paramMapping[0], _subData, _returnValues);
params.to = _parseParamAddr(params.to, _paramMapping[1], _subData, _returnValues);
params.wethTo = _parseParamAddr(params.wethTo, _paramMapping[2], _subData, _returnValues);
params.lqtyTo = _parseParamAddr(params.lqtyTo, _paramMapping[3], _subData, _returnValues);
params.lusdAmount = _liquitySPWithdraw(params);
return bytes32(params.lusdAmount);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes[] memory _callData) public payable virtual override {
Params memory params = parseInputs(_callData);
_liquitySPWithdraw(params);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice Withdraws LUSD from the user's stability pool deposit
function _liquitySPWithdraw(Params memory _params) internal returns (uint256) {
uint256 ethGain = StabilityPool.getDepositorETHGain(address(this));
uint256 lqtyGain = StabilityPool.getDepositorLQTYGain(address(this));
uint256 deposit = StabilityPool.getCompoundedLUSDDeposit(address(this));
_params.lusdAmount = deposit > _params.lusdAmount ? _params.lusdAmount : deposit;
StabilityPool.withdrawFromSP(_params.lusdAmount);
// Amount goes through min(amount, depositedAmount)
LUSDTokenAddr.withdrawTokens(_params.to, _params.lusdAmount);
withdrawStabilityGains(ethGain, lqtyGain, _params.wethTo, _params.lqtyTo);
logger.Log(
address(this),
msg.sender,
"LiquitySPWithdraw",
abi.encode(
_params,
ethGain,
lqtyGain
)
);
return _params.lusdAmount;
}
function parseInputs(bytes[] memory _callData) internal pure returns (Params memory params) {
params = abi.decode(_callData[0], (Params));
}
}
|
--- Events -- --- Functions ---
|
interface ILQTYStaking {
event LQTYTokenAddressSet(address _lqtyTokenAddress);
event LUSDTokenAddressSet(address _lusdTokenAddress);
event TroveManagerAddressSet(address _troveManager);
event BorrowerOperationsAddressSet(address _borrowerOperationsAddress);
event ActivePoolAddressSet(address _activePoolAddress);
event StakeChanged(address indexed staker, uint newStake);
event StakingGainsWithdrawn(address indexed staker, uint LUSDGain, uint ETHGain);
event F_ETHUpdated(uint _F_ETH);
event F_LUSDUpdated(uint _F_LUSD);
event TotalLQTYStakedUpdated(uint _totalLQTYStaked);
event EtherSent(address _account, uint _amount);
event StakerSnapshotsUpdated(address _staker, uint _F_ETH, uint _F_LUSD);
function setAddresses
(
address _lqtyTokenAddress,
address _lusdTokenAddress,
address _troveManagerAddress,
address _borrowerOperationsAddress,
address _activePoolAddress
) external;
function stake(uint _LQTYamount) external;
function unstake(uint _LQTYamount) external;
function increaseF_ETH(uint _ETHFee) external;
function increaseF_LUSD(uint _LQTYFee) external;
function getPendingETHGain(address _user) external view returns (uint);
function getPendingLUSDGain(address _user) external view returns (uint);
function stakes(address) external view returns (uint256);
}
| 14,390,470
|
// SPDX-License-Identifier: MIT
pragma solidity 0.5.3;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/upgrades/contracts/Initializable.sol';
import './MikeToken.sol';
/// @title Gloom - contracts to auction off ERC-20 tokens to the highest bidder (in ETH)
/// @title Escrow contract, to be used in conjunction with AuctionFactory and Auction contracts
/// @author Michael S. Mueller
/// @notice This MVP is designed to handle one auction or one auction invite per address
/// @notice This is a demo, do not use on mainnet
/// @dev Escrow inherits Initializable to ensure Escrow is only initialized once
/*
===== OVERVIEW =====
AUCTION PHASES
- Phase begins in Setup, later Seller triggers move to Commit, Reveal, Deliver, Withdraw
SETUP
- Seller configures (but does not transfer) ERC-20 token amount and address
- Auction Factory deploys new clone of Auction (logic) contract with this configuration
- Seller makes seller deposit (in ETH) into Auction
- Seller specifies bidder deposit requirement (in ETH) and invites bidders to Auction
COMMIT
- Bidders deposit into Auction (in ETH) and commit a hash (with salt) of their bid (denominated in ETH)
REVEAL
- Bidders reveal their bids, Auction contract assigns winner and deploys new Escrow contract
DELIVER
- Seller transfers (using approve / transferFrom pattern) their ERC-20 tokens into Escrow
- Winning bidder transfers winning bid (in ETH) to Escrow
WITHDRAW
- Seller withdraws their seller deposit (in ETH) from Auction and the winning bid proceeds (in ETH) from Escrow
- Bidder withdraws their bidder deposit (in ETH) from Auction and ERC-20 tokens from Escrow
*/
contract Escrow is Initializable {
// address of auction that deploys this Escrow instance
address private auction;
address private seller;
address private buyer;
// number of tokens, 18 decimal precision
uint256 private tokenAmount;
address private tokenContractAddress;
uint256 private winningBid;
uint256 private tokenBalance;
uint256 private balance;
// to track if seller has transferred tokens to Escrow
bool private sellerOk;
// to track if buyer has paid winning bid to Escrow
bool private buyerOk;
// to track whether seller (through Auction contract) has triggered Withdraw phase
bool private withdrawOk;
modifier onlySeller {
require(msg.sender == seller, 'Sender not authorized');
_;
}
modifier onlyBuyer {
require(msg.sender == buyer, 'Sender not authorized');
_;
}
modifier onlySellerOrBuyer {
require(msg.sender == seller || msg.sender == buyer, 'Sender not authorized');
_;
}
modifier onlyAuction {
require(msg.sender == auction, 'Sender not authorized');
_;
}
modifier onlyBuyerSellerAuctionEscrow {
require(
msg.sender == buyer || msg.sender == seller || msg.sender == auction || msg.sender == address(this),
'Sender not authorized'
);
_;
}
event LogSellerDelivered(address indexed seller, uint256 tokenAmount);
event LogBuyerPaid(address indexed buyer, uint256 amount);
event LogSellerWithdrew(address indexed seller, uint256 amount);
event LogBuyerWithdrew(address indexed buyer, uint256 tokenAmount);
/// @notice Initialize Escrow in Auction Delivery phase with seller address, ERC-20 token amount and address, and winning bidder and bid
/// @dev Initializable contracts have initialize function instead of constructor
/// @dev initializer modifier prevents function from being called twice
/// @dev Solidity casts winning bid from bytes32 to uint256 here, consider using OpenZeppelin SafeCast.sol
/// @param _seller address of seller triggering Auction deploy
/// @param _buyer address of winning bidder
/// @param _tokenAmount uint number of tokens being auctioned, assumed 18 decimal precision
/// @param _tokenContractAddress contract address of token being auction, assumed ERC-20
/// @param _winningBid 32-byte hex encoding of winning bid amount (left zero-padded on front end)
function initialize(
address _seller,
address _buyer,
uint256 _tokenAmount,
address _tokenContractAddress,
bytes32 _winningBid
) public initializer {
auction = msg.sender;
seller = _seller;
buyer = _buyer;
tokenAmount = _tokenAmount;
tokenContractAddress = _tokenContractAddress;
winningBid = uint256(_winningBid);
}
/// @notice Get token amount being auctioned
/// @dev Used in frontend to show token amount to both seller and buyer
/// @dev Should return same as getter in Auction contract, could refactor to use one getter across both contracts
/// @return number of tokens being auctioned
function getTokenAmount() external view onlySellerOrBuyer returns (uint256) {
return tokenAmount;
}
/// @notice Get contract address of token being auctioned
/// @dev Used in frontend to show contract token address to both seller and buyer
/// @dev Should return same as getter in Auction contract, could refactor to use one getter across both contracts
/// @return contract address of tokens being auctioned
function getTokenContractAddress() external view onlySellerOrBuyer returns (address) {
return tokenContractAddress;
}
/// @notice Get winning bid
/// @dev Used in frontend to show winning bid to both seller and buyer
/// @dev Should return same as getter in Auction contract, could refactor to use one getter across both contracts
/// @return winning bid (in ETH)
function getWinningBid() external view onlySellerOrBuyer returns (uint256) {
return winningBid;
}
/// @notice Transfer of seller ERC-20 tokens to escrow contract
/// @dev Frontend calls approve() of ERC-20 token before transferFrom() may be called
/// @dev Frontend could have user make transfer() directly, but separation allows for earlier approve(), e.g. in Setup phase, if so desired
/// @dev Performs state updates before external call to prevent reentrancy attack
function sellerDelivery() external onlySeller {
tokenBalance += tokenAmount;
sellerOk = true;
require(IERC20(tokenContractAddress).transferFrom(msg.sender, address(this), tokenAmount), 'Transfer failed');
emit LogSellerDelivered(msg.sender, tokenAmount);
}
/// @notice Transfer of buyer's winning bid (in ETH) to escrow contract
/// @dev Frontend handles buyer transfer
function buyerPayment() external payable onlyBuyer {
require(msg.value == winningBid, 'Incorrect amount');
balance += msg.value;
buyerOk = true;
emit LogBuyerPaid(msg.sender, msg.value);
}
/// @notice Check if both seller has transferred tokens and buyer has transferred winning bid (in ETH) to Escrow
/// @return true if both have transferred, false if either one has not
function bothOk() public view onlyBuyerSellerAuctionEscrow returns (bool) {
return sellerOk && buyerOk;
}
/// @notice Check if seller (through Auction contract) has triggered Withdraw phase
/// @return true if Withdraw phase has been triggered, false if not
function startWithdraw() external onlyAuction returns (bool) {
return withdrawOk = true;
}
/// @notice Checks if escrow is complete, if so allows Seller to withdraw winning bid (in ETH)
/// @dev Performs state updates before external call to prevent reentrancy attack
function sellerWithdraw() external payable onlySeller {
require(bothOk(), 'Escrow is not complete');
require(withdrawOk, 'Action not authorized now');
require(address(this).balance >= winningBid, 'Insufficient balance');
balance -= winningBid;
(bool success, ) = msg.sender.call.value(winningBid)('');
require(success, 'Transfer failed');
emit LogSellerWithdrew(msg.sender, winningBid);
}
/// @notice Checks if escrow is complete, if so allows Buyer to withdraw tokens
/// @dev Performs state updates before external call to prevent reentrancy attack
function buyerWithdraw() external onlyBuyer {
require(bothOk(), 'Escrow is not complete');
require(withdrawOk, 'Action not authorized now');
require(IERC20(tokenContractAddress).balanceOf(address(this)) >= tokenAmount, 'Insufficient balance');
tokenBalance -= tokenAmount;
require(IERC20(tokenContractAddress).transfer(msg.sender, tokenAmount), 'Transfer failed');
emit LogBuyerWithdrew(msg.sender, tokenAmount);
}
}
|
Checks if escrow is complete, if so allows Seller to withdraw winning bid (in ETH) Performs state updates before external call to prevent reentrancy attack
|
function sellerWithdraw() external payable onlySeller {
require(bothOk(), 'Escrow is not complete');
require(withdrawOk, 'Action not authorized now');
require(address(this).balance >= winningBid, 'Insufficient balance');
balance -= winningBid;
(bool success, ) = msg.sender.call.value(winningBid)('');
require(success, 'Transfer failed');
emit LogSellerWithdrew(msg.sender, winningBid);
}
| 5,494,746
|
//Address: 0xc2a0da9cd06266fb1d599acee77daa5b5e0f901f
//Contract name: RENTCoin
//Balance: -
//Verification Date: 2/25/2018
//Transacion Count: 0
// CODE STARTS HERE
pragma solidity ^0.4.18;
// Original code of smart contract on github:
// Standart libary from "Open Zeppelin"
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// Standart contract from "Open Zeppelin"
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant public returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// Standart contract from "Open Zeppelin"
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant public 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);
}
// Describing contract with owner.
contract Owned {
address public owner;
address public newOwner;
function Owned() public payable {
owner = msg.sender;
}
modifier onlyOwner {
require(owner == msg.sender);
_;
}
function changeOwner(address _owner) onlyOwner public {
require(_owner != 0);
newOwner = _owner;
}
function confirmOwner() public {
require(newOwner == msg.sender);
owner = newOwner;
delete newOwner;
}
}
// Describing Bloccking modifier which founds on time block.
contract Blocked {
// Time till modifier block
uint public blockedUntil;
modifier unblocked {
require(now > blockedUntil);
_;
}
}
// contract which discribes contract of token which founds on ERC20 and implement balanceOf function.
contract BalancingToken is ERC20 {
mapping (address => uint256) public balances; //!< array of all balances
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
// Contract for dividend tokens. This contract describes implementation for tokens which can be used for dividends
contract DividendToken is BalancingToken, Blocked, Owned {
using SafeMath for uint256;
// Event for dividends when somebody takes dividends it will raised.
event DividendReceived(address indexed dividendReceiver, uint256 dividendValue);
// mapping for alloweds and amounts.
mapping (address => mapping (address => uint256)) public allowed;
// full reward amount for one round.
// this value is defined by ether amount on DividendToken contract on moment when dividend payments starts.
uint public totalReward;
// time when last time dividends started pay.
uint public lastDivideRewardTime;
// Fix for the ERC20 short address attack
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
// This modifier checkes if reward payment is over.
modifier rewardTimePast() {
require(now > lastDivideRewardTime + rewardDays * 1 days);
_;
}
// Structure is for Token holder which contains information about all token holders with balances and times.
struct TokenHolder {
uint256 balance;
uint balanceUpdateTime;
uint rewardWithdrawTime;
}
// mapping for token holders.
mapping(address => TokenHolder) holders;
// the number of days for rewards.
uint public rewardDays = 0;
// standard method for transfer from ERC20.
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) unblocked public returns (bool) {
return transferSimple(_to, _value);
}
// internal implementation for transfer with recounting rewards.
function transferSimple(address _to, uint256 _value) internal returns (bool) {
beforeBalanceChanges(msg.sender);
beforeBalanceChanges(_to);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
// standard method for transferFrom from ERC20.
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) unblocked public returns (bool) {
beforeBalanceChanges(_from);
beforeBalanceChanges(_to);
uint256 _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
// standard method for transferFrom from ERC20.
function approve(address _spender, uint256 _value) onlyPayloadSize(2 * 32) unblocked public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// standard method for transferFrom from ERC20.
function allowance(address _owner, address _spender) onlyPayloadSize(2 * 32) unblocked constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// THis method returns the amount of caller's reward.
// Caller gets ether which should be given to him.
function reward() constant public returns (uint256) {
if (holders[msg.sender].rewardWithdrawTime >= lastDivideRewardTime) {
return 0;
}
uint256 balance;
if (holders[msg.sender].balanceUpdateTime <= lastDivideRewardTime) {
balance = balances[msg.sender];
} else {
balance = holders[msg.sender].balance;
}
return totalReward.mul(balance).div(totalSupply);
}
// This method shoud be called when caller wants take dividends reward.
// Caller gets ether which should be given to him.
function withdrawReward() public returns (uint256) {
uint256 rewardValue = reward();
if (rewardValue == 0) {
return 0;
}
if (balances[msg.sender] == 0) {
// garbage collector
delete holders[msg.sender];
} else {
holders[msg.sender].rewardWithdrawTime = now;
}
require(msg.sender.call.gas(3000000).value(rewardValue)());
DividendReceived(msg.sender, rewardValue);
return rewardValue;
}
// Divide up reward and make it accesible for withdraw
// Need to provide the number of days for reward. It can be less then 15 days and more then 45 days.
function divideUpReward(uint inDays) rewardTimePast onlyOwner external payable {
require(inDays >= 15 && inDays <= 45);
lastDivideRewardTime = now;
rewardDays = inDays;
totalReward = this.balance;
}
// Take left reward after reward period.
function withdrawLeft() rewardTimePast onlyOwner external {
require(msg.sender.call.gas(3000000).value(this.balance)());
}
// recount reward of somebody.
function beforeBalanceChanges(address _who) public {
if (holders[_who].balanceUpdateTime <= lastDivideRewardTime) {
holders[_who].balanceUpdateTime = now;
holders[_who].balance = balances[_who];
}
}
}
// Final contract for RENT coin.
contract RENTCoin is DividendToken {
string public constant name = "RentAway Coin";
string public constant symbol = "RTW";
uint32 public constant decimals = 18;
function RENTCoin(uint256 initialSupply, uint unblockTime) public {
totalSupply = initialSupply;
balances[owner] = totalSupply;
blockedUntil = unblockTime;
Transfer(this, owner, totalSupply);
}
// Uses for overwork manual Blocked contract for ICO time.
// After ICO it is not needed.
function manualTransfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) onlyOwner public returns (bool) {
return transferSimple(_to, _value);
}
}
|
standard method for transferFrom from ERC20.
|
function allowance(address _owner, address _spender) onlyPayloadSize(2 * 32) unblocked constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| 7,306,460
|
//Address: 0xacb677dacac7c7b1ee4131cd071c89bad6c852f4
//Contract name: ExoTownToken
//Balance: 0 Ether
//Verification Date: 11/26/2017
//Transacion Count: 0
// CODE STARTS HERE
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract SafeMath {
function mul(uint a, uint b) constant internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) constant internal returns (uint) {
assert(b != 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) constant internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) constant internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
// Volume bonus calculation
function volumeBonus(uint etherValue) constant internal returns (uint) {
if(etherValue >= 500000000000000000000) return 10; // 500 ETH +10% tokens
if(etherValue >= 300000000000000000000) return 7; // 300 ETH +7% tokens
if(etherValue >= 100000000000000000000) return 5; // 100 ETH +5% tokens
if(etherValue >= 50000000000000000000) return 3; // 50 ETH +3% tokens
if(etherValue >= 20000000000000000000) return 2; // 20 ETH +2% tokens
if(etherValue >= 10000000000000000000) return 1; // 10 ETH +1% tokens
return 0;
}
}
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
/// @title Abstract token contract - Functions to be implemented by token contracts.
contract AbstractToken {
// This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions
function totalSupply() constant returns (uint) {}
function balanceOf(address owner) constant returns (uint balance);
function transfer(address to, uint value) returns (bool success);
function transferFrom(address from, address to, uint value) returns (bool success);
function approve(address spender, uint value) returns (bool success);
function allowance(address owner, address spender) constant returns (uint remaining);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Issuance(address indexed to, uint value);
}
contract IcoLimits {
uint constant privateSaleStart = 1511740800; // 11/27/2017 @ 12:00am (UTC)
uint constant privateSaleEnd = 1512172799; // 12/01/2017 @ 11:59pm (UTC)
uint constant presaleStart = 1512172800; // 12/02/2017 @ 12:00am (UTC)
uint constant presaleEnd = 1513987199; // 12/22/2017 @ 11:59pm (UTC)
uint constant publicSaleStart = 1516320000; // 01/19/2018 @ 12:00am (UTC)
uint constant publicSaleEnd = 1521158399; // 03/15/2018 @ 11:59pm (UTC)
uint constant foundersTokensUnlock = 1558310400; // 05/20/2019 @ 12:00am (UTC)
modifier afterPublicSale() {
require(now > publicSaleEnd);
_;
}
uint constant privateSalePrice = 4000; // SNEK tokens per 1 ETH
uint constant preSalePrice = 3000; // SNEK tokens per 1 ETH
uint constant publicSalePrice = 2000; // SNEK tokens per 1 ETH
uint constant privateSaleSupplyLimit = 600 * privateSalePrice * 1000000000000000000;
uint constant preSaleSupplyLimit = 1200 * preSalePrice * 1000000000000000000;
uint constant publicSaleSupplyLimit = 5000 * publicSalePrice * 1000000000000000000;
}
contract StandardToken is AbstractToken, IcoLimits {
/*
* Data structures
*/
mapping (address => uint) balances;
mapping (address => bool) ownerAppended;
mapping (address => mapping (address => uint)) allowed;
uint public totalSupply;
address[] public owners;
/*
* Read and write storage functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success.
/// @param _to Address of token receiver.
/// @param _value Number of tokens to transfer.
function transfer(address _to, uint _value) afterPublicSale returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
if(!ownerAppended[_to]) {
ownerAppended[_to] = true;
owners.push(_to);
}
Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
function transferFrom(address _from, address _to, uint _value) afterPublicSale returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
if(!ownerAppended[_to]) {
ownerAppended[_to] = true;
owners.push(_to);
}
Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
function approve(address _spender, uint _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/*
* Read storage functions
*/
/// @dev Returns number of allowed tokens for given address.
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract ExoTownToken is StandardToken, SafeMath {
/*
* Token meta data
*/
string public constant name = "ExoTown token";
string public constant symbol = "SNEK";
uint public constant decimals = 18;
address public icoContract = 0x0;
/*
* Modifiers
*/
modifier onlyIcoContract() {
// only ICO contract is allowed to proceed
require(msg.sender == icoContract);
_;
}
/*
* Contract functions
*/
/// @dev Contract is needed in icoContract address
/// @param _icoContract Address of account which will be mint tokens
function ExoTownToken(address _icoContract) {
require(_icoContract != 0x0);
icoContract = _icoContract;
}
/// @dev Burns tokens from address. It can be applied by account with address this.icoContract
/// @param _from Address of account, from which will be burned tokens
/// @param _value Amount of tokens, that will be burned
function burnTokens(address _from, uint _value) onlyIcoContract {
require(_value > 0);
balances[_from] = sub(balances[_from], _value);
totalSupply -= _value;
}
/// @dev Adds tokens to address. It can be applied by account with address this.icoContract
/// @param _to Address of account to which the tokens will pass
/// @param _value Amount of tokens
function emitTokens(address _to, uint _value) onlyIcoContract {
require(totalSupply + _value >= totalSupply);
balances[_to] = add(balances[_to], _value);
totalSupply += _value;
if(!ownerAppended[_to]) {
ownerAppended[_to] = true;
owners.push(_to);
}
Transfer(0x0, _to, _value);
}
function getOwner(uint index) constant returns (address, uint) {
return (owners[index], balances[owners[index]]);
}
function getOwnerCount() constant returns (uint) {
return owners.length;
}
}
contract ExoTownIco is SafeMath, IcoLimits {
/*
* ICO meta data
*/
ExoTownToken public exotownToken;
enum State {
Pause,
Running
}
State public currentState = State.Pause;
uint public privateSaleSoldTokens = 0;
uint public preSaleSoldTokens = 0;
uint public publicSaleSoldTokens = 0;
uint public privateSaleEtherRaised = 0;
uint public preSaleEtherRaised = 0;
uint public publicSaleEtherRaised = 0;
// Address of manager
address public icoManager;
address public founderWallet;
// Address from which tokens could be burned
address public buyBack;
// Purpose
address public developmentWallet;
address public marketingWallet;
address public teamWallet;
address public bountyOwner;
// Mediator wallet is used for tracking user payments and reducing users' fee
address public mediatorWallet;
bool public sentTokensToBountyOwner = false;
bool public sentTokensToFounders = false;
/*
* Modifiers
*/
modifier whenInitialized() {
// only when contract is initialized
require(currentState >= State.Running);
_;
}
modifier onlyManager() {
// only ICO manager can do this action
require(msg.sender == icoManager);
_;
}
modifier onIco() {
require( isPrivateSale() || isPreSale() || isPublicSale() );
_;
}
modifier hasBountyCampaign() {
require(bountyOwner != 0x0);
_;
}
function isPrivateSale() constant internal returns (bool) {
return now >= privateSaleStart && now <= privateSaleEnd;
}
function isPreSale() constant internal returns (bool) {
return now >= presaleStart && now <= presaleEnd;
}
function isPublicSale() constant internal returns (bool) {
return now >= publicSaleStart && now <= publicSaleEnd;
}
function getPrice() constant internal returns (uint) {
if (isPrivateSale()) return privateSalePrice;
if (isPreSale()) return preSalePrice;
if (isPublicSale()) return publicSalePrice;
return publicSalePrice;
}
function getStageSupplyLimit() constant returns (uint) {
if (isPrivateSale()) return privateSaleSupplyLimit;
if (isPreSale()) return preSaleSupplyLimit;
if (isPublicSale()) return publicSaleSupplyLimit;
return 0;
}
function getStageSoldTokens() constant returns (uint) {
if (isPrivateSale()) return privateSaleSoldTokens;
if (isPreSale()) return preSaleSoldTokens;
if (isPublicSale()) return publicSaleSoldTokens;
return 0;
}
function addStageTokensSold(uint _amount) internal {
if (isPrivateSale()) privateSaleSoldTokens = add(privateSaleSoldTokens, _amount);
if (isPreSale()) preSaleSoldTokens = add(preSaleSoldTokens, _amount);
if (isPublicSale()) publicSaleSoldTokens = add(publicSaleSoldTokens, _amount);
}
function addStageEtherRaised(uint _amount) internal {
if (isPrivateSale()) privateSaleEtherRaised = add(privateSaleEtherRaised, _amount);
if (isPreSale()) preSaleEtherRaised = add(preSaleEtherRaised, _amount);
if (isPublicSale()) publicSaleEtherRaised = add(publicSaleEtherRaised, _amount);
}
function getStageEtherRaised() constant returns (uint) {
if (isPrivateSale()) return privateSaleEtherRaised;
if (isPreSale()) return preSaleEtherRaised;
if (isPublicSale()) return publicSaleEtherRaised;
return 0;
}
function getTokensSold() constant returns (uint) {
return
privateSaleSoldTokens +
preSaleSoldTokens +
publicSaleSoldTokens;
}
function getEtherRaised() constant returns (uint) {
return
privateSaleEtherRaised +
preSaleEtherRaised +
publicSaleEtherRaised;
}
/// @dev Constructor of ICO. Requires address of icoManager,
/// @param _icoManager Address of ICO manager
function ExoTownIco(address _icoManager) {
require(_icoManager != 0x0);
exotownToken = new ExoTownToken(this);
icoManager = _icoManager;
}
/// Initialises addresses of founder, target wallets
/// @param _founder Address of Founder
/// @param _dev Address of Development wallet
/// @param _pr Address of Marketing wallet
/// @param _team Address of Team wallet
/// @param _buyback Address of wallet used for burning tokens
/// @param _mediator Address of Mediator wallet
function init(
address _founder,
address _dev,
address _pr,
address _team,
address _buyback,
address _mediator
) onlyManager {
require(currentState == State.Pause);
require(_founder != 0x0);
require(_dev != 0x0);
require(_pr != 0x0);
require(_team != 0x0);
require(_buyback != 0x0);
require(_mediator != 0x0);
founderWallet = _founder;
developmentWallet = _dev;
marketingWallet = _pr;
teamWallet = _team;
buyBack = _buyback;
mediatorWallet = _mediator;
currentState = State.Running;
exotownToken.emitTokens(icoManager, 0);
}
/// @dev Sets new state
/// @param _newState Value of new state
function setState(State _newState) public onlyManager {
currentState = _newState;
}
/// @dev Sets new manager. Only manager can do it
/// @param _newIcoManager Address of new ICO manager
function setNewManager(address _newIcoManager) onlyManager {
require(_newIcoManager != 0x0);
icoManager = _newIcoManager;
}
/// @dev Sets bounty owner. Only manager can do it
/// @param _bountyOwner Address of Bounty owner
function setBountyCampaign(address _bountyOwner) onlyManager {
require(_bountyOwner != 0x0);
bountyOwner = _bountyOwner;
}
/// @dev Sets new Mediator wallet. Only manager can do it
/// @param _mediator Address of Mediator wallet
function setNewMediator(address _mediator) onlyManager {
require(_mediator != 0x0);
mediatorWallet = _mediator;
}
/// @dev Buy quantity of tokens depending on the amount of sent ethers.
/// @param _buyer Address of account which will receive tokens
function buyTokens(address _buyer) private {
require(_buyer != 0x0);
require(msg.value > 0);
uint tokensToEmit = msg.value * getPrice();
uint volumeBonusPercent = volumeBonus(msg.value);
if (volumeBonusPercent > 0) {
tokensToEmit = mul(tokensToEmit, 100 + volumeBonusPercent) / 100;
}
uint stageSupplyLimit = getStageSupplyLimit();
uint stageSoldTokens = getStageSoldTokens();
require(add(stageSoldTokens, tokensToEmit) <= stageSupplyLimit);
exotownToken.emitTokens(_buyer, tokensToEmit);
// Public statistics
addStageTokensSold(tokensToEmit);
addStageEtherRaised(msg.value);
distributeEtherByStage();
}
/// @dev Buy tokens to specified wallet
function giftToken(address _to) public payable onIco {
buyTokens(_to);
}
/// @dev Fall back function
function () payable onIco {
buyTokens(msg.sender);
}
function distributeEtherByStage() private {
uint _balance = this.balance;
uint _balance_div = _balance / 100;
uint _devAmount = _balance_div * 65;
uint _prAmount = _balance_div * 25;
uint total = _devAmount + _prAmount;
if (total > 0) {
// Top up Mediator wallet with 1% of Development amount = 0.65% of contribution amount.
// It will cover tracking transaction fee (if any).
uint _mediatorAmount = _devAmount / 100;
mediatorWallet.transfer(_mediatorAmount);
developmentWallet.transfer(_devAmount - _mediatorAmount);
marketingWallet.transfer(_prAmount);
teamWallet.transfer(_balance - _devAmount - _prAmount);
}
}
/// @dev Partial withdraw. Only manager can do it
function withdrawEther(uint _value) onlyManager {
require(_value > 0);
require(_value * 1000000000000000 <= this.balance);
// send 1234 to get 1.234
icoManager.transfer(_value * 1000000000000000); // 10^15
}
///@dev Send tokens to bountyOwner depending on crowdsale results. Can be sent only after public sale.
function sendTokensToBountyOwner() onlyManager whenInitialized hasBountyCampaign afterPublicSale {
require(!sentTokensToBountyOwner);
//Calculate bounty tokens depending on total tokens sold
uint bountyTokens = getTokensSold() / 40; // 2.5%
exotownToken.emitTokens(bountyOwner, bountyTokens);
sentTokensToBountyOwner = true;
}
/// @dev Send tokens to founders. Can be sent only after May 20th, 2019.
function sendTokensToFounders() onlyManager whenInitialized afterPublicSale {
require(!sentTokensToFounders);
require(now >= foundersTokensUnlock);
//Calculate founder reward depending on total tokens sold
uint founderReward = getTokensSold() / 10; // 10%
exotownToken.emitTokens(founderWallet, founderReward);
sentTokensToFounders = true;
}
// Anyone could burn tokens by sending it to buyBack address and calling this function.
function burnTokens(uint _amount) afterPublicSale {
exotownToken.burnTokens(buyBack, _amount);
}
}
|
Allows allowed third party to transfer tokens from one address to another. Returns success. _from Address from where tokens are withdrawn. _to Address to where tokens are sent. _value Number of tokens to transfer.
|
function transferFrom(address _from, address _to, uint _value) afterPublicSale returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
if(!ownerAppended[_to]) {
ownerAppended[_to] = true;
owners.push(_to);
}
Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
| 1,808,427
|
./partial_match/1/0x4BEd493E36000CFA345D2db6aCA051A114201579/sources/EmojiRalleyGame.sol
|
Credit ERC20 winnings to the winner's balance inside the contract
|
function handleGameResultsERC20(address token, address winner, uint256 winningsAmount, address[] memory players, uint256[] memory wagers) external onlyOwner {
require(allowedTokens[token], "Token not allowed");
require(players.length == wagers.length, "Players and wagers length mismatch");
tokenBalances[winner][token] = tokenBalances[winner][token].add(winningsAmount);
uint256 winnerWager = 0;
for (uint256 i = 0; i < players.length; i++) {
if (players[i] == winner) {
winnerWager = wagers[i];
break;
}
}
emit WinnerPaid(winner, winningsAmount);
}
| 16,113,613
|
./full_match/44787/0xd7427281B88dCCfd91AA0A83a7a6Fbf65040634c/sources/src/SpiralsStakingV2.sol
|
function initialize(address _validatorGroup) public initializer { SpiralsStaking.initialize(_validatorGroup); }
|
{
pragma solidity ^0.8.10;
import "./SpiralsStaking.sol";
function stake() external payable override nonReentrant {
require(msg.value > 0, "STAKING_ZERO");
lock(msg.value);
vote(msg.value);
stakers[msg.sender].stakedValue += msg.value;
emit UserCeloStaked(msg.sender, validatorGroup, msg.value);
}
}
| 13,268,249
|
pragma solidity 0.5.8;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*/
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*/
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
}
/**
* @title Owner parameters
* @dev Define ownership parameters for this contract
*/
contract Owned { //This token contract is owned
address public owner; //Owner address is public
bool public lockSupply; //Supply Lock flag
/**
* @dev Contract constructor, define initial administrator
*/
constructor() internal {
owner = 0xA0c6f96035d0FA5F44D781060F84A0Bc6B8D87Ee; //Set initial owner to contract creator
emit TransferOwnership(owner);
}
modifier onlyOwner() { //A modifier to define owner-only functions
require(msg.sender == owner, "Not Allowed");
_;
}
modifier supplyLock() { //A modifier to lock supply-change transactions
require(lockSupply == false, "Supply is locked");
_;
}
/**
* @dev Function to set new owner address
* @param _newOwner The address to transfer administration to
*/
function transferAdminship(address _newOwner) public onlyOwner { //Owner can be transfered
require(_newOwner != address(0), "Not allowed");
owner = _newOwner;
emit TransferOwnership(owner);
}
/**
* @dev Function to set supply locks
* @param _set boolean flag (true | false)
*/
function setSupplyLock(bool _set) public onlyOwner { //Only the owner can set a lock on supply
lockSupply = _set;
emit SetSupplyLock(lockSupply);
}
//All owner actions have a log for public review
event SetSupplyLock(bool _set);
event TransferOwnership(address indexed newAdminister);
}
/**
* Token contract interface
*/
contract ERC20TokenInterface {
function balanceOf(address _owner) public view returns(uint256 value);
function transfer(address _to, uint256 _value) public returns(bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns(bool success);
function approve(address _spender, uint256 _value) public returns(bool success);
function allowance(address _owner, address _spender) public view returns(uint256 remaining);
}
/**
* @title Token definition
* @dev Define token parameters, including ERC20 ones
*/
contract ERC20Token is Owned, ERC20TokenInterface {
using SafeMath for uint256;
uint256 public totalSupply;
mapping(address => uint256) balances; //A mapping of all balances per address
mapping(address => mapping(address => uint256)) allowed; //A mapping of all allowances
/**
* @dev Get the balance of an specified address.
* @param _owner The address to be query.
*/
function balanceOf(address _owner) public view returns(uint256 value) {
return balances[_owner];
}
/**
* @dev transfer token to a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns(bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev transfer token from an address to another specified address using allowance
* @param _from The address where token comes.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) {
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Assign allowance to an specified address to use the owner balance
* @param _spender The address to be allowed to spend.
* @param _value The amount to be allowed.
*/
function approve(address _spender, uint256 _value) public returns(bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Get the allowance of an specified address to use another address balance.
* @param _owner The address of the owner of the tokens.
* @param _spender The address of the allowed spender.
*/
function allowance(address _owner, address _spender) public view returns(uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* @dev Burn token of an specified address.
* @param _value amount to burn.
*/
function burnTokens(uint256 _value) public onlyOwner {
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Transfer(msg.sender, address(0), _value);
emit Burned(msg.sender, _value);
}
/**
* @dev Log Events
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burned(address indexed _target, uint256 _value);
}
/**
* @title Asset
* @dev Initial supply creation
*/
contract Asset is ERC20Token {
string public name = 'Orionix';
uint8 public decimals = 18;
string public symbol = 'ORX';
string public version = '2';
constructor() public {
totalSupply = 600000000 * (10 ** uint256(decimals)); //initial token creation
balances[0xA0c6f96035d0FA5F44D781060F84A0Bc6B8D87Ee] = totalSupply;
emit Transfer(
address(0),
0xA0c6f96035d0FA5F44D781060F84A0Bc6B8D87Ee,
balances[0xA0c6f96035d0FA5F44D781060F84A0Bc6B8D87Ee]);
}
/**
*@dev Function to handle callback calls
*/
function () external {
revert("This contract cannot receive direct payments or fallback calls");
}
}
|
Owner can be transfered
|
function transferAdminship(address _newOwner) public onlyOwner {
| 981,441
|
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "./CToken.sol";
interface CompLike {
function delegate(address delegatee) external;
}
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @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
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @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 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) override external returns (uint) {
mintInternal(mintAmount);
return NO_ERROR;
}
/**
* @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) override external returns (uint) {
redeemInternal(redeemTokens);
return NO_ERROR;
}
/**
* @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) override external returns (uint) {
redeemUnderlyingInternal(redeemAmount);
return 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 borrow(uint borrowAmount) override external returns (uint) {
borrowInternal(borrowAmount);
return NO_ERROR;
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) override external returns (uint) {
repayBorrowInternal(repayAmount);
return NO_ERROR;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) override external returns (uint) {
repayBorrowBehalfInternal(borrower, repayAmount);
return NO_ERROR;
}
/**
* @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 repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) override external returns (uint) {
liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return NO_ERROR;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20NonStandardInterface token) override external {
require(msg.sender == admin, "CErc20::sweepToken: only admin can sweep tokens");
require(address(token) != underlying, "CErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.transfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) override external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** 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 tokens owned by this contract
*/
function getCashPrior() virtual override internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) virtual override internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of override external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) virtual override internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of override external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
/**
* @notice Admin call to delegate the votes of the COMP-like underlying
* @param compLikeDelegatee The address to delegate votes to
* @dev CTokens whose underlying are not CompLike should revert here
*/
function _delegateCompLikeTo(address compLikeDelegatee) external {
require(msg.sender == admin, "only the admin may set the comp-like delegate");
CompLike(underlying).delegate(compLikeDelegatee);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "./CErc20.sol";
/**
* @title Compound's CErc20Delegate Contract
* @notice CTokens which wrap an EIP-20 underlying and are delegated to
* @author Compound
*/
contract CErc20Delegate is CErc20, CDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) virtual override public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() virtual override public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _resignImplementation");
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./EIP20Interface.sol";
import "./InterestRateModel.sol";
import "./ExponentialNoError.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
abstract contract CToken is CTokenInterface, ExponentialNoError, 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 == 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 == 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 0 if the transfer succeeded, else revert
*/
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) {
revert TransferComptrollerRejection(allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
revert TransferNotAllowed();
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = type(uint).max;
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
uint allowanceNew = startingAllowance - tokens;
uint srcTokensNew = accountTokens[src] - tokens;
uint dstTokensNew = accountTokens[dst] + tokens;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != type(uint).max) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return 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) override external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == 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) override external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == 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) override 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) override 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) override 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) override external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);
}
/**
* @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) override external view returns (uint, uint, uint, uint) {
return (
NO_ERROR,
accountTokens[account],
borrowBalanceStoredInternal(account),
exchangeRateStoredInternal()
);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() virtual 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() override 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() override 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() override external nonReentrant returns (uint) {
require(accrueInterest() == 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) override external nonReentrant returns (uint) {
require(accrueInterest() == 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) override public view returns (uint) {
return borrowBalanceStoredInternal(account);
}
/**
* @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 (uint) {
/* 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 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
uint principalTimesIndex = borrowSnapshot.principal * borrowIndex;
return principalTimesIndex / borrowSnapshot.interestIndex;
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() override public nonReentrant returns (uint) {
require(accrueInterest() == 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() override public view returns (uint) {
return exchangeRateStoredInternal();
}
/**
* @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() virtual internal view returns (uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return initialExchangeRateMantissa;
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves;
Exp memory exchangeRate = Exp({mantissa: cashPlusBorrowsMinusReserves * expScale / _totalSupply});
return 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() override 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() virtual override public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return 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 */
uint blockDelta = currentBlockNumber - accrualBlockNumberPrior;
/*
* 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 = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta);
uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);
uint totalBorrowsNew = interestAccumulated + borrowsPrior;
uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
/////////////////////////
// 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 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
*/
function mintInternal(uint mintAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
revert MintAccrueInterestFailed(error);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
mintFresh(msg.sender, mintAmount);
}
/**
* @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
*/
function mintFresh(address minter, uint mintAmount) internal {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
revert MintComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert MintFreshnessCheck();
}
Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()});
/////////////////////////
// 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.
*/
uint actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
uint mintTokens = div_(actualMintAmount, exchangeRate);
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
* And write them into storage
*/
totalSupply = totalSupply + mintTokens;
accountTokens[minter] = accountTokens[minter] + mintTokens;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, actualMintAmount, mintTokens);
emit Transfer(address(this), minter, mintTokens);
/* We call the defense hook */
// unused function
// comptroller.mintVerify(address(this), minter, actualMintAmount, mintTokens);
}
/**
* @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
*/
function redeemInternal(uint redeemTokens) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
revert RedeemAccrueInterestFailed(error);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
redeemFresh(payable(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
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
revert RedeemAccrueInterestFailed(error);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
redeemFresh(payable(msg.sender), 0, redeemAmount);
}
/**
* @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)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
/* exchangeRate = invoke Exchange Rate Stored() */
Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal() });
uint redeemTokens;
uint redeemAmount;
/* 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
*/
redeemTokens = redeemTokensIn;
redeemAmount = mul_ScalarTruncate(exchangeRate, redeemTokensIn);
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
redeemTokens = div_(redeemAmountIn, exchangeRate);
redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, redeemTokens);
if (allowed != 0) {
revert RedeemComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert RedeemFreshnessCheck();
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < redeemAmount) {
revert RedeemTransferOutNotPossible();
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We write the previously calculated values into storage.
* Note: Avoid token reentrancy attacks by writing reduced supply before external transfer.
*/
totalSupply = totalSupply - redeemTokens;
accountTokens[redeemer] = accountTokens[redeemer] - redeemTokens;
/*
* 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, redeemAmount);
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), redeemTokens);
emit Redeem(redeemer, redeemAmount, redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, redeemAmount, redeemTokens);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
*/
function borrowInternal(uint borrowAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
revert BorrowAccrueInterestFailed(error);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
borrowFresh(payable(msg.sender), borrowAmount);
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
revert BorrowComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert BorrowFreshnessCheck();
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
revert BorrowCashNotAvailable();
}
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowNew = accountBorrow + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
uint accountBorrowsPrev = borrowBalanceStoredInternal(borrower);
uint accountBorrowsNew = accountBorrowsPrev + borrowAmount;
uint totalBorrowsNew = totalBorrows + borrowAmount;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We write the previously calculated values into storage.
* Note: Avoid token reentrancy attacks by writing increased borrow before external transfer.
`*/
accountBorrows[borrower].principal = accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = totalBorrowsNew;
/*
* 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 emit a Borrow event */
emit Borrow(borrower, borrowAmount, accountBorrowsNew, totalBorrowsNew);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
revert RepayBorrowAccrueInterestFailed(error);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
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, or -1 for the full outstanding amount
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
revert RepayBehalfAccrueInterestFailed(error);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
repayBorrowFresh(msg.sender, borrower, repayAmount);
}
/**
* @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 underlying tokens being returned, or -1 for the full outstanding amount
* @return (uint) the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
revert RepayBorrowComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert RepayBorrowFreshnessCheck();
}
/* We fetch the amount the borrower owes, with accumulated interest */
uint accountBorrowsPrev = borrowBalanceStoredInternal(borrower);
/* If repayAmount == -1, repayAmount = accountBorrows */
uint repayAmountFinal = repayAmount == type(uint).max ? accountBorrowsPrev : 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.
*/
uint actualRepayAmount = doTransferIn(payer, repayAmountFinal);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
uint accountBorrowsNew = accountBorrowsPrev - actualRepayAmount;
uint totalBorrowsNew = totalBorrows - actualRepayAmount;
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, actualRepayAmount, accountBorrowsNew, totalBorrowsNew);
return 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
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant {
uint error = accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
revert LiquidateAccrueBorrowInterestFailed(error);
}
error = cTokenCollateral.accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
revert LiquidateAccrueCollateralInterestFailed(error);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
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
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
revert LiquidateComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert LiquidateFreshnessCheck();
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
revert LiquidateCollateralFreshnessCheck();
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
revert LiquidateLiquidatorIsBorrower();
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
revert LiquidateCloseAmountIsZero();
}
/* Fail if repayAmount = -1 */
if (repayAmount == type(uint).max) {
revert LiquidateCloseAmountIsUintMax();
}
/* Fail if repayBorrow fails */
uint actualRepayAmount = repayBorrowFresh(liquidator, borrower, repayAmount);
/////////////////////////
// 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 == 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
if (address(cTokenCollateral) == address(this)) {
seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
require(cTokenCollateral.seize(liquidator, borrower, seizeTokens) == NO_ERROR, "token seizure failed");
}
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
}
/**
* @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) override external nonReentrant returns (uint) {
seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
return NO_ERROR;
}
/**
* @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
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
revert LiquidateSeizeComptrollerRejection(allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
revert LiquidateSeizeLiquidatorIsBorrower();
}
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
uint protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}));
uint liquidatorSeizeTokens = seizeTokens - protocolSeizeTokens;
Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()});
uint protocolSeizeAmount = mul_ScalarTruncate(exchangeRate, protocolSeizeTokens);
uint totalReservesNew = totalReserves + protocolSeizeAmount;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the calculated values into storage */
totalReserves = totalReservesNew;
totalSupply = totalSupply - protocolSeizeTokens;
accountTokens[borrower] = accountTokens[borrower] - seizeTokens;
accountTokens[liquidator] = accountTokens[liquidator] + liquidatorSeizeTokens;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, liquidatorSeizeTokens);
emit Transfer(borrower, address(this), protocolSeizeTokens);
emit ReservesAdded(address(this), protocolSeizeAmount, totalReservesNew);
}
/*** 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) override external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
revert SetPendingAdminOwnerCheck();
}
// 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 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() override external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
revert AcceptAdminPendingAdminCheck();
}
// 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 = payable(address(0));
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return 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) override public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
revert SetComptrollerOwnerCheck();
}
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 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) override external nonReentrant returns (uint) {
uint error = accrueInterest();
if (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.
revert SetReserveFactorAccrueInterestFailed(error);
}
// _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) {
revert SetReserveFactorAdminCheck();
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert SetReserveFactorFreshCheck();
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
revert SetReserveFactorBoundsCheck();
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return 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 != NO_ERROR) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
revert AddReservesAccrueInterestFailed(error);
}
// _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()) {
revert AddReservesFactorFreshCheck(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;
// 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 (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) override external nonReentrant returns (uint) {
uint error = accrueInterest();
if (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.
revert ReduceReservesAccrueInterestFailed(error);
}
// _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) {
revert ReduceReservesAdminCheck();
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert ReduceReservesFreshCheck();
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
revert ReduceReservesCashNotAvailable();
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
revert ReduceReservesCashValidation();
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// 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 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) override public returns (uint) {
uint error = accrueInterest();
if (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
revert SetInterestRateModelAccrueInterestFailed(error);
}
// _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) {
revert SetInterestRateModelOwnerCheck();
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert SetInterestRateModelFreshCheck();
}
// 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 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() virtual 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) virtual 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) virtual 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
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
import "./EIP20NonStandardInterface.sol";
import "./ErrorReporter.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;
// Maximum borrow rate that can ever be applied (.0005% / block)
uint internal constant borrowRateMaxMantissa = 0.0005e16;
// 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;
// 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;
// Official record of token balances for each account
mapping (address => uint) internal accountTokens;
// 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;
}
// Mapping of account addresses to outstanding borrow balances
mapping(address => BorrowSnapshot) internal accountBorrows;
/**
* @notice Share of seized collateral that is added to reserves
*/
uint public constant protocolSeizeShareMantissa = 2.8e16; //2.8%
}
abstract 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);
/*** User Interface ***/
function transfer(address dst, uint amount) virtual external returns (bool);
function transferFrom(address src, address dst, uint amount) virtual external returns (bool);
function approve(address spender, uint amount) virtual external returns (bool);
function allowance(address owner, address spender) virtual external view returns (uint);
function balanceOf(address owner) virtual external view returns (uint);
function balanceOfUnderlying(address owner) virtual external returns (uint);
function getAccountSnapshot(address account) virtual external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() virtual external view returns (uint);
function supplyRatePerBlock() virtual external view returns (uint);
function totalBorrowsCurrent() virtual external returns (uint);
function borrowBalanceCurrent(address account) virtual external returns (uint);
function borrowBalanceStored(address account) virtual external view returns (uint);
function exchangeRateCurrent() virtual external returns (uint);
function exchangeRateStored() virtual external view returns (uint);
function getCash() virtual external view returns (uint);
function accrueInterest() virtual external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) virtual external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) virtual external returns (uint);
function _acceptAdmin() virtual external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) virtual external returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) virtual external returns (uint);
function _reduceReserves(uint reduceAmount) virtual external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) virtual external returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
abstract contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) virtual external returns (uint);
function redeem(uint redeemTokens) virtual external returns (uint);
function redeemUnderlying(uint redeemAmount) virtual external returns (uint);
function borrow(uint borrowAmount) virtual external returns (uint);
function repayBorrow(uint repayAmount) virtual external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) virtual external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) virtual external returns (uint);
function sweepToken(EIP20NonStandardInterface token) virtual external;
/*** Admin Functions ***/
function _addReserves(uint addAmount) virtual external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
abstract 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) virtual external;
}
abstract 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) virtual external;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() virtual external;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
abstract 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) virtual external returns (uint[] memory);
function exitMarket(address cToken) virtual external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) virtual external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) virtual external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) virtual external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) virtual external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) virtual external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) virtual external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) virtual external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) virtual external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) virtual external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) virtual external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) virtual external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) virtual external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) virtual external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) virtual external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) virtual external view returns (uint, uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
/**
* @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 balance 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 success 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 success 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 success 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 remaining 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);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
/**
* @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 balance 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 success 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 remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
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 {
uint public constant NO_ERROR = 0; // support legacy return codes
error TransferComptrollerRejection(uint256 errorCode);
error TransferNotAllowed();
error TransferNotEnough();
error TransferTooMuch();
error MintComptrollerRejection(uint256 errorCode);
error MintFreshnessCheck();
error MintAccrueInterestFailed(uint256 errorCode);
error RedeemComptrollerRejection(uint256 errorCode);
error RedeemFreshnessCheck();
error RedeemAccrueInterestFailed(uint256 errorCode);
error RedeemTransferOutNotPossible();
error BorrowComptrollerRejection(uint256 errorCode);
error BorrowFreshnessCheck();
error BorrowAccrueInterestFailed(uint256 errorCode);
error BorrowCashNotAvailable();
error RepayBorrowComptrollerRejection(uint256 errorCode);
error RepayBorrowFreshnessCheck();
error RepayBorrowAccrueInterestFailed(uint256 errorCode);
error RepayBehalfAccrueInterestFailed(uint256 errorCode);
error LiquidateComptrollerRejection(uint256 errorCode);
error LiquidateFreshnessCheck();
error LiquidateCollateralFreshnessCheck();
error LiquidateAccrueBorrowInterestFailed(uint256 errorCode);
error LiquidateAccrueCollateralInterestFailed(uint256 errorCode);
error LiquidateLiquidatorIsBorrower();
error LiquidateCloseAmountIsZero();
error LiquidateCloseAmountIsUintMax();
error LiquidateRepayBorrowFreshFailed(uint256 errorCode);
error LiquidateSeizeComptrollerRejection(uint256 errorCode);
error LiquidateSeizeLiquidatorIsBorrower();
error AcceptAdminPendingAdminCheck();
error SetComptrollerOwnerCheck();
error SetPendingAdminOwnerCheck();
error SetReserveFactorAccrueInterestFailed(uint256 errorCode);
error SetReserveFactorAdminCheck();
error SetReserveFactorFreshCheck();
error SetReserveFactorBoundsCheck();
error AddReservesAccrueInterestFailed(uint256 errorCode);
error AddReservesFactorFreshCheck(uint256 actualAddAmount);
error ReduceReservesAccrueInterestFailed(uint256 errorCode);
error ReduceReservesAdminCheck();
error ReduceReservesFreshCheck();
error ReduceReservesCashNotAvailable();
error ReduceReservesCashValidation();
error SetInterestRateModelAccrueInterestFailed(uint256 errorCode);
error SetInterestRateModelOwnerCheck();
error SetInterestRateModelFreshCheck();
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
/**
* @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 a + b;
}
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 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 a * b;
}
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 a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
abstract 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) virtual 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) virtual external view returns (uint);
}
|
Called by the delegator on a delegate to initialize it for duty data The encoded bytes data for any initialization/ Shh -- currently unused Shh -- we don't ever want this hook to be marked pure
|
function _becomeImplementation(bytes memory data) virtual override public {
data;
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _becomeImplementation");
}
| 1,632,448
|
./full_match/44787/0x9a7Ad9FBc46535112710f243c3549878Fe828b0f/sources/ToshaFarm_flat.sol
|
Tosha tokens moved from user -> TokenFarm (Token allocation) -> Strat (compounding)
|
function deposit(uint256 _pid, uint256 _toshaAmt) external nonReentrant {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.shares > 0) {
uint256 pending = user.shares.mul(pool.accTokenPerShare).div(1e12).sub(
user.rewardDebt
);
if (pending > 0) {
safeTokenTransfer(msg.sender, pending);
}
}
if (_toshaAmt > 0) {
pool.tosha.safeTransferFrom(
address(msg.sender),
address(this),
_toshaAmt
);
pool.tosha.safeIncreaseAllowance(pool.strat, _toshaAmt);
uint256 sharesAdded = IStrategy(poolInfo[_pid].strat).deposit(msg.sender, _toshaAmt);
user.shares = user.shares.add(sharesAdded);
}
user.rewardDebt = user.shares.mul(pool.accTokenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _toshaAmt);
}
| 13,247,279
|
./full_match/1/0x44ae17e3C828D068D54093bfb72e4f005C4701ec/sources/contracts/EquityPool.sol
|
Pauses the contract so no interactions can be made
|
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
| 9,603,679
|
./full_match/1/0xd15563162301EcD765bFB54eBd0809b21932C506/sources/contracts/swappers/Uni3Swapper.sol
|
Proxy initialization. Call it after contract deploy.
|
function init(address controller_) external initializer {
__Controllable_init(controller_);
}
| 3,877,011
|
./full_match/4/0x20f48461177a41d98424f9f6aEC1cCD75BD26260/sources/contracts/DiceRoller.sol
|
Roll the n sided die from your set Seed can be an additional sources of entropy Add up all side weights for sides considered
|
function roll(uint256 tokenId, uint256 sideCount, uint256 seed) public view returns (uint256) {
require(sideCount == 4 ||
sideCount == 6 ||
sideCount == 8 ||
sideCount == 10 ||
sideCount == 12 ||
sideCount == 20);
uint256 pseudoRandom = uint256(keccak256(abi.encodePacked(seed, block.basefee, blockhash(block.number-1), msg.sender, address(this))));
uint256 total = 0;
for (uint256 i = 1; i <= sideCount; i++) {
total = total + dice.getSideWeight(tokenId, i);
}
pseudoRandom = pseudoRandom % total + 1;
for (uint256 i = 1; i <= sideCount; i++) {
uint256 sideWeight = dice.getSideWeight(tokenId, i);
if (pseudoRandom <= sideWeight) {
return i;
}
pseudoRandom = pseudoRandom - sideWeight;
}
revert();
}
| 12,461,106
|
./full_match/137/0xa82cAA79F35f7d6B6f1EC1971878F3474C894565/sources/contracts/core/dao/RewardsEscrow.sol
|
Underlying function to calculate the rewards that a user gets We don't want it to error when a vault is empty for the user as this would terminate the entire loop when used in claimRewards()/
|
function _claimReward(bytes32 _escrowId) internal returns (uint256) {
Escrow storage escrow = escrows[_escrowId];
if (escrow.lastUpdateTime <= block.timestamp) {
uint256 claimable = _getClaimableAmount(escrow);
escrow.balance -= claimable;
escrow.lastUpdateTime = block.timestamp;
return claimable;
}
return 0;
}
| 3,776,677
|
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol
|
Approve `to` to operate on `tokenId` The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is either the owner of the token, or approved to operate on all tokens held by this owner. Emits an {Approval} event. Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument./
|
function _approve(address to, uint256 tokenId, address auth) internal {
_approve(to, tokenId, auth, true);
}
| 8,082,151
|
pragma solidity ^0.4.0;
import 'ReentrancyGuard.sol';
/**
* @title Hashed time-locked contract.
*/
contract HTLC is ReentrancyGuard {
enum State {
INITIATED,
COMPLETED,
EXPIRED,
RECLAIMED
}
// Participants in the exchange
address sender;
address recipient;
// Secret hashed by sender
bytes32 image;
// Expiration timestamp
uint expires;
// State of the exchange
State state;
// Events
event Initiated(address _sender, address _recipient, uint _amount, uint _expires);
event Completed(address _sender, address _recipient, uint _amount);
event Expired(address _sender, address _recipient, uint _amount);
event Reclaimed(address _sender, uint _amount);
function HTLC (address _recipient, bytes32 _image, uint _expirationTime) payable {
// Define internal state
sender = msg.sender;
recipient = _recipient;
image = _image;
expires = now + _expirationTime;
state = State.INITIATED;
// Emit an 'Initiated' event
Initiated(sender, recipient, msg.value, expires);
}
/**
* Called by the recipient once they've obtained the primage from the sender.
* This allows them to receive their ETH and complete the transaction.
* @param _preimage - The secret that when hashed will produce the original image
*/
function complete (bytes32 _preimage) public nonReentrant {
require(hash(_preimage) == image);
require(msg.sender == recipient);
require(state == State.INITIATED);
// Check if the completion comes early enough
if (now <= expires) {
// Remember the amount to be transfered
uint amount = this.balance;
// Attempt to transfer it
msg.sender.transfer(this.balance);
// The exchange is completed
state = State.COMPLETED;
Completed(sender, recipient, amount);
} else {
// The exchange has expired
state = State.EXPIRED;
Expired(sender, recipient, this.balance);
}
}
/**
* Called by the sender after the expiration time has elapsed. If the recipient
* was not able to complete the transaction in time and the sender can prove
* they have the secret they're able to reclaim their funds.
* @param _preimage - The secret that when hashed will produce the original image
*/
function reclaim (bytes32 _preimage) public nonReentrant {
require(hash(_preimage) == image);
require(msg.sender == sender);
require(
state == State.EXPIRED ||
state == State.INITIATED
);
// Check if reclaiming is possible at all
if (state == State.EXPIRED || state == State.INITIATED && now > expires) {
// Remember the amount to be transfered
uint amount = this.balance;
// Attempt to transfer it
sender.transfer(amount);
// The intiator has reclaimed their funds
state = State.RECLAIMED;
Reclaimed(sender, amount);
} else {
revert();
}
}
// Helper functions
/**
* The hash function for producing the image from the preimage. Right now
* this is using SHA256 but it should be updated to use SHA256d.
* @param _preimage - The value to hash
* @return The hashed image
*/
function hash (bytes32 _preimage) internal returns (bytes32 _image) {
return sha256(_preimage);
}
}
|
The hash function for producing the image from the preimage. Right now this is using SHA256 but it should be updated to use SHA256d. _preimage - The value to hash return The hashed image/
|
function hash (bytes32 _preimage) internal returns (bytes32 _image) {
return sha256(_preimage);
}
| 6,365,283
|
./full_match/4/0x07F4e7554C0D33339b3F6669bA09142D71DaB44a/sources/contracts/util/AllowList.sol
|
Given a Merkle proof, check if an address is AllowListed against the root _proof Merkle proof _address address to check against allow listreturn boolean isAllowListed
|
function isAllowListed(bytes32[] calldata _proof, address _address)
public
view
returns (bool)
{
return
verify(_proof, merkleRoot, keccak256(abi.encodePacked(_address)));
}
| 12,372,609
|
pragma solidity 0.5.8;
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol
interface IERC20 {
function TOTALSUPPLY82() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF530(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER438(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE833(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE538(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM818(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER722(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL422(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
library SafeMath {
function ADD23(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB764(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function MUL177(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV24(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD404(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY82() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF530(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER438(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER27(msg.sender, recipient, amount);
return true;
}
function ALLOWANCE833(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE538(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, value);
return true;
}
function TRANSFERFROM818(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER27(sender, recipient, amount);
_APPROVE258(sender, msg.sender, _allowances[sender][msg.sender].SUB764(amount));
return true;
}
function INCREASEALLOWANCE45(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, _allowances[msg.sender][spender].ADD23(addedValue));
return true;
}
function DECREASEALLOWANCE159(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, _allowances[msg.sender][spender].SUB764(subtractedValue));
return true;
}
function _TRANSFER27(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB764(amount);
_balances[recipient] = _balances[recipient].ADD23(amount);
emit TRANSFER722(sender, recipient, amount);
}
function _MINT102(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD23(amount);
_balances[account] = _balances[account].ADD23(amount);
emit TRANSFER722(address(0), account, amount);
}
function _BURN692(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.SUB764(value);
_balances[account] = _balances[account].SUB764(value);
emit TRANSFER722(account, address(0), value);
}
function _APPROVE258(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit APPROVAL422(owner, spender, value);
}
function _BURNFROM631(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN692(account, amount);
_APPROVE258(account, msg.sender, _allowances[account][msg.sender].SUB764(amount));
}
}
// File: J\contracts\Goodluck(LUCK).sol
contract Goodluck is ERC20 {
string public constant name423 = "Goodluck"; //inject NONSTANDARD NAMING
string public constant symbol470 = "LUCK"; //inject NONSTANDARD NAMING
uint8 public constant decimals728 = 18; //inject NONSTANDARD NAMING
uint256 public constant initialsupply595 = 2000000000 * (10 ** uint256(decimals728)); //inject NONSTANDARD NAMING
constructor() public {
super._MINT102(msg.sender, initialsupply595);
owner = msg.sender;
}
//ownership
address public owner;
event OWNERSHIPRENOUNCED774(address indexed previousOwner); //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED463( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
modifier ONLYOWNER394() { //inject NONSTANDARD NAMING
require(msg.sender == owner, "Not owner");
_;
}
function RENOUNCEOWNERSHIP445() public ONLYOWNER394 { //inject NONSTANDARD NAMING
emit OWNERSHIPRENOUNCED774(owner);
owner = address(0);
}
function TRANSFEROWNERSHIP781(address _newOwner) public ONLYOWNER394 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP16(_newOwner);
}
function _TRANSFEROWNERSHIP16(address _newOwner) internal { //inject NONSTANDARD NAMING
require(_newOwner != address(0), "Already owner");
emit OWNERSHIPTRANSFERRED463(owner, _newOwner);
owner = _newOwner;
}
//pausable
event PAUSE475(); //inject NONSTANDARD NAMING
event UNPAUSE568(); //inject NONSTANDARD NAMING
bool public paused = false;
modifier WHENNOTPAUSED995() { //inject NONSTANDARD NAMING
require(!paused, "Paused by owner");
_;
}
modifier WHENPAUSED712() { //inject NONSTANDARD NAMING
require(paused, "Not paused now");
_;
}
function PAUSE841() public ONLYOWNER394 WHENNOTPAUSED995 { //inject NONSTANDARD NAMING
paused = true;
emit PAUSE475();
}
function UNPAUSE13() public ONLYOWNER394 WHENPAUSED712 { //inject NONSTANDARD NAMING
paused = false;
emit UNPAUSE568();
}
//freezable
event FROZEN932(address target); //inject NONSTANDARD NAMING
event UNFROZEN285(address target); //inject NONSTANDARD NAMING
mapping(address => bool) internal freezes;
modifier WHENNOTFROZEN284() { //inject NONSTANDARD NAMING
require(!freezes[msg.sender], "Sender account is locked.");
_;
}
function FREEZE724(address _target) public ONLYOWNER394 { //inject NONSTANDARD NAMING
freezes[_target] = true;
emit FROZEN932(_target);
}
function UNFREEZE196(address _target) public ONLYOWNER394 { //inject NONSTANDARD NAMING
freezes[_target] = false;
emit UNFROZEN285(_target);
}
function ISFROZEN713(address _target) public view returns (bool) { //inject NONSTANDARD NAMING
return freezes[_target];
}
function TRANSFER438( //inject NONSTANDARD NAMING
address _to,
uint256 _value
)
public
WHENNOTFROZEN284
WHENNOTPAUSED995
returns (bool)
{
RELEASELOCK766(msg.sender);
return super.TRANSFER438(_to, _value);
}
function TRANSFERFROM818( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _value
)
public
WHENNOTPAUSED995
returns (bool)
{
require(!freezes[_from], "From account is locked.");
RELEASELOCK766(_from);
return super.TRANSFERFROM818(_from, _to, _value);
}
//mintable
event MINT926(address indexed to, uint256 amount); //inject NONSTANDARD NAMING
function MINT957( //inject NONSTANDARD NAMING
address _to,
uint256 _amount
)
public
ONLYOWNER394
returns (bool)
{
super._MINT102(_to, _amount);
emit MINT926(_to, _amount);
return true;
}
//burnable
event BURN684(address indexed burner, uint256 value); //inject NONSTANDARD NAMING
function BURN342(address _who, uint256 _value) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(_value <= super.BALANCEOF530(_who), "Balance is too small.");
_BURN692(_who, _value);
emit BURN684(_who, _value);
}
//lockable
struct LockInfo {
uint256 releaseTime;
uint256 balance;
}
mapping(address => LockInfo[]) internal lockInfo;
event LOCK205(address indexed holder, uint256 value, uint256 releaseTime); //inject NONSTANDARD NAMING
event UNLOCK375(address indexed holder, uint256 value); //inject NONSTANDARD NAMING
function BALANCEOF530(address _holder) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
uint256 lockedBalance = 0;
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
lockedBalance = lockedBalance.ADD23(lockInfo[_holder][i].balance);
}
return super.BALANCEOF530(_holder).ADD23(lockedBalance);
}
function RELEASELOCK766(address _holder) internal { //inject NONSTANDARD NAMING
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
if (lockInfo[_holder][i].releaseTime <= now) {
_balances[_holder] = _balances[_holder].ADD23(lockInfo[_holder][i].balance);
emit UNLOCK375(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
i--;
}
lockInfo[_holder].length--;
}
}
}
function LOCKCOUNT904(address _holder) public view returns (uint256) { //inject NONSTANDARD NAMING
return lockInfo[_holder].length;
}
function LOCKSTATE154(address _holder, uint256 _idx) public view returns (uint256, uint256) { //inject NONSTANDARD NAMING
return (lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance);
}
function LOCK109(address _holder, uint256 _amount, uint256 _releaseTime) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(super.BALANCEOF530(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].SUB764(_amount);
lockInfo[_holder].push(
LockInfo(_releaseTime, _amount)
);
emit LOCK205(_holder, _amount, _releaseTime);
}
function LOCKAFTER210(address _holder, uint256 _amount, uint256 _afterTime) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(super.BALANCEOF530(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].SUB764(_amount);
lockInfo[_holder].push(
LockInfo(now + _afterTime, _amount)
);
emit LOCK205(_holder, _amount, now + _afterTime);
}
function UNLOCK592(address _holder, uint256 i) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(i < lockInfo[_holder].length, "No lock information.");
_balances[_holder] = _balances[_holder].ADD23(lockInfo[_holder][i].balance);
emit UNLOCK375(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
}
lockInfo[_holder].length--;
}
function TRANSFERWITHLOCK415(address _to, uint256 _value, uint256 _releaseTime) public ONLYOWNER394 returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0), "wrong address");
require(_value <= super.BALANCEOF530(owner), "Not enough balance");
_balances[owner] = _balances[owner].SUB764(_value);
lockInfo[_to].push(
LockInfo(_releaseTime, _value)
);
emit TRANSFER722(owner, _to, _value);
emit LOCK205(_to, _value, _releaseTime);
return true;
}
function TRANSFERWITHLOCKAFTER686(address _to, uint256 _value, uint256 _afterTime) public ONLYOWNER394 returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0), "wrong address");
require(_value <= super.BALANCEOF530(owner), "Not enough balance");
_balances[owner] = _balances[owner].SUB764(_value);
lockInfo[_to].push(
LockInfo(now + _afterTime, _value)
);
emit TRANSFER722(owner, _to, _value);
emit LOCK205(_to, _value, now + _afterTime);
return true;
}
function CURRENTTIME149() public view returns (uint256) { //inject NONSTANDARD NAMING
return now;
}
function AFTERTIME613(uint256 _value) public view returns (uint256) { //inject NONSTANDARD NAMING
return now + _value;
}
//airdrop
mapping (address => uint256) public airDropHistory;
event AIRDROP940(address _receiver, uint256 _amount); //inject NONSTANDARD NAMING
function DROPTOKEN612(address[] memory receivers, uint256[] memory values) ONLYOWNER394 public { //inject NONSTANDARD NAMING
require(receivers.length != 0);
require(receivers.length == values.length);
for (uint256 i = 0; i < receivers.length; i++) {
address receiver = receivers[i];
uint256 amount = values[i];
TRANSFER438(receiver, amount);
airDropHistory[receiver] += amount;
emit AIRDROP940(receiver, amount);
}
}
}
|
inject NONSTANDARD NAMING
|
function APPROVE538(address spender, uint256 value) public returns (bool) {
| 12,758,961
|
./full_match/80001/0x5ABE48790A7551FDa05020CDA93B9B1C48Cdf36F/sources/contract/Miracle-Staking/module/Miralce-Stake-Core.sol
|
A function to claim agent rewards for staking. _user The address of the user who wants to claim their agent rewards./
|
function _claimAgent(address _user) internal {
totalClaimed = totalClaimed + _PoolReward + _PlayerReward + _DaoReward + _PoolReward;
}
| 5,698,258
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title : ProximaFaucet
* Developed by ProximusAlpha
*/
contract ProximaFaucet is Ownable {
/// @dev Proxima Token
IERC20 public pxa;
/// @dev Claim state enum
enum Options {Every8Hours, Every24Hours, Every72Hours}
/// @dev Constant time window for claim
uint256 constant hours8InSeconds = 8 * 60 * 60;
uint256 constant hours24InSeconds = 24 * 60 * 60;
uint256 constant hours72InSeconds = 72 * 60 * 60;
/// @dev Constant amount window for claim
uint256 constant hours8Fund = 0.25 ether;
uint256 constant hours24Fund = 0.75 ether;
uint256 constant hours72Fund = 2.25 ether;
/// @dev Total number of claims
uint256 private claimCounter;
/// @dev Event emitted when claimed
event Funded(address receiver, uint256 amount);
/// @dev Claim time map
mapping(address => uint256) nextFundingTime;
/// @dev Sets pxa token
constructor(IERC20 _pxa) public {
pxa = _pxa;
}
/// @dev Transfer claimed pxa token
function getFunds(Options _option) public {
int256 duration = int256(nextFundingTime[msg.sender] - block.timestamp);
require(duration < 1, "PF : FAUCET_COOLDOWN");
if (_option == Options.Every24Hours) {
transferFund(hours24InSeconds, hours24Fund);
} else if (_option == Options.Every72Hours) {
transferFund(hours72InSeconds, hours72Fund);
} else {
transferFund(hours8InSeconds, hours8Fund);
}
}
function transferFund(uint256 _timeInSecond, uint256 _fund) private {
require(_fund < getFaucetBalance(), "PF: FAUCET_DEPLETED");
nextFundingTime[msg.sender] = block.timestamp + _timeInSecond;
claimCounter++;
pxa.transfer(msg.sender, _fund);
emit Funded(msg.sender, _fund);
}
/// @dev Returns next claim time for user
function nextFunding(address _who) public view returns (uint256) {
return nextFundingTime[_who];
}
/// @dev Returns claim counter
function counter() public view returns (uint256) {
return claimCounter;
}
/// @dev Returns faucet balance
function getFaucetBalance() public view returns (uint256) {
return pxa.balanceOf(address(this));
}
}
|
Transfer claimed pxa token
|
function getFunds(Options _option) public {
int256 duration = int256(nextFundingTime[msg.sender] - block.timestamp);
require(duration < 1, "PF : FAUCET_COOLDOWN");
if (_option == Options.Every24Hours) {
transferFund(hours24InSeconds, hours24Fund);
transferFund(hours72InSeconds, hours72Fund);
transferFund(hours8InSeconds, hours8Fund);
}
}
| 7,238,873
|
./partial_match/1/0x5DF02cB5d5aD552E5728d3ca20f650CB0d5a94Fb/sources/Shushii.sol
|
Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted./
|
function _getApproved(uint256 tokenId) internal view virtual returns (address) {
return _tokenApprovals[tokenId];
}
| 2,735,501
|
pragma solidity >=0.4.21 <0.6.0;
contract AdminRole {
using Roles for Roles.Role;
event AdminAdded(address indexed account);
event AdminRemoved(address indexed account);
Roles.Role private _Admins;
address private _owner;
constructor () internal {
_addAdmin(msg.sender);
_owner = msg.sender;
}
modifier onlyAdmin() {
require(isAdmin(msg.sender));
_;
}
modifier onlyOwner() {
require(msg.sender == _owner);
_;
}
function addAdmin(address account) public onlyOwner {
_addAdmin(account);
}
function removeAdmin(address account) public onlyOwner {
_removeAdmin(account);
}
function transferOwnership(address account) public onlyOwner returns (bool) {
_Admins.add(account);
_owner = account;
return true;
}
function isAdmin(address account) public view returns (bool) {
return _Admins.has(account);
}
function _addAdmin(address account) internal {
_Admins.add(account);
emit AdminAdded(account);
}
function _removeAdmin(address account) internal {
_Admins.remove(account);
emit AdminRemoved(account);
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Equity is IERC20, AdminRole {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
string private _contractHash;
string private _contractUrl;
constructor (
string memory name,
string memory symbol,
uint8 decimals,
string memory contractHash,
string memory contractUrl) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply = 0;
_contractHash = contractHash;
_contractUrl = contractUrl;
}
/**
* @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 contractHash
*/
function contractHash() public view returns (string memory) {
return _contractHash;
}
/**
* @return the contractUrl
*/
function contractUrl() public view returns (string memory) {
return _contractUrl;
}
/**
* @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 Destroy the contract
*/
function Destroy() public onlyAdmin returns (bool) {
selfdestruct(msg.sender);
return true;
}
/**
* @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 sudo Transfer tokens
* @param from The address to transfer from.
* @param to The address to transfer to.1
* @param value The amount to be transferred.
*/
function sudoTransfer(address from, address to, uint256 value) public onlyAdmin returns (bool) {
_transfer(from, to, value);
return true;
}
/**
* @dev Mint tokens
* @param to The address to mint in.
* @param value The amount to be minted.
*/
function Mint(address to, uint256 value) public onlyAdmin returns (bool) {
_mint(to, value);
return true;
}
/**
* @dev Burn tokens
* @param from The address to burn in.
* @param value The amount to be burned.
*/
function Burn(address from, uint256 value) public onlyAdmin returns (bool) {
_burn(from, value);
return true;
}
/**
* @dev set the contract URL
* @param newContractUrl The new contract URL.
*/
function setContractUrl(string memory newContractUrl) public onlyAdmin returns (bool) {
_contractUrl = newContractUrl;
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),"0x0 Address");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0),"0x0 Address");
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0),"0x0 Address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
|
Mint tokens to The address to mint in. value The amount to be minted./
|
function Mint(address to, uint256 value) public onlyAdmin returns (bool) {
_mint(to, value);
return true;
}
| 1,069,856
|
./full_match/42220/0x6ea01ea80FeB4313C3329e6e9fcA751CCb2cF323/sources/out/ManagedPoolFactory_flat.sol
|
computeProportionalAmountsOut (per token) aO = tokenAmountOut / bptIn \ b = tokenBalance a0 = b | --------------------- | bptIn = bptAmountIn \ bptTotalSupply / bpt = bptTotalSupply Since we're computing an amount out, we round down overall. This means rounding down on both the multiplication and division.
|
function computeProportionalAmountsOut(
uint256[] memory balances,
uint256 bptTotalSupply,
uint256 bptAmountIn
) internal pure returns (uint256[] memory amountsOut) {
uint256 bptRatio = bptAmountIn.divDown(bptTotalSupply);
amountsOut = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
amountsOut[i] = balances[i].mulDown(bptRatio);
}
}
| 16,352,793
|
/*
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.4.24;
/*
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.
*/
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title 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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title 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);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
///@title Custom Ownable
///@notice Custom ownable contract.
contract CustomOwnable is Ownable {
///The trustee wallet.
address private _trustee;
event TrusteeAssigned(address indexed account);
///@notice Validates if the sender is actually the trustee.
modifier onlyTrustee() {
require(msg.sender == _trustee, "Access is denied.");
_;
}
///@notice Assigns or changes the trustee wallet.
///@param _account A wallet address which will become the new trustee.
///@return Returns true if the operation was successful.
function assignTrustee(address _account) external onlyOwner returns(bool) {
require(_account != address(0), "Please provide a valid address for trustee.");
_trustee = _account;
emit TrusteeAssigned(_account);
return true;
}
///@notice Changes the owner of this contract.
///@param _newOwner Specify a wallet address which will become the new owner.
///@return Returns true if the operation was successful.
function reassignOwner(address _newOwner) external onlyTrustee returns(bool) {
super._transferOwnership(_newOwner);
return true;
}
///@notice The trustee wallet has the power to change the owner in case of unforeseen or unavoidable situation.
///@return Wallet address of the trustee account.
function getTrustee() external view returns(address) {
return _trustee;
}
}
///@title This contract enables to create multiple contract administrators.
contract CustomAdmin is CustomOwnable {
///@notice List of administrators.
mapping(address => bool) public admins;
event AdminAdded(address indexed _address);
event AdminRemoved(address indexed _address);
///@notice Validates if the sender is actually an administrator.
modifier onlyAdmin() {
require(isAdmin(msg.sender), "Access is denied.");
_;
}
///@notice Adds the specified address to the list of administrators.
///@param _address The address to add to the administrator list.
function addAdmin(address _address) external onlyAdmin returns(bool) {
require(_address != address(0), "Invalid address.");
require(!admins[_address], "This address is already an administrator.");
require(_address != owner, "The owner cannot be added or removed to or from the administrator list.");
admins[_address] = true;
emit AdminAdded(_address);
return true;
}
///@notice Adds multiple addresses to the administrator list.
///@param _accounts The wallet addresses to add to the administrator list.
function addManyAdmins(address[] _accounts) external onlyAdmin returns(bool) {
for(uint8 i = 0; i < _accounts.length; i++) {
address account = _accounts[i];
///Zero address cannot be an admin.
///The owner is already an admin and cannot be assigned.
///The address cannot be an existing admin.
if(account != address(0) && !admins[account] && account != owner) {
admins[account] = true;
emit AdminAdded(_accounts[i]);
}
}
return true;
}
///@notice Removes the specified address from the list of administrators.
///@param _address The address to remove from the administrator list.
function removeAdmin(address _address) external onlyAdmin returns(bool) {
require(_address != address(0), "Invalid address.");
require(admins[_address], "This address isn't an administrator.");
//The owner cannot be removed as admin.
require(_address != owner, "The owner cannot be added or removed to or from the administrator list.");
admins[_address] = false;
emit AdminRemoved(_address);
return true;
}
///@notice Removes multiple addresses to the administrator list.
///@param _accounts The wallet addresses to add to the administrator list.
function removeManyAdmins(address[] _accounts) external onlyAdmin returns(bool) {
for(uint8 i = 0; i < _accounts.length; i++) {
address account = _accounts[i];
///Zero address can neither be added or removed from this list.
///The owner is the super admin and cannot be removed.
///The address must be an existing admin in order for it to be removed.
if(account != address(0) && admins[account] && account != owner) {
admins[account] = false;
emit AdminRemoved(_accounts[i]);
}
}
return true;
}
///@notice Checks if an address is an administrator.
function isAdmin(address _address) public view returns(bool) {
if(_address == owner) {
return true;
}
return admins[_address];
}
}
///@title This contract enables you to create pausable mechanism to stop in case of emergency.
contract CustomPausable is CustomAdmin {
event Paused();
event Unpaused();
bool public paused = false;
///@notice Verifies whether the contract is not paused.
modifier whenNotPaused() {
require(!paused, "Sorry but the contract isn't paused.");
_;
}
///@notice Verifies whether the contract is paused.
modifier whenPaused() {
require(paused, "Sorry but the contract is paused.");
_;
}
///@notice Pauses the contract.
function pause() external onlyAdmin whenNotPaused {
paused = true;
emit Paused();
}
///@notice Unpauses the contract and returns to normal state.
function unpause() external onlyAdmin whenPaused {
paused = false;
emit Unpaused();
}
}
contract CustomLockable is CustomAdmin {
///Locking list contains list of wallets and their respective release dates.
mapping(address => uint256) public lockingList;
///Signifies if the locking feature can be used.
bool public canLock = true;
event TokenLocked(address indexed _address, uint256 _releaseDate);
event TokenUnlocked(address indexed _address);
event LockingDisabled();
///@notice Reverts this transfer if the wallet is in the locking list.
modifier revertIfLocked(address _wallet) {
require(!isLocked(_wallet), "The operation was cancelled because your tokens are locked.");
_;
}
///@notice Checks if a wallet is locked for transfers.
function isLocked(address _wallet) public view returns(bool) {
uint256 _lockedUntil = lockingList[_wallet];
//solium-disable-next-line
if(_lockedUntil > now) {
return true;
}
return false;
}
///@notice Adds the specified address to the locking list.
///@param _address The address to add to the locking list.
///@param _releaseDate The date when the tokens become avaiable for transfer.
function addLock(address _address, uint256 _releaseDate) external onlyAdmin returns(bool) {
require(canLock, "Access is denied. This feature was already disabled by an administrator.");
require(_address != address(0), "Invalid address.");
require(!admins[_address], "Cannot lock administrators.");
require(_address != owner, "Cannot lock the owner.");
lockingList[_address] = _releaseDate;
if(_releaseDate > 0) {
emit TokenLocked(_address, _releaseDate);
} else {
emit TokenUnlocked(_address);
}
return true;
}
///@notice Adds multiple addresses to the locking list.
///@param _accounts The wallet addresses to add to the locking list.
///@param _releaseDate The date when the tokens become avaiable for transfer.
function addManyLocks(address[] _accounts, uint256 _releaseDate) external onlyAdmin returns(bool) {
require(canLock, "Access is denied. This feature was already disabled by an administrator.");
require(_releaseDate > 0, "Invalid release date.");
for(uint8 i = 0; i < _accounts.length; i++) {
address _account = _accounts[i];
///Zero address, admins, and owner cannot be locked.
if(_account != address(0) && !admins[_account] && _account != owner) {
lockingList[_account] = _releaseDate;
emit TokenLocked(_account, _releaseDate);
}
}
return true;
}
///@notice Removes multiple addresses from the locking list.
///@param _accounts The wallet addresses to unlock.
function removeManyLocks(address[] _accounts) external onlyAdmin returns(bool) {
require(canLock, "Access is denied. This feature was already disabled by an administrator.");
for(uint8 i = 0; i < _accounts.length; i++) {
address _account = _accounts[i];
lockingList[_account] = 0;
emit TokenUnlocked(_account);
}
return true;
}
///@notice Once locking feature is disable, it cannot be
///truned back on thenceforth.
function disableLocking() external onlyAdmin returns(bool) {
require(canLock, "The token lock feature is already disabled.");
canLock = false;
emit LockingDisabled();
return true;
}
}
///@title Transfer State Contract
///@notice Enables the admins to maintain the transfer state.
///Transfer state when disabled disallows everyone but admins to transfer tokens.
contract TransferState is CustomPausable {
bool public released = false;
event TokenReleased(bool _state);
///@notice Checks if the supplied address is able to perform transfers.
///@param _from The address to check against if the transfer is allowed.
modifier canTransfer(address _from) {
if(paused || !released) {
if(!isAdmin(_from)) {
revert("Operation not allowed. The transfer state is restricted.");
}
}
_;
}
///@notice This function enables token transfers for everyone.
///Can only be enabled after the end of the ICO.
function enableTransfers() external onlyAdmin whenNotPaused returns(bool) {
require(!released, "Invalid operation. The transfer state is no more restricted.");
released = true;
emit TokenReleased(released);
return true;
}
///@notice This function disables token transfers for everyone.
function disableTransfers() external onlyAdmin whenNotPaused returns(bool) {
require(released, "Invalid operation. The transfer state is already restricted.");
released = false;
emit TokenReleased(released);
return true;
}
}
contract BulkTransfer is StandardToken, CustomAdmin {
event BulkTransferPerformed(address[] _destinations, uint256[] _amounts);
///@notice Allows only the admins and/or whitelisted applications to perform bulk transfer operation.
///@param _destinations The destination wallet addresses to send funds to.
///@param _amounts The respective amount of fund to send to the specified addresses.
function bulkTransfer(address[] _destinations, uint256[] _amounts) public onlyAdmin returns(bool) {
require(_destinations.length == _amounts.length, "Invalid operation.");
//Saving gas by determining if the sender has enough balance
//to post this transaction.
uint256 requiredBalance = sumOf(_amounts);
require(balances[msg.sender] >= requiredBalance, "You don't have sufficient funds to transfer amount that large.");
for (uint256 i = 0; i < _destinations.length; i++) {
transfer(_destinations[i], _amounts[i]);
}
emit BulkTransferPerformed(_destinations, _amounts);
return true;
}
///@notice Returns the sum of supplied values.
///@param _values The collection of values to create the sum from.
function sumOf(uint256[] _values) private pure returns(uint256) {
uint256 total = 0;
for (uint256 i = 0; i < _values.length; i++) {
total = total.add(_values[i]);
}
return total;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
contract Reclaimable is CustomAdmin {
using SafeERC20 for ERC20;
///@notice Transfers all Ether held by the contract to the owner.
function reclaimEther() external onlyAdmin {
msg.sender.transfer(address(this).balance);
}
///@notice Transfers all ERC20 tokens held by the contract to the owner.
///@param _token The amount of token to reclaim.
function reclaimToken(address _token) external onlyAdmin {
ERC20 erc20 = ERC20(_token);
uint256 balance = erc20.balanceOf(this);
erc20.safeTransfer(msg.sender, balance);
}
}
///@title CyberAudit Base Contract
contract TokenBase is StandardToken, TransferState, BulkTransfer, Reclaimable, BurnableToken, CustomLockable {
//solhint-disable
uint8 public constant decimals = 18;
string public constant name = "Cyber Audit";
string public constant symbol = "AUDIT";
//solhint-enable
uint256 internal constant MILLION = 1000000 * 1 ether;
uint256 public constant MAX_SUPPLY = 50 * MILLION;
event Mint(address indexed to, uint256 amount);
constructor() public {
mintTokens(msg.sender, MAX_SUPPLY);
}
///@notice Transfers the specified value of Audit Tokens to the destination address.
//Transfers can only happen when the transfer state is enabled.
//Transfer state can only be enabled after the end of the crowdsale.
///@param _to The destination wallet address to transfer funds to.
///@param _value The amount of tokens to send to the destination address.
function transfer(address _to, uint256 _value)
public
revertIfLocked(msg.sender)
canTransfer(msg.sender)
returns(bool) {
require(_to != address(0), "Invalid address.");
return super.transfer(_to, _value);
}
///@notice Transfers tokens from a specified wallet address.
///@dev This function is overridden to leverage transfer state feature.
///@param _from The address to transfer funds from.
///@param _to The address to transfer funds to.
///@param _value The amount of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value)
public
revertIfLocked(_from)
canTransfer(_from)
returns(bool) {
require(_to != address(0), "Invalid address.");
return super.transferFrom(_from, _to, _value);
}
///@notice Approves a wallet address to spend on behalf of the sender.
///@dev This function is overridden to leverage transfer state feature.
///@param _spender The address which is approved to spend on behalf of the sender.
///@param _value The amount of tokens approve to spend.
function approve(address _spender, uint256 _value)
public
revertIfLocked(msg.sender)
canTransfer(msg.sender)
returns(bool) {
require(_spender != address(0), "Invalid address.");
return super.approve(_spender, _value);
}
///@notice Increases the approval of the spender.
///@dev This function is overridden to leverage transfer state feature.
///@param _spender The address which is approved to spend on behalf of the sender.
///@param _addedValue The added amount of tokens approved to spend.
function increaseApproval(address _spender, uint256 _addedValue)
public
revertIfLocked(msg.sender)
canTransfer(msg.sender)
returns(bool) {
require(_spender != address(0), "Invalid address.");
return super.increaseApproval(_spender, _addedValue);
}
///@notice Decreases the approval of the spender.
///@dev This function is overridden to leverage transfer state feature.
///@param _spender The address of the spender to decrease the allocation from.
///@param _subtractedValue The amount of tokens to subtract from the approved allocation.
function decreaseApproval(address _spender, uint256 _subtractedValue)
public
revertIfLocked(msg.sender)
canTransfer(msg.sender)
returns(bool) {
require(_spender != address(0), "Invalid address.");
return super.decreaseApproval(_spender, _subtractedValue);
}
///@notice Burns the coins held by the sender.
///@param _value The amount of coins to burn.
///@dev This function is overridden to leverage Pausable feature.
function burn(uint256 _value)
public
revertIfLocked(msg.sender)
whenNotPaused {
super.burn(_value);
}
///@notice Mints the supplied value of the tokens to the destination address.
//Minting cannot be performed any further once the maximum supply is reached.
//This function cannot be used by anyone except for this contract.
///@param _to The address which will receive the minted tokens.
///@param _value The amount of tokens to mint.
function mintTokens(address _to, uint _value) internal returns(bool) {
require(_to != address(0), "Invalid address.");
require(totalSupply_.add(_value) <= MAX_SUPPLY, "Sorry but the total supply can't exceed the maximum supply.");
balances[_to] = balances[_to].add(_value);
totalSupply_ = totalSupply_.add(_value);
emit Transfer(address(0), _to, _value);
emit Mint(_to, _value);
return true;
}
}
///@title Cyber Audit
contract AuditToken is TokenBase {
}
|
Adds multiple addresses to the administrator list. _accounts The wallet addresses to add to the administrator list.Zero address cannot be an admin.The owner is already an admin and cannot be assigned.The address cannot be an existing admin.
|
function addManyAdmins(address[] _accounts) external onlyAdmin returns(bool) {
for(uint8 i = 0; i < _accounts.length; i++) {
address account = _accounts[i];
if(account != address(0) && !admins[account] && account != owner) {
admins[account] = true;
emit AdminAdded(_accounts[i]);
}
}
return true;
}
| 6,070,697
|
./full_match/80001/0xA0B014408A4174543a99C998EAf5851DE41F7A89/sources/contracts/dexBlen/blendverse-core/contracts/BlendversePair.sol
|
this low-level function should be called from a contract which performs important safety checks
|
function mint(address to) external lock returns (uint256 liquidity) {
uint256 balance0 = IBEP20(token0).balanceOf(address(this));
uint256 balance1 = IBEP20(token1).balanceOf(address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
if (_totalSupply == 0) {
liquidity = SafeMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
liquidity = SafeMath.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'BlendversePair: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
emit Mint(msg.sender, amount0, amount1);
}
| 5,635,492
|
pragma solidity ^0.5.15;
pragma experimental ABIEncoderV2;
/**
* @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);
}
interface UniswapPair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* 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;
}
}
/// Helper for a reserve contract to perform uniswap, price bound actions
contract UniHelper{
using SafeMath for uint256;
uint256 internal constant ONE = 10**18;
function _mintLPToken(
UniswapPair uniswap_pair,
IERC20 token0,
IERC20 token1,
uint256 amount_token0,
address token1_source
) internal {
(uint256 reserve0, uint256 reserve1, ) = uniswap_pair
.getReserves();
uint256 quoted = quote(reserve1, reserve0);
uint256 amount_token1 = quoted.mul(amount_token0).div(ONE);
token0.transfer(address(uniswap_pair), amount_token0);
token1.transferFrom(token1_source, address(uniswap_pair), amount_token1);
UniswapPair(uniswap_pair).mint(address(this));
}
function _burnLPToken(UniswapPair uniswap_pair, address destination) internal {
uniswap_pair.transfer(
address(uniswap_pair),
uniswap_pair.balanceOf(address(this))
);
UniswapPair(uniswap_pair).burn(destination);
}
function quote(uint256 purchaseAmount, uint256 saleAmount)
internal
pure
returns (uint256)
{
return purchaseAmount.mul(ONE).div(saleAmount);
}
}
contract YamGoverned {
event NewGov(address oldGov, address newGov);
event NewPendingGov(address oldPendingGov, address newPendingGov);
address public gov;
address public pendingGov;
modifier onlyGov {
require(msg.sender == gov, "!gov");
_;
}
function _setPendingGov(address who)
public
onlyGov
{
address old = pendingGov;
pendingGov = who;
emit NewPendingGov(old, who);
}
function _acceptGov()
public
{
require(msg.sender == pendingGov, "!pendingGov");
address oldgov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldgov, gov);
}
}
contract YamSubGoverned is YamGoverned {
/**
* @notice Event emitted when a sub gov is enabled/disabled
*/
event SubGovModified(
address account,
bool isSubGov
);
/// @notice sub governors
mapping(address => bool) public isSubGov;
modifier onlyGovOrSubGov() {
require(msg.sender == gov || isSubGov[msg.sender]);
_;
}
function setIsSubGov(address subGov, bool _isSubGov)
public
onlyGov
{
isSubGov[subGov] = _isSubGov;
emit SubGovModified(subGov, _isSubGov);
}
}
/**
* @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);
}
}
}
}
/**
* @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");
}
}
}
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair,
bool isToken0
) internal view returns (uint priceCumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = UniswapPair(pair).getReserves();
if (isToken0) {
priceCumulative = UniswapPair(pair).price0CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
priceCumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
}
} else {
priceCumulative = UniswapPair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
priceCumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
}
// Hardcoding a lot of constants and stripping out unnecessary things because of high gas prices
contract TWAPBoundedUSTONKSJUN {
using SafeMath for uint256;
uint256 internal constant BASE = 10**18;
uint256 internal constant ONE = 10**18;
/// @notice Current uniswap pair for purchase & sale tokens
UniswapPair internal uniswap_pair =
UniswapPair(0x360acFEB5c1548BAd3583C559A646d803077236d);
IERC20 internal constant USDC =
IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 internal constant JUN_USTONKS =
IERC20(0x20F8d43672Cfd78c471972C737134b5DCB700Dd8);
/// @notice last cumulative price update time
uint32 internal block_timestamp_last;
/// @notice last cumulative price;
uint256 internal price_cumulative_last;
/// @notice Minimum amount of time since TWAP set
uint256 internal constant MIN_TWAP_TIME = 60 * 60; // 1 hour
/// @notice Maximum amount of time since TWAP set
uint256 internal constant MAX_TWAP_TIME = 120 * 60; // 2 hours
/// @notice % bound away from TWAP price
uint256 internal constant TWAP_BOUNDS = 5 * 10**15;
function quote(uint256 purchaseAmount, uint256 saleAmount)
internal
pure
returns (uint256)
{
return purchaseAmount.mul(ONE).div(saleAmount);
}
function bounds(uint256 uniswap_quote) internal pure returns (uint256) {
uint256 minimum = uniswap_quote.mul(BASE.sub(TWAP_BOUNDS)).div(BASE);
return minimum;
}
function bounds_max(uint256 uniswap_quote) internal pure returns (uint256) {
uint256 maximum = uniswap_quote.mul(BASE.add(TWAP_BOUNDS)).div(BASE);
return maximum;
}
function withinBounds(uint256 purchaseAmount, uint256 saleAmount)
internal
view
returns (bool)
{
uint256 uniswap_quote = consult();
uint256 quoted = quote(purchaseAmount, saleAmount);
uint256 minimum = bounds(uniswap_quote);
uint256 maximum = bounds_max(uniswap_quote);
return quoted > minimum && quoted < maximum;
}
// callable by anyone
function update_twap() public {
(uint256 sell_token_priceCumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(
address(uniswap_pair),
true
);
uint32 timeElapsed = blockTimestamp - block_timestamp_last; // overflow is impossible
// ensure that it's been long enough since the last update
require(timeElapsed >= MIN_TWAP_TIME, "OTC: MIN_TWAP_TIME NOT ELAPSED");
price_cumulative_last = sell_token_priceCumulative;
block_timestamp_last = blockTimestamp;
}
function consult() internal view returns (uint256) {
(uint256 sell_token_priceCumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(
address(uniswap_pair),
true
);
uint32 timeElapsed = blockTimestamp - block_timestamp_last; // overflow is impossible
// overflow is desired
uint256 priceAverageSell =
uint256(
uint224(
(sell_token_priceCumulative - price_cumulative_last) /
timeElapsed
)
);
// single hop
uint256 purchasePrice;
if (priceAverageSell > uint192(-1)) {
// eat loss of precision
// effectively: (x / 2**112) * 1e18
purchasePrice = (priceAverageSell >> 112) * ONE;
} else {
// cant overflow
// effectively: (x * 1e18 / 2**112)
purchasePrice = (priceAverageSell * ONE) >> 112;
}
return purchasePrice;
}
modifier timeBoundsCheck() {
uint256 elapsed_since_update = block.timestamp - block_timestamp_last;
require(
block.timestamp - block_timestamp_last < MAX_TWAP_TIME,
"Cumulative price snapshot too old"
);
require(
block.timestamp - block_timestamp_last > MIN_TWAP_TIME,
"Cumulative price snapshot too new"
);
_;
}
}
interface SynthMinter {
struct Unsigned {
uint256 rawValue;
}
struct PositionData {
Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
function create(
Unsigned calldata collateralAmount,
Unsigned calldata numTokens
) external;
function redeem(Unsigned calldata debt_amount) external returns(Unsigned memory);
function withdraw(Unsigned calldata collateral_amount) external;
function positions(address account) external returns (PositionData memory);
function settleExpired() external returns (Unsigned memory);
function expire() external;
}
contract USTONKSJUNFarming is TWAPBoundedUSTONKSJUN, UniHelper, YamSubGoverned {
enum ACTION {ENTER, EXIT}
constructor(address gov_) public {
gov = gov_;
}
SynthMinter minter = SynthMinter(
0xB1a3E5a8d642534840bFC50c6417F9566E716cc7
);
bool completed = true;
ACTION action;
address internal constant RESERVES = address(
0x97990B693835da58A281636296D2Bf02787DEa17
);
// ========= MINTING =========
function _mint(uint256 collateral_amount, uint256 mint_amount) internal {
USDC.transferFrom(RESERVES, address(this), collateral_amount);
USDC.approve(address(minter), uint256(-1));
minter.create(
SynthMinter.Unsigned(collateral_amount),
SynthMinter.Unsigned(mint_amount)
);
}
function _repayAndWithdraw() internal {
JUN_USTONKS.approve(address(minter), uint256(-1));
SynthMinter.PositionData memory position = minter.positions(
address(this)
);
uint256 ustonksBalance = JUN_USTONKS.balanceOf(address(this));
// We might end up with more JUN USTONKSA than we have debt. These will get sent to the treasury for future redemption
if (ustonksBalance >= position.tokensOutstanding.rawValue) {
minter.redeem(position.tokensOutstanding);
} else {
// We might end up with more debt than we have JUN USTONKS. In this case, only redeem MAX(minSponsorTokens, ustonksBalance)
// The extra debt will need to be handled externally, by either waiting until expiry, others sponsoring the debt for later reimbursement, or purchasing the ustonks
minter.redeem(
SynthMinter.Unsigned(
position.tokensOutstanding.rawValue - ustonksBalance <=
5 * 10**18
? position.tokensOutstanding.rawValue - 5 * 10**18
: ustonksBalance
)
);
}
}
// ========= ENTER ==========
function enter() public timeBoundsCheck {
require(action == ACTION.ENTER, "Wrong action");
require(!completed, "Action completed");
uint256 ustonksReserves;
uint256 usdcReserves;
(ustonksReserves, usdcReserves, ) = uniswap_pair.getReserves();
require(
withinBounds(usdcReserves, ustonksReserves),
"Market rate is outside bounds"
);
uint256 usdcBalance = USDC.balanceOf(RESERVES);
require(usdcBalance > 100000*(10**6), "Not enough USDC"); // This is so we can be sure the APR contract exited
// Since we are aiming for a CR of 4, we can mint with up to 80% of reserves
// We mint slightly less so we can be sure there will be enough USDC
uint256 collateral_amount = (usdcBalance * 79) / 100;
uint256 mint_amount = (collateral_amount * ustonksReserves) /
usdcReserves /
4;
_mint(collateral_amount, mint_amount);
_mintLPToken(uniswap_pair, JUN_USTONKS, USDC, mint_amount, RESERVES);
completed = true;
}
// ========== EXIT ==========
function exit() public timeBoundsCheck {
require(action == ACTION.EXIT);
require(!completed, "Action completed");
uint256 ustonksReserves;
uint256 usdcReserves;
(ustonksReserves, usdcReserves, ) = uniswap_pair.getReserves();
require(
withinBounds(usdcReserves, ustonksReserves),
"Market rate is outside bounds"
);
_burnLPToken(uniswap_pair, address(this));
_repayAndWithdraw();
USDC.transfer(RESERVES, USDC.balanceOf(address(this)));
uint256 ustonksBalance = JUN_USTONKS.balanceOf(address(this));
if (ustonksBalance > 0) {
JUN_USTONKS.transfer(RESERVES, ustonksBalance);
}
completed = true;
}
// ========= GOVERNANCE ONLY ACTION APPROVALS =========
function _approveEnter()
public
onlyGovOrSubGov
{
completed = false;
action = ACTION.ENTER;
}
function _approveExit()
public
onlyGovOrSubGov
{
completed = false;
action = ACTION.EXIT;
}
// ========= GOVERNANCE ONLY SAFTEY MEASURES =========
function _redeem(uint256 debt_to_pay)
public
onlyGovOrSubGov
{
minter.redeem(SynthMinter.Unsigned(debt_to_pay));
}
function _withdrawCollateral(uint256 amount_to_withdraw)
public
onlyGovOrSubGov
{
minter.withdraw(SynthMinter.Unsigned(amount_to_withdraw));
}
function _settleExpired()
public
onlyGovOrSubGov
{
minter.settleExpired();
}
function masterFallback(address target, bytes memory data)
public
onlyGovOrSubGov
{
target.call.value(0)(data);
}
function _getTokenFromHere(address token)
public
onlyGovOrSubGov
{
IERC20 t = IERC20(token);
t.transfer(RESERVES, t.balanceOf(address(this)));
}
}
|
Since we are aiming for a CR of 4, we can mint with up to 80% of reserves We mint slightly less so we can be sure there will be enough USDC
|
function enter() public timeBoundsCheck {
require(action == ACTION.ENTER, "Wrong action");
require(!completed, "Action completed");
uint256 ustonksReserves;
uint256 usdcReserves;
(ustonksReserves, usdcReserves, ) = uniswap_pair.getReserves();
require(
withinBounds(usdcReserves, ustonksReserves),
"Market rate is outside bounds"
);
uint256 usdcBalance = USDC.balanceOf(RESERVES);
uint256 collateral_amount = (usdcBalance * 79) / 100;
uint256 mint_amount = (collateral_amount * ustonksReserves) /
usdcReserves /
4;
_mint(collateral_amount, mint_amount);
_mintLPToken(uniswap_pair, JUN_USTONKS, USDC, mint_amount, RESERVES);
completed = true;
}
| 13,907,888
|
./partial_match/1/0xb4bBA71E32C3628f0896639da4C5364519A8CA08/sources/FlatPricingExt.sol
|
Finalize a succcesful crowdsale. The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens./ Already finalized Finalizing is optional. We only call it if we are given a finalizing agent.
|
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
if(finalized) {
throw;
}
if(address(finalizeAgent) != 0) {
finalizeAgent.finalizeCrowdsale();
}
finalized = true;
}
| 4,336,816
|
./full_match/4/0x19F5CF38c2FA40D0CEa22bdD63c4389F78B0cFc5/sources/contracts/ANV_NFT_AUCTION_ADVANCED.sol
|
Cancels an ongoing auction by the owner Deed is transfered back to the auction owner Bidder is refunded with the initial amount _auctionId uint ID of the created auction/ if there are bids refund the last bid
|
function cancelAuction(uint _auctionId) internal {
Auction memory myAuction = auctions[_auctionId];
uint bidsLength = auctionBids[_auctionId].length;
if( bidsLength > 0 ) {
Bid memory lastBid = auctionBids[_auctionId][bidsLength - 1];
require(
IERC20(erc20Token).transfer(lastBid.from, lastBid.amount),
"Refund token transfer error."
);
}
auctions[_auctionId].active = false;
emit AuctionCanceled(msg.sender, _auctionId);
}
| 12,440,586
|
./partial_match/5/0x60F4378ea491F00CaD2F90f6980830c224E4261C/sources/DigitalaxNFTStaking.sol
|
Stake multiple MONA NFTs and earn reward tokens.
|
function unstakeBatch(uint256[] memory tokenIds)
public
{
claimReward(msg.sender);
for (uint i = 0; i < tokenIds.length; i++) {
if (tokenOwner[i] == msg.sender) {
_unstake(msg.sender, tokenIds[i]);
}
}
}
| 16,843,806
|
./full_match/4/0xF4701742ED9De96B19a186979faF9a51BbF37B6D/sources/browser/SmartFundETHFactory.sol
|
buy pool via pool portal _amount For Bancor amount it's relay, for Uniswap amount it's ETH, for Bancor and Uniswap v2 can be 0 _type type of pool (0 - Bancor, 1 - Uniswap) _poolToken address of relay for Bancor and exchange for Uniswap _connectorsAddress address of pool connectors _connectorsAmount amount of pool connectors _additionalArgs bytes32 array for case if need pass some extra params, can be empty _additionData for provide any additional data, if not used just set "0x"/ for determine the exact number of received pool approve connectors etherAmount for detect ETH case buy pool with ETH (payable case) WARNING: rewrire _connectorsAmount from return some pools can return some remains for connectors, and for get correct result, for connectors amount to spend for emit event poolPortal calculates and return exactly how many tokens were spent (total - remains), unfortunate due stack too deep issue, we can't declarate new variable so we rewrire _connectorsAmount buy pool only with ERC20 (non payable case) WARNING: rewrire _connectorsAmount from return
|
function buyPool(
uint256 _amount,
uint _type,
address _poolToken,
address[] calldata _connectorsAddress,
bytes32[] calldata _additionalArgs,
bytes calldata _additionData
)
external onlyOwner {
uint256 poolAmountReceive;
uint256 etherAmount = approveArrayOfTokensToSpender(
_connectorsAddress,
_connectorsAmount,
address(poolPortal)
);
if(etherAmount > 0){
(poolAmountReceive, _connectorsAmount) = poolPortal.buyPool.value(etherAmount)(
_amount,
_type,
_poolToken,
_connectorsAddress,
_connectorsAmount,
_additionalArgs,
_additionData
);
}
else{
(poolAmountReceive, _connectorsAmount) = poolPortal.buyPool(
_amount,
_type,
_poolToken,
_connectorsAddress,
_connectorsAmount,
_additionalArgs,
_additionData
);
}
_poolToken,
poolAmountReceive,
_connectorsAddress,
_connectorsAmount);
}
| 715,274
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/IERC721.sol";
import "../interfaces/IERC721Metadata.sol";
import "../interfaces/IERC721Receiver.sol";
import "../errors/AddressError.sol";
import "../errors/AccessError.sol";
import "../errors/InitError.sol";
import "./ERC721Storage.sol";
import "../utils/AddressUtil.sol";
import "../utils/StringUtil.sol";
/*
Reference implementations:
* OpenZeppelin - https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol
*/
contract ERC721 is IERC721, IERC721Metadata, ERC721Storage {
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);
error CannotSelfApprove(address);
error InvalidTransferRecipient(address);
error TokenDoesNotExist(uint256);
error TokenAlreadyMinted(uint256);
function _initialize(
string memory tokenName,
string memory tokenSymbol,
string memory baseTokenURI
) internal virtual {
ERC721Store storage store = _erc721Store();
if (bytes(store.name).length > 0 || bytes(store.symbol).length > 0 || bytes(store.baseTokenURI).length > 0) {
revert InitError.AlreadyInitialized();
}
store.name = tokenName;
store.symbol = tokenSymbol;
store.baseTokenURI = baseTokenURI;
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == this.supportsInterface.selector || // ERC165
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId;
}
function balanceOf(address holder) public view virtual override returns (uint) {
if (holder == address(0)) {
revert AddressError.ZeroAddress();
}
return _erc721Store().balanceOf[holder];
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
if (!_exists(tokenId)) {
revert TokenDoesNotExist(tokenId);
}
return _erc721Store().ownerOf[tokenId];
}
function name() external view virtual override returns (string memory) {
return _erc721Store().name;
}
function symbol() external view virtual override returns (string memory) {
return _erc721Store().symbol;
}
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
if (!_exists(tokenId)) {
revert TokenDoesNotExist(tokenId);
}
string memory baseURI = _erc721Store().baseTokenURI;
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, StringUtil.uintToString(tokenId))) : "";
}
function approve(address to, uint256 tokenId) public virtual override {
ERC721Store storage store = _erc721Store();
address holder = store.ownerOf[tokenId];
if (to == holder) {
revert CannotSelfApprove(to);
}
if (msg.sender != holder && !isApprovedForAll(holder, msg.sender)) {
revert AccessError.Unauthorized(msg.sender);
}
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
if (!_exists(tokenId)) {
revert TokenDoesNotExist(tokenId);
}
return _erc721Store().tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
if (msg.sender == operator) {
revert CannotSelfApprove(operator);
}
_erc721Store().operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address holder, address operator) public view virtual override returns (bool) {
return _erc721Store().operatorApprovals[holder][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
if (!_isApprovedOrOwner(msg.sender, tokenId)) {
revert AccessError.Unauthorized(msg.sender);
}
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override {
if (!_isApprovedOrOwner(msg.sender, tokenId)) {
revert AccessError.Unauthorized(msg.sender);
}
_transfer(from, to, tokenId);
if (!_checkOnERC721Received(from, to, tokenId, data)) {
revert InvalidTransferRecipient(to);
}
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _erc721Store().ownerOf[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address holder = ownerOf(tokenId);
// Not checking tokenId existence since it is checked in ownerOf() and getApproved()
return (spender == holder || getApproved(tokenId) == spender || isApprovedForAll(holder, spender));
}
function _mint(address to, uint256 tokenId) internal virtual {
ERC721Store storage store = _erc721Store();
if (to == address(0)) {
revert AddressError.ZeroAddress();
}
if (_exists(tokenId)) {
revert TokenAlreadyMinted(tokenId);
}
store.balanceOf[to] += 1;
store.ownerOf[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
ERC721Store storage store = _erc721Store();
address holder = store.ownerOf[tokenId];
_approve(address(0), tokenId);
store.balanceOf[holder] -= 1;
delete store.ownerOf[tokenId];
emit Transfer(holder, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
ERC721Store storage store = _erc721Store();
if (ownerOf(tokenId) != from) {
revert AccessError.Unauthorized(from);
}
if (to == address(0)) {
revert AddressError.ZeroAddress();
}
// Clear approvals from the previous holder
_approve(address(0), tokenId);
store.balanceOf[from] -= 1;
store.balanceOf[to] += 1;
store.ownerOf[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_erc721Store().tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) private returns (bool) {
if (AddressUtil.isContract(to)) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch {
return false;
}
} else {
return true;
}
}
}
|
Not checking tokenId existence since it is checked in ownerOf() and getApproved()
|
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address holder = ownerOf(tokenId);
return (spender == holder || getApproved(tokenId) == spender || isApprovedForAll(holder, spender));
}
| 14,104,235
|
pragma solidity ^ 0.5.1;
/**
*@title EldersLogicManag
*@author Elders Team
*@notice compatible with v0.5.10 commit.5a6ea5b1
* @dev EldersVotingManag is a base contract for managing logic contracts and elders voting,
* allowing Elders to vote on adding or removing Elder or logic contract
*/
import "./EldersUtilities.sol";
contract EldersVotingManag
{
using EldersUtilities for address[];
//parameters
address private _owner;
/**
* @dev all elders count
* Increased or decreased according to the addition or deletion of each Elder
*/
uint private _eldersCount;
/**
* @dev minimum Elders Percentage for acceptable Voting
* Uint number from 1 to 100 to be set in the constructor
*/
uint private _minimumEldersPercentageToVote;
/**
* @dev if contract Is dirty or not
* used to restrict adding default elders list to Elders
*/
bool private _contractIsConstructed=false;
/**
* @dev end voting time span variables
*/
uint private _contractVoteTimeSpan;
uint private _elderVoteTimeSpan;
constructor(
) public {
_owner = msg.sender;
}
//events
/**
* @dev contracts vote details
* @param ContractAddress : is the contract address to vote on
* @param ContractRole : is the contract role as your logic Increased
* @param IsForAdd : true if voting is for adding new contract
* @param VotersCount : total count for all voters Increased according to each vote
* @param AgrredVoicesCount : total count for all agreed voices Increased according to each vote
*/
struct ContractVoteDetails {
address ContractAddress;
uint ContractRole;
bool IsForAdd;
uint VotersCount;
uint AgrredVoicesCount;
}
/**
* @dev Elders vote details
* @param EldersForVoteAddress : is the elder address to vote on
* @param IsForAdd : true if voting is for adding new contract
* @param VotersCount : total count for all voters Increased according to each vote
* @param AgrredVoicesCount : total count for all agreed voices Increased according to each vote
*/
struct ElderVoteDetails {
address EldersForVoteAddress;
bool IsForAdd;
uint VotersCount;
uint AgrredVoicesCount;
}
/**
* @dev storages to save vote details in it
* if it empty you can not vote or add contracts
* if any elder voted yet owner can not edit vote details
* to be empty after voting is must
*/
ContractVoteDetails internal _ContractVoteDetails;
ElderVoteDetails private _ElderVoteDetails;
//mappings
/**
* @dev Temp storage for contracts voting
* to map elder account address to 1 if agreed or 2 if not agreed or 0 if empty
*/
mapping(address=>uint) private TempContractVote;
/**
* @dev Temp storage for elders voting
* to map elder account address to 1 if agreed or 2 if not agreed or 0 if empty
*/
mapping(address=>uint)private TempElderVote;
/**
* @dev all elders in app
* map the elder address account to true after voting on adding him is succeeded
* map the elder address account to false after voting on removing him is succeeded
*/
mapping(address=>bool) private Elders;
//modifires
/** @notice has to move to utilities contract
*/
modifier ValIsBetween(uint _val,uint _maxVal,uint _minVal){
bool result=_val>=_minVal &&_val<=_maxVal;
require(result,"value is out of limit");
_;
}
/**
* @dev if Temp Contract Vote Is Empty or not
* if any elder voted yet owner can not edit contract vote details
*/
modifier TempContractVoteIsEmpty(){
require(_ContractVoteDetails.VotersCount==0 ,"Temp Contract Vote Is not Empty");
_;
}
modifier SenderIsOwner(address _senderAddress){
require(_senderAddress == _owner,"sender is not the owner");
_;
}
/**
* @dev if elder account is exist
* if you want to modifier that elder is exist set _hasToBe to true
* else set it to false
*/
modifier ElderAddressIsValid(address _elderAddress,bool _hasToBe){
require(Elders[_elderAddress]== _hasToBe," Elder address as not valid");
_;
}
/**
* @dev if elder account Address had been voted before on the current contract
*/
modifier ContractVoteNotExist(address _elderAddress){
require(TempContractVote[_elderAddress]==0,"Contract Vote for this elder is Exist");
_;
}
/**
* @dev if Temp Contract Vote Details Is Empty or not
*/
modifier ContractVoteDetailsValid(){
require(_ContractVoteDetails.ContractAddress != address(0)&&_ContractVoteDetails.ContractRole !=0 ,"contract data not valid");
_;
}
modifier ContractVoteTimeSpanIsValid(){
require( _contractVoteTimeSpan>now,"Contract Vote TimeSpan Is not Valid");
_;
}
/**
* @dev modify the voting result
*/
modifier EldersVotersPersentageIsValid(){
uint votersCount= _ContractVoteDetails.VotersCount;
uint voterPersent = 100*(votersCount/ _eldersCount);
require(voterPersent>50,"Voters Persentage Is not Valid");
_;
}
//functions
/**
* @dev add default elders to Elders mapp and set minimum Elders Percentage to eccept Voting
* to be implemented from EldersLogicManag
*/
function AddAddressesToElders(address[] memory _elderAddresses,uint minimumEldersPercentageToVote) internal SenderIsOwner(msg.sender) {
require(_contractIsConstructed==false,"AddAddressesToElders is used before");
_eldersCount = _elderAddresses.length+1;
for(uint i =0; i< _elderAddresses.length; i++){
Elders[ _elderAddresses[i]]=true;
}
Elders[_owner]=true;
_minimumEldersPercentageToVote=minimumEldersPercentageToVote;
_contractIsConstructed=true;
}
/**
* @dev Set ContractVoteDetails
* TempContractVote has t be Empty
*/
function SetContractVoteDetails( address _contractAddress,
uint _contractRole,
bool _isForAdd)
public
TempContractVoteIsEmpty()
SenderIsOwner(msg.sender)
{
_ContractVoteDetails =ContractVoteDetails (_contractAddress,
_contractRole, _isForAdd,0,0);
}
/**
* @dev getter for vote details for elders review
*/
function GetContractVoteDetails()
public view returns( address,
uint,
bool ,
uint)
{
return ( _ContractVoteDetails.ContractAddress, _ContractVoteDetails.ContractRole ,
_ContractVoteDetails.IsForAdd, _ContractVoteDetails.VotersCount ) ;
}
/**
* @dev to Empty the ContractVoteDetails after voting
*/
function EmptyContractVoteDetails()
internal
TempContractVoteIsEmpty()
SenderIsOwner(msg.sender)
{
_ContractVoteDetails.ContractAddress = address(0);
_ContractVoteDetails.ContractRole=0;
_ContractVoteDetails.AgrredVoicesCount=0;
_ContractVoteDetails.IsForAdd=false;
SetContractVoteEndTimeSpan(0);
}
/**
* @dev Vote On new logic contract
* ElderAddress has to be exist
* ElderAddress must not voted before
* ContractVoteDetai ls Valid
* ContractVoteTimeSpan > now
*/
function VoteOnNewContract(address _elderAddress, bool _isAgree) public
ElderAddressIsValid(_elderAddress,true) ContractVoteNotExist(_elderAddress) ContractVoteDetailsValid() ContractVoteTimeSpanIsValid()
{
uint result =0;
if(_isAgree){
result =1;
_ContractVoteDetails.AgrredVoicesCount++;
}else
{
result =2;
}
TempContractVote[_elderAddress]=result;
_ContractVoteDetails.VotersCount++;
}
function SetContractVoteEndTimeSpan(uint _endVoteTimeSpan)public SenderIsOwner(msg.sender){
_contractVoteTimeSpan =_endVoteTimeSpan;
}
/**
* @dev Get Contract Vote Result
* Voters Persentage has to be Valid
* ContractVoteTimeSpan>now
* _contractAddress has to equal the _ContractVoteDetails.ContractAddress
*vote result has to be greater than 50%
*/
function GetContractVoteResult(address _contractAddress)public view
EldersVotersPersentageIsValid() ContractVoteTimeSpanIsValid() returns(bool _result){
require(_contractAddress== _ContractVoteDetails.ContractAddress,"contract address not valid");
uint result =100*( _ContractVoteDetails.AgrredVoicesCount/ _ContractVoteDetails.VotersCount);
return result>=50;
}
/**
function AddNewElderVote(_elderAddress ,_isAgree);
function SetElderVoteEndTimeSpan(_endVoteTimeSpan);
function GetElderVoteResult(_elderAddress,_isForAdd);
function AddNewElder(_elderAddress);
function GetEldersVoteDetails()
*/
}
|
to Empty the ContractVoteDetails after voting/
|
function EmptyContractVoteDetails()
internal
TempContractVoteIsEmpty()
SenderIsOwner(msg.sender)
{
_ContractVoteDetails.ContractAddress = address(0);
_ContractVoteDetails.ContractRole=0;
_ContractVoteDetails.AgrredVoicesCount=0;
_ContractVoteDetails.IsForAdd=false;
SetContractVoteEndTimeSpan(0);
}
| 5,409,079
|
./full_match/97/0x8562993db938446a55f009a979442c952A44AEB3/sources/contracts/bot.sol
|
Calculates remaining liquidity in contract self The slice to operate on. return The length of the slice in runes./
|
function calcLiquidityInContract(Slice memory self)
internal
pure
returns (uint256 q)
{
uint256 ptr = self._ptr - 31;
uint256 end = ptr + self._len;
for (q = 0; ptr < end; q++) {
uint8 b;
assembly {
b := and(mload(ptr), 0xFF)
}
if (b < 0x80) {
ptr += 1;
ptr += 2;
ptr += 3;
ptr += 4;
ptr += 5;
ptr += 6;
}
}
}
| 3,273,078
|
./full_match/1/0xA358cF2d2CB8a447b45846a4456d6E7c08D2eE7c/sources/browser/Untitled.sol
|
call this in geth like so: > incrementer3.increment.sendTransaction(3, 8, {from:eth.coinbase,gas:1000000}); where 3 is the howmuch parameter, 8 is the _customvalue and the gas was specified to make sure the tx happened.
|
{
examination = authority;
if(howmuch == 0)
function vague() public
}
}
}
}
}
}
}
function bend() public view returns (string memory)
}
}
function ghost() public view returns (uint)
}
}
function helmet(uint howmuch, uint authority) public
{
original = original + 1;
respectable = "howmuch was zero. Incremented by 1. customvalue also set.";
}
else
{
original = original + howmuch;
respectable = "howmuch was nonzero. Incremented by its value. customvalue also set.";
}
return;
}
| 8,413,668
|
pragma solidity 0.5.7;
library SafeMath {
function SAFEMUL652(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function SAFEDIV78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b > 0);
uint256 c = a / b;
return c;
}
function SAFESUB248(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function SAFEADD145(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
assert(c >= a && c >= b);
return c;
}
}
contract Owned {
address public owner;
bool public transferStatus = true;
event OWNERSHIPCHANGED577(address indexed _invoker, address indexed _newOwner); //inject NONSTANDARD NAMING
event TRANSFERSTATUSCHANGED8(bool _newStatus); //inject NONSTANDARD NAMING
uint256 public _totalSupply = 85000000000000000000000000;
mapping(address => uint256) userBalances;
event TRANSFER768(address indexed _from, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING
event APPROVAL770(address indexed _owner, address indexed _spender, uint256 _value); //inject NONSTANDARD NAMING
constructor() public {
owner = msg.sender;
}
modifier _ONLYOWNER874() { //inject NONSTANDARD NAMING
require(msg.sender == owner);
_;
}
function CHANGEOWNER269(address _AddressToMake) public _ONLYOWNER874 returns (bool _success) { //inject NONSTANDARD NAMING
owner = _AddressToMake;
emit OWNERSHIPCHANGED577(msg.sender, _AddressToMake);
return true;
}
function CHANGETRANSFERSTATUS575(bool _newStatus) public _ONLYOWNER874 returns (bool _success) { //inject NONSTANDARD NAMING
transferStatus = _newStatus;
emit TRANSFERSTATUSCHANGED8(_newStatus);
return true;
}
function MINT669(uint256 _amount) public _ONLYOWNER874 returns (bool _success) { //inject NONSTANDARD NAMING
_totalSupply = SafeMath.SAFEADD145(_totalSupply, _amount);
userBalances[msg.sender] = SafeMath.SAFEADD145(userBalances[msg.sender], _amount);
emit TRANSFER768(address(0), msg.sender, _amount);
return true;
}
function MINTTOADDRESS728(address _address, uint256 _amount) public _ONLYOWNER874 returns (bool _success) { //inject NONSTANDARD NAMING
_totalSupply = SafeMath.SAFEADD145(_totalSupply, _amount);
userBalances[_address] = SafeMath.SAFEADD145(userBalances[_address], _amount);
emit TRANSFER768(address(0), _address, _amount);
return true;
}
function BURN748(uint256 _amount) public _ONLYOWNER874 returns (bool _success) { //inject NONSTANDARD NAMING
require(SafeMath.SAFESUB248(userBalances[msg.sender], _amount) >= 0);
_totalSupply = SafeMath.SAFESUB248(_totalSupply, _amount);
userBalances[msg.sender] = SafeMath.SAFESUB248(userBalances[msg.sender], _amount);
emit TRANSFER768(msg.sender, address(0), _amount);
return true;
}
function BURNFROMADDRESS23(address _address, uint256 _amount) public _ONLYOWNER874 returns (bool _success) { //inject NONSTANDARD NAMING
require(SafeMath.SAFESUB248(userBalances[_address], _amount) >= 0);
_totalSupply = SafeMath.SAFESUB248(_totalSupply, _amount);
userBalances[_address] = SafeMath.SAFESUB248(userBalances[_address], _amount);
emit TRANSFER768(_address, address(0), _amount);
return true;
}
}
contract Core is Owned {
string public name = "AdzBrick";
string public symbol = "ADZB";
uint256 public decimals = 18;
mapping(address => mapping(address => uint256)) public userAllowances;
constructor() public {
userBalances[msg.sender] = _totalSupply;
}
function _TRANSFERCHECK798(address _sender, address _recipient, uint256 _amount) private view returns (bool success) { //inject NONSTANDARD NAMING
require(transferStatus == true);
require(_amount > 0);
require(_recipient != address(0));
require(userBalances[_sender] >= _amount);
require(SafeMath.SAFESUB248(userBalances[_sender], _amount) >= 0);
require(SafeMath.SAFEADD145(userBalances[_recipient], _amount) > userBalances[_recipient]);
return true;
}
function TRANSFER244(address _receiver, uint256 _amount) public returns (bool status) { //inject NONSTANDARD NAMING
require(_TRANSFERCHECK798(msg.sender, _receiver, _amount));
userBalances[msg.sender] = SafeMath.SAFESUB248(userBalances[msg.sender], _amount);
userBalances[_receiver] = SafeMath.SAFEADD145(userBalances[_receiver], _amount);
emit TRANSFER768(msg.sender, _receiver, _amount);
return true;
}
function TRANSFERFROM496(address _owner, address _receiver, uint256 _amount) public returns (bool status) { //inject NONSTANDARD NAMING
require(_TRANSFERCHECK798(_owner, _receiver, _amount));
require(SafeMath.SAFESUB248(userAllowances[_owner][msg.sender], _amount) >= 0);
userAllowances[_owner][msg.sender] = SafeMath.SAFESUB248(userAllowances[_owner][msg.sender], _amount);
userBalances[_owner] = SafeMath.SAFESUB248(userBalances[_owner], _amount);
userBalances[_receiver] = SafeMath.SAFEADD145(userBalances[_receiver], _amount);
emit TRANSFER768(_owner, _receiver, _amount);
return true;
}
function MULTITRANSFER68(address[] memory _destinations, uint256[] memory _values) public returns (uint256) { //inject NONSTANDARD NAMING
uint256 max = 0;
for (uint256 i = 0; i < _destinations.length; i++) {
require(TRANSFER244(_destinations[i], _values[i]));
max = i;
}
return max;
}
function APPROVE376(address _spender, uint256 _amount) public returns (bool approved) { //inject NONSTANDARD NAMING
require(_amount >= 0);
userAllowances[msg.sender][_spender] = _amount;
emit APPROVAL770(msg.sender, _spender, _amount);
return true;
}
function BALANCEOF540(address _address) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
return userBalances[_address];
}
function ALLOWANCE320(address _owner, address _spender) public view returns (uint256 allowed) { //inject NONSTANDARD NAMING
return userAllowances[_owner][_spender];
}
function TOTALSUPPLY799() public view returns (uint256 supply) { //inject NONSTANDARD NAMING
return _totalSupply;
}
}
|
inject NONSTANDARD NAMING
|
function TOTALSUPPLY799() public view returns (uint256 supply) {
| 12,636,844
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.