file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
pragma solidity ^0.4.13;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Math
* @dev Assorted math operations
*/
contract Math {
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract 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;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is SafeMath, ERC20Basic {
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) returns (bool){
balances[msg.sender] = sub(balances[msg.sender],_value);
balances[_to] = add(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = add(balances[_to],_value);
balances[_from] = sub(balances[_from],_value);
allowed[_from][msg.sender] = sub(_allowance,_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @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 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
totalSupply = add(totalSupply,_amount);
balances[_to] = add(balances[_to],_amount);
Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused {
paused = false;
Unpause();
}
}
/**
* Pausable token
*
* Simple ERC20 Token example, with pausable token creation
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
/**
* @title LimitedTransferToken
* @dev LimitedTransferToken defines the generic interface and the implementation to limit token
* transferability for different events. It is intended to be used as a base class for other token
* contracts.
* LimitedTransferToken has been designed to allow for different limiting factors,
* this can be achieved by recursively calling super.transferableTokens() until the base class is
* hit. For example:
* function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
* return min256(unlockedTokens, super.transferableTokens(holder, time));
* }
* A working example is VestedToken.sol:
* https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol
*/
contract LimitedTransferToken is ERC20 {
/**
* @dev Checks whether it can transfer or otherwise throws.
*/
modifier canTransfer(address _sender, uint256 _value) {
require(_value <= transferableTokens(_sender, uint64(now)));
_;
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _to The address that will recieve the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _from The address that will send the tokens.
* @param _to The address that will recieve the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Default transferable tokens function returns all tokens for a holder (no limit).
* @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the
* specific logic for limiting token transferability for a holder over time.
*/
function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
return balanceOf(holder);
}
}
/**
* @title Vested token
* @dev Tokens that can be vested for a group of addresses.
*/
contract VestedToken is Math, StandardToken, LimitedTransferToken {
uint256 MAX_GRANTS_PER_ADDRESS = 20;
struct TokenGrant {
address granter; // 20 bytes
uint256 value; // 32 bytes
uint64 cliff;
uint64 vesting;
uint64 start; // 3 * 8 = 24 bytes
bool revokable;
bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes?
} // total 78 bytes = 3 sstore per operation (32 per sstore)
mapping (address => TokenGrant[]) public grants;
event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId);
/**
* @dev Grant tokens to a specified address
* @param _to address The address which the tokens will be granted to.
* @param _value uint256 The amount of tokens to be granted.
* @param _start uint64 Time of the beginning of the grant.
* @param _cliff uint64 Time of the cliff period.
* @param _vesting uint64 The vesting period.
*/
function grantVestedTokens(
address _to,
uint256 _value,
uint64 _start,
uint64 _cliff,
uint64 _vesting,
bool _revokable,
bool _burnsOnRevoke
) public {
// Check for date inconsistencies that may cause unexpected behavior
require(_cliff >= _start && _vesting >= _cliff);
require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting).
uint256 count = grants[_to].push(
TokenGrant(
_revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable
_value,
_cliff,
_vesting,
_start,
_revokable,
_burnsOnRevoke
)
);
transfer(_to, _value);
NewTokenGrant(msg.sender, _to, _value, count - 1);
}
/**
* @dev Revoke the grant of tokens of a specifed address.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
*/
function revokeTokenGrant(address _holder, uint256 _grantId) public {
TokenGrant storage grant = grants[_holder][_grantId];
require(grant.revokable);
require(grant.granter == msg.sender); // Only granter can revoke it
address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender;
uint256 nonVested = nonVestedTokens(grant, uint64(now));
// remove grant from array
delete grants[_holder][_grantId];
grants[_holder][_grantId] = grants[_holder][sub(grants[_holder].length,1)];
grants[_holder].length -= 1;
balances[receiver] = add(balances[receiver],nonVested);
balances[_holder] = sub(balances[_holder],nonVested);
Transfer(_holder, receiver, nonVested);
}
/**
* @dev Calculate the total amount of transferable tokens of a holder at a given time
* @param holder address The address of the holder
* @param time uint64 The specific time.
* @return An uint256 representing a holder's total amount of transferable tokens.
*/
function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
uint256 grantIndex = tokenGrantsCount(holder);
if (grantIndex == 0) return super.transferableTokens(holder, time); // shortcut for holder without grants
// Iterate through all the grants the holder has, and add all non-vested tokens
uint256 nonVested = 0;
for (uint256 i = 0; i < grantIndex; i++) {
nonVested = add(nonVested, nonVestedTokens(grants[holder][i], time));
}
// Balance - totalNonVested is the amount of tokens a holder can transfer at any given time
uint256 vestedTransferable = sub(balanceOf(holder), nonVested);
// Return the minimum of how many vested can transfer and other value
// in case there are other limiting transferability factors (default is balanceOf)
return min256(vestedTransferable, super.transferableTokens(holder, time));
}
/**
* @dev Check the amount of grants that an address has.
* @param _holder The holder of the grants.
* @return A uint256 representing the total amount of grants.
*/
function tokenGrantsCount(address _holder) constant returns (uint256 index) {
return grants[_holder].length;
}
/**
* @dev Calculate amount of vested tokens at a specifc time.
* @param tokens uint256 The amount of tokens grantted.
* @param time uint64 The time to be checked
* @param start uint64 A time representing the begining of the grant
* @param cliff uint64 The cliff period.
* @param vesting uint64 The vesting period.
* @return An uint256 representing the amount of vested tokensof a specif grant.
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |
* | . |
* +===+===========+---------+----------> time
* Start Clift Vesting
*/
function calculateVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vesting) constant returns (uint256)
{
// Shortcuts for before cliff and after vesting cases.
if (time < cliff) return 0;
if (time >= vesting) return tokens;
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can use just calculate a value
// in the vesting rect (as shown in above's figure)
// vestedTokens = tokens * (time - start) / (vesting - start)
uint256 vestedTokens = div(
mul(
tokens,
sub(time, start)
),
sub(vesting, start)
);
return vestedTokens;
}
/**
* @dev Get all information about a specifc grant.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
* @return Returns all the values that represent a TokenGrant(address, value, start, cliff,
* revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.
*/
function tokenGrant(address _holder, uint256 _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {
TokenGrant storage grant = grants[_holder][_grantId];
granter = grant.granter;
value = grant.value;
start = grant.start;
cliff = grant.cliff;
vesting = grant.vesting;
revokable = grant.revokable;
burnsOnRevoke = grant.burnsOnRevoke;
vested = vestedTokens(grant, uint64(now));
}
/**
* @dev Get the amount of vested tokens at a specific time.
* @param grant TokenGrant The grant to be checked.
* @param time The time to be checked
* @return An uint256 representing the amount of vested tokens of a specific grant at a specific time.
*/
function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
return calculateVestedTokens(
grant.value,
uint256(time),
uint256(grant.start),
uint256(grant.cliff),
uint256(grant.vesting)
);
}
/**
* @dev Calculate the amount of non vested tokens at a specific time.
* @param grant TokenGrant The grant to be checked.
* @param time uint64 The time to be checked
* @return An uint256 representing the amount of non vested tokens of a specifc grant on the
* passed time frame.
*/
function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
return sub(grant.value,vestedTokens(grant, time));
}
/**
* @dev Calculate the date when the holder can trasfer all its tokens
* @param holder address The address of the holder
* @return An uint256 representing the date of the last transferable tokens.
*/
function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) {
date = uint64(now);
uint256 grantIndex = grants[holder].length;
for (uint256 i = 0; i < grantIndex; i++) {
date = max64(grants[holder][i].vesting, date);
}
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is SafeMath, StandardToken {
event Burn(address indexed burner, uint indexed value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint _value)
public
{
require(_value > 0);
address burner = msg.sender;
balances[burner] = sub(balances[burner], _value);
totalSupply = sub(totalSupply, _value);
Burn(burner, _value);
}
}
/**
* @title PLC
* @dev PLC is ERC20 token contract, inheriting MintableToken, PausableToken,
* VestedToken, BurnableToken contract from open zeppelin.
*/
contract PLC is MintableToken, PausableToken, VestedToken, BurnableToken {
string public name = "PlusCoin";
string public symbol = "PLC";
uint256 public decimals = 18;
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable, SafeMath{
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
mapping (address => uint256) public refunded;
State public state;
address public devMultisig;
address[] public reserveWallet;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/**
* @dev This constructor sets the addresses of multi-signature wallet and
* 5 reserve wallets.
* and forwarding it if crowdsale is successful.
* @param _devMultiSig address The address of multi-signature wallet.
* @param _reserveWallet address[5] The addresses of reserve wallet.
*/
function RefundVault(address _devMultiSig, address[] _reserveWallet) {
state = State.Active;
devMultisig = _devMultiSig;
reserveWallet = _reserveWallet;
}
/**
* @dev This function is called when user buy tokens. Only RefundVault
* contract stores the Ether user sent which forwarded from crowdsale
* contract.
* @param investor address The address who buy the token from crowdsale.
*/
function deposit(address investor) onlyOwner payable {
require(state == State.Active);
deposited[investor] = add(deposited[investor], msg.value);
}
event Transferred(address _to, uint _value);
/**
* @dev This function is called when crowdsale is successfully finalized.
*/
function close() onlyOwner {
require(state == State.Active);
state = State.Closed;
uint256 balance = this.balance;
uint256 devAmount = div(balance, 10);
devMultisig.transfer(devAmount);
Transferred(devMultisig, devAmount);
uint256 reserveAmount = div(mul(balance, 9), 10);
uint256 reserveAmountForEach = div(reserveAmount, reserveWallet.length);
for(uint8 i = 0; i < reserveWallet.length; i++){
reserveWallet[i].transfer(reserveAmountForEach);
Transferred(reserveWallet[i], reserveAmountForEach);
}
Closed();
}
/**
* @dev This function is called when crowdsale is unsuccessfully finalized
* and refund is required.
*/
function enableRefunds() onlyOwner {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
/**
* @dev This function allows for user to refund Ether.
*/
function refund(address investor) returns (bool) {
require(state == State.Refunding);
if (refunded[investor] > 0) {
return false;
}
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
refunded[investor] = depositedValue;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
return true;
}
}
/**
* @title KYC
* @dev KYC contract handles the white list for PLCCrowdsale contract
* Only accounts registered in KYC contract can buy PLC token.
* Admins can register account, and the reason why
*/
contract KYC is Ownable, SafeMath, Pausable {
// check the address is registered for token sale
mapping (address => bool) public registeredAddress;
// check the address is admin of kyc contract
mapping (address => bool) public admin;
event Registered(address indexed _addr);
event Unregistered(address indexed _addr);
event NewAdmin(address indexed _addr);
/**
* @dev check whether the address is registered for token sale or not.
* @param _addr address
*/
modifier onlyRegistered(address _addr) {
require(isRegistered(_addr));
_;
}
/**
* @dev check whether the msg.sender is admin or not
*/
modifier onlyAdmin() {
require(admin[msg.sender]);
_;
}
function KYC() {
admin[msg.sender] = true;
}
/**
* @dev set new admin as admin of KYC contract
* @param _addr address The address to set as admin of KYC contract
*/
function setAdmin(address _addr)
public
onlyOwner
{
require(_addr != address(0) && admin[_addr] == false);
admin[_addr] = true;
NewAdmin(_addr);
}
/**
* @dev check the address is register for token sale
* @param _addr address The address to check whether register or not
*/
function isRegistered(address _addr)
public
constant
returns (bool)
{
return registeredAddress[_addr];
}
/**
* @dev register the address for token sale
* @param _addr address The address to register for token sale
*/
function register(address _addr)
public
onlyAdmin
whenNotPaused
{
require(_addr != address(0) && registeredAddress[_addr] == false);
registeredAddress[_addr] = true;
Registered(_addr);
}
/**
* @dev register the addresses for token sale
* @param _addrs address[] The addresses to register for token sale
*/
function registerByList(address[] _addrs)
public
onlyAdmin
whenNotPaused
{
for(uint256 i = 0; i < _addrs.length; i++) {
require(_addrs[i] != address(0) && registeredAddress[_addrs[i]] == false);
registeredAddress[_addrs[i]] = true;
Registered(_addrs[i]);
}
}
/**
* @dev unregister the registered address
* @param _addr address The address to unregister for token sale
*/
function unregister(address _addr)
public
onlyAdmin
onlyRegistered(_addr)
{
registeredAddress[_addr] = false;
Unregistered(_addr);
}
/**
* @dev unregister the registered addresses
* @param _addrs address[] The addresses to unregister for token sale
*/
function unregisterByList(address[] _addrs)
public
onlyAdmin
{
for(uint256 i = 0; i < _addrs.length; i++) {
require(isRegistered(_addrs[i]));
registeredAddress[_addrs[i]] = false;
Unregistered(_addrs[i]);
}
}
}
/**
* @title PLCCrowdsale
* @dev PLCCrowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract PLCCrowdsale is Ownable, SafeMath, Pausable {
// token registery contract
KYC public kyc;
// The token being sold
PLC public token;
// start and end timestamps where investments are allowed (both inclusive)
uint64 public startTime; // 1506384000; //2017.9.26 12:00 am (UTC)
uint64 public endTime; // 1507593600; //2017.10.10 12:00 am (UTC)
uint64[5] public deadlines; // [1506643200, 1506902400, 1507161600, 1507420800, 1507593600]; // [2017.9.26, 2017.10.02, 2017.10.05, 2017.10.08, 2017.10.10]
mapping (address => uint256) public presaleRate;
uint8[5] public rates = [240, 230, 220, 210, 200];
// amount of raised money in wei
uint256 public weiRaised;
// amount of ether buyer can buy
uint256 constant public maxGuaranteedLimit = 5000 ether;
// amount of ether presale buyer can buy
mapping (address => uint256) public presaleGuaranteedLimit;
mapping (address => bool) public isDeferred;
// amount of ether funded for each buyer
// bool: true if deferred otherwise false
mapping (bool => mapping (address => uint256)) public buyerFunded;
// amount of tokens minted for deferredBuyers
uint256 public deferredTotalTokens;
// buyable interval in block number 20
uint256 constant public maxCallFrequency = 20;
// block number when buyer buy
mapping (address => uint256) public lastCallBlock;
bool public isFinalized = false;
// minimum amount of funds to be raised in weis
uint256 public maxEtherCap; // 100000 ether;
uint256 public minEtherCap; // 30000 ether;
// investor address list
address[] buyerList;
mapping (address => bool) inBuyerList;
// number of refunded investors
uint256 refundCompleted;
// new owner of token contract when crowdsale is Finalized
address newTokenOwner = 0x568E2B5e9643D38e6D8146FeE8d80a1350b2F1B9;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
// dev team multisig wallet
address devMultisig;
// reserve
address[] reserveWallet;
/**
* @dev Checks whether buyer is sending transaction too frequently
*/
modifier canBuyInBlock () {
require(add(lastCallBlock[msg.sender], maxCallFrequency) < block.number);
lastCallBlock[msg.sender] = block.number;
_;
}
/**
* @dev Checks whether ico is started
*/
modifier onlyAfterStart() {
require(now >= startTime && now <= endTime);
_;
}
/**
* @dev Checks whether ico is not started
*/
modifier onlyBeforeStart() {
require(now < startTime);
_;
}
/**
* @dev Checks whether the account is registered
*/
modifier onlyRegistered(address _addr) {
require(kyc.isRegistered(_addr));
_;
}
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event PresaleTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event DeferredPresaleTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* event for finalize logging
*/
event Finalized();
/**
* event for register presale logging
* @param presaleInvestor who register for presale
* @param presaleAmount weis presaleInvestor can buy as presale
* @param _presaleRate rate at which presaleInvestor can buy tokens
* @param _isDeferred whether the investor is deferred investor
*/
event RegisterPresale(address indexed presaleInvestor, uint256 presaleAmount, uint256 _presaleRate, bool _isDeferred);
/**
* event for unregister presale logging
* @param presaleInvestor who register for presale
*/
event UnregisterPresale(address indexed presaleInvestor);
/**
* @dev PLCCrowdsale constructor sets variables
* @param _kyc address The address which KYC contract is deployed at
* @param _token address The address which PLC contract is deployed at
* @param _refundVault address The address which RefundVault is deployed at
* @param _devMultisig address The address which MultiSigWallet for devTeam is deployed at
* @param _reserveWallet address[5] The address list of reserveWallet addresses
* @param _timelines uint64[5] list of timelines from startTime to endTime with timelines for rate changes
* @param _maxEtherCap uint256 The value which maximum weis to be funded
* @param _minEtherCap uint256 The value which minimum weis to be funded
*/
function PLCCrowdsale(
address _kyc,
address _token,
address _refundVault,
address _devMultisig,
address[] _reserveWallet,
uint64[6] _timelines, // [startTime, ... , endTime]
uint256 _maxEtherCap,
uint256 _minEtherCap)
{
//timelines check
for(uint8 i = 0; i < _timelines.length-1; i++){
require(_timelines[i] < _timelines[i+1]);
}
require(_timelines[0] >= now);
//address check
require(_kyc != 0x00 && _token != 0x00 && _refundVault != 0x00 && _devMultisig != 0x00);
for(i = 0; i < _reserveWallet.length; i++){
require(_reserveWallet[i] != 0x00);
}
//cap check
require(_minEtherCap < _maxEtherCap);
kyc = KYC(_kyc);
token = PLC(_token);
vault = RefundVault(_refundVault);
devMultisig = _devMultisig;
reserveWallet = _reserveWallet;
startTime = _timelines[0];
endTime = _timelines[5];
deadlines[0] = _timelines[1];
deadlines[1] = _timelines[2];
deadlines[2] = _timelines[3];
deadlines[3] = _timelines[4];
deadlines[4] = _timelines[5];
maxEtherCap = _maxEtherCap;
minEtherCap = _minEtherCap;
}
/**
* @dev PLCCrowdsale fallback function for buying Tokens
*/
function () payable {
if(isDeferred[msg.sender])
buyDeferredPresaleTokens(msg.sender);
else if(now < startTime)
buyPresaleTokens(msg.sender);
else
buyTokens();
}
/**
* @dev push all token buyers in list
* @param _addr address Account to push into buyerList
*/
function pushBuyerList(address _addr) internal {
if (!inBuyerList[_addr]) {
inBuyerList[_addr] = true;
buyerList.push(_addr);
}
}
/**
* @dev register presale account checking modifier
* @param presaleInvestor address The account to register as presale account
* @param presaleAmount uint256 The value which investor is allowed to buy
* @param _presaleRate uint256 The rate at which investor buy tokens
* @param _isDeferred bool whether presaleInvestor is deferred buyer
*/
function registerPresale(address presaleInvestor, uint256 presaleAmount, uint256 _presaleRate, bool _isDeferred)
onlyBeforeStart
onlyOwner
{
require(presaleInvestor != 0x00);
require(presaleAmount > 0);
require(_presaleRate > 0);
require(presaleGuaranteedLimit[presaleInvestor] == 0);
presaleGuaranteedLimit[presaleInvestor] = presaleAmount;
presaleRate[presaleInvestor] = _presaleRate;
isDeferred[presaleInvestor] = _isDeferred;
if(_isDeferred) {
weiRaised = add(weiRaised, presaleAmount);
uint256 deferredInvestorToken = mul(presaleAmount, _presaleRate);
uint256 deferredDevToken = div(mul(deferredInvestorToken, 20), 70);
uint256 deferredReserveToken = div(mul(deferredInvestorToken, 10), 70);
uint256 totalAmount = add(deferredInvestorToken, add(deferredDevToken, deferredReserveToken));
token.mint(address(this), totalAmount);
deferredTotalTokens = add(deferredTotalTokens, totalAmount);
}
RegisterPresale(presaleInvestor, presaleAmount, _presaleRate, _isDeferred);
}
/**
* @dev register presale account checking modifier
* @param presaleInvestor address The account to register as presale account
*/
function unregisterPresale(address presaleInvestor)
onlyBeforeStart
onlyOwner
{
require(presaleInvestor != 0x00);
require(presaleGuaranteedLimit[presaleInvestor] > 0);
uint256 _amount = presaleGuaranteedLimit[presaleInvestor];
uint256 _rate = presaleRate[presaleInvestor];
bool _isDeferred = isDeferred[presaleInvestor];
require(buyerFunded[_isDeferred][presaleInvestor] == 0);
presaleGuaranteedLimit[presaleInvestor] = 0;
presaleRate[presaleInvestor] = 0;
isDeferred[presaleInvestor] = false;
if(_isDeferred) {
weiRaised = sub(weiRaised, _amount);
uint256 deferredInvestorToken = mul(_amount, _rate);
uint256 deferredDevToken = div(mul(deferredInvestorToken, 20), 70);
uint256 deferredReserveToken = div(mul(deferredInvestorToken, 10), 70);
uint256 totalAmount = add(deferredInvestorToken, add(deferredDevToken, deferredReserveToken));
deferredTotalTokens = sub(deferredTotalTokens, totalAmount);
token.burn(totalAmount);
}
UnregisterPresale(presaleInvestor);
}
/**
* @dev buy token (deferred presale investor)
* @param beneficiary address The account to receive tokens
*/
function buyDeferredPresaleTokens(address beneficiary)
payable
whenNotPaused
{
require(beneficiary != 0x00);
require(isDeferred[beneficiary]);
uint guaranteedLimit = presaleGuaranteedLimit[beneficiary];
require(guaranteedLimit > 0);
uint256 weiAmount = msg.value;
require(weiAmount != 0);
uint256 totalAmount = add(buyerFunded[true][beneficiary], weiAmount);
uint256 toFund;
if (totalAmount > guaranteedLimit) {
toFund = sub(guaranteedLimit, buyerFunded[true][beneficiary]);
} else {
toFund = weiAmount;
}
require(toFund > 0);
require(weiAmount >= toFund);
uint256 tokens = mul(toFund, presaleRate[beneficiary]);
uint256 toReturn = sub(weiAmount, toFund);
buy(beneficiary, tokens, toFund, toReturn, true);
// token distribution : 70% for sale, 20% for dev, 10% for reserve
uint256 devAmount = div(mul(tokens, 20), 70);
uint256 reserveAmount = div(mul(tokens, 10), 70);
distributeToken(devAmount, reserveAmount, true);
// ether distribution : 10% for dev, 90% for reserve
uint256 devEtherAmount = div(toFund, 10);
uint256 reserveEtherAmount = div(mul(toFund, 9), 10);
distributeEther(devEtherAmount, reserveEtherAmount);
DeferredPresaleTokenPurchase(msg.sender, beneficiary, toFund, tokens);
}
/**
* @dev buy token (normal presale investor)
* @param beneficiary address The account to receive tokens
*/
function buyPresaleTokens(address beneficiary)
payable
whenNotPaused
onlyBeforeStart
{
// check validity
require(beneficiary != 0x00);
require(validPurchase());
require(!isDeferred[beneficiary]);
uint guaranteedLimit = presaleGuaranteedLimit[beneficiary];
require(guaranteedLimit > 0);
// calculate eth amount
uint256 weiAmount = msg.value;
uint256 totalAmount = add(buyerFunded[false][beneficiary], weiAmount);
uint256 toFund;
if (totalAmount > guaranteedLimit) {
toFund = sub(guaranteedLimit, buyerFunded[false][beneficiary]);
} else {
toFund = weiAmount;
}
require(toFund > 0);
require(weiAmount >= toFund);
uint256 tokens = mul(toFund, presaleRate[beneficiary]);
uint256 toReturn = sub(weiAmount, toFund);
buy(beneficiary, tokens, toFund, toReturn, false);
forwardFunds(toFund);
PresaleTokenPurchase(msg.sender, beneficiary, toFund, tokens);
}
/**
* @dev buy token (normal investors)
*/
function buyTokens()
payable
whenNotPaused
canBuyInBlock
onlyAfterStart
onlyRegistered(msg.sender)
{
// check validity
require(validPurchase());
require(buyerFunded[false][msg.sender] < maxGuaranteedLimit);
// calculate eth amount
uint256 weiAmount = msg.value;
uint256 totalAmount = add(buyerFunded[false][msg.sender], weiAmount);
uint256 toFund;
if (totalAmount > maxGuaranteedLimit) {
toFund = sub(maxGuaranteedLimit, buyerFunded[false][msg.sender]);
} else {
toFund = weiAmount;
}
if(add(weiRaised,toFund) > maxEtherCap) {
toFund = sub(maxEtherCap, weiRaised);
}
require(toFund > 0);
require(weiAmount >= toFund);
uint256 tokens = mul(toFund, getRate());
uint256 toReturn = sub(weiAmount, toFund);
buy(msg.sender, tokens, toFund, toReturn, false);
forwardFunds(toFund);
TokenPurchase(msg.sender, msg.sender, toFund, tokens);
}
/**
* @dev get buy rate for now
* @return rate uint256 rate for now
*/
function getRate() constant returns (uint256 rate) {
for(uint8 i = 0; i < deadlines.length; i++)
if(now < deadlines[i])
return rates[i];
return rates[rates.length-1];//should never be returned, but to be sure to not divide by 0
}
/**
* @dev get the number of buyers
* @return uint256 the number of buyers
*/
function getBuyerNumber() constant returns (uint256) {
return buyerList.length;
}
/**
* @dev send ether to the fund collection wallet
* @param toFund uint256 The value of weis to send to vault
*/
function forwardFunds(uint256 toFund) internal {
vault.deposit.value(toFund)(msg.sender);
}
/**
* @dev checks whether purchase value is not zero and maxEtherCap is not reached
* @return true if the transaction can buy tokens
*/
function validPurchase() internal constant returns (bool) {
bool nonZeroPurchase = msg.value != 0;
return nonZeroPurchase && !maxReached();
}
function buy(
address _beneficiary,
uint256 _tokens,
uint256 _toFund,
uint256 _toReturn,
bool _isDeferred)
internal
{
if (!_isDeferred) {
pushBuyerList(msg.sender);
weiRaised = add(weiRaised, _toFund);
}
buyerFunded[_isDeferred][_beneficiary] = add(buyerFunded[_isDeferred][_beneficiary], _toFund);
if (!_isDeferred) {
token.mint(address(this), _tokens);
}
// 1 week lock
token.grantVestedTokens(
_beneficiary,
_tokens,
uint64(endTime),
uint64(endTime + 1 weeks),
uint64(endTime + 1 weeks),
false,
false);
// return ether if needed
if (_toReturn > 0) {
msg.sender.transfer(_toReturn);
}
}
/**
* @dev distribute token to multisig wallet and reserve walletes.
* This function is called in two context where crowdsale is closing and
* deferred token is bought.
* @param devAmount uint256 token amount for dev multisig wallet
* @param reserveAmount uint256 token amount for reserve walletes
* @param _isDeferred bool check whether function is called when deferred token is sold
*/
function distributeToken(uint256 devAmount, uint256 reserveAmount, bool _isDeferred) internal {
uint256 eachReserveAmount = div(reserveAmount, reserveWallet.length);
token.grantVestedTokens(
devMultisig,
devAmount,
uint64(endTime),
uint64(endTime),
uint64(endTime + 1 years),
false,
false);
if (_isDeferred) {
for(uint8 i = 0; i < reserveWallet.length; i++) {
token.transfer(reserveWallet[i], eachReserveAmount);
}
} else {
for(uint8 j = 0; j < reserveWallet.length; j++) {
token.mint(reserveWallet[j], eachReserveAmount);
}
}
}
/**
* @dev distribute ether to multisig wallet and reserve walletes
* @param devAmount uint256 ether amount for dev multisig wallet
* @param reserveAmount uint256 ether amount for reserve walletes
*/
function distributeEther(uint256 devAmount, uint256 reserveAmount) internal {
uint256 eachReserveAmount = div(reserveAmount, reserveWallet.length);
devMultisig.transfer(devAmount);
for(uint8 i = 0; i < reserveWallet.length; i++){
reserveWallet[i].transfer(eachReserveAmount);
}
}
/**
* @dev checks whether crowdsale is ended
* @return true if crowdsale event has ended
*/
function hasEnded() public constant returns (bool) {
return now > endTime;
}
/**
* @dev should be called after crowdsale ends, to do
*/
function finalize() {
require(!isFinalized);
require(hasEnded() || maxReached());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev end token minting on finalization, mint tokens for dev team and reserve wallets
*/
function finalization() internal {
if (minReached()) {
vault.close();
uint256 totalToken = token.totalSupply();
uint256 tokenSold = sub(totalToken, deferredTotalTokens);
// token distribution : 70% for sale, 20% for dev, 10% for reserve
uint256 devAmount = div(mul(tokenSold, 20), 70);
uint256 reserveAmount = div(mul(tokenSold, 10), 70);
token.mint(address(this), devAmount);
distributeToken(devAmount, reserveAmount, false);
} else {
vault.enableRefunds();
}
token.finishMinting();
token.transferOwnership(newTokenOwner);
}
/**
* @dev should be called when ethereum is forked during crowdsale for refunding ethers on not supported fork
*/
function finalizeWhenForked() onlyOwner whenPaused {
require(!isFinalized);
isFinalized = true;
vault.enableRefunds();
token.finishMinting();
}
/**
* @dev refund a lot of investors at a time checking onlyOwner
* @param numToRefund uint256 The number of investors to refund
*/
function refundAll(uint256 numToRefund) onlyOwner {
require(isFinalized);
require(!minReached());
require(numToRefund > 0);
uint256 limit = refundCompleted + numToRefund;
if (limit > buyerList.length) {
limit = buyerList.length;
}
for(uint256 i = refundCompleted; i < limit; i++) {
vault.refund(buyerList[i]);
}
refundCompleted = limit;
}
/**
* @dev if crowdsale is unsuccessful, investors can claim refunds here
* @param investor address The account to be refunded
*/
function claimRefund(address investor) returns (bool) {
require(isFinalized);
require(!minReached());
return vault.refund(investor);
}
/**
* @dev Checks whether maxEtherCap is reached
* @return true if max ether cap is reaced
*/
function maxReached() public constant returns (bool) {
return weiRaised == maxEtherCap;
}
/**
* @dev Checks whether minEtherCap is reached
* @return true if min ether cap is reaced
*/
function minReached() public constant returns (bool) {
return weiRaised >= minEtherCap;
}
/**
* @dev should burn unpaid tokens of deferred presale investors
*/
function burnUnpaidTokens()
onlyOwner
{
require(isFinalized);
uint256 unpaidTokens = token.balanceOf(address(this));
token.burn(unpaidTokens);
}
}
|
* @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 amout of tokens to be transfered/ Check is not needed because sub(_allowance, _value) will already throw if this condition is not met require (_value <= _allowance);
|
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = add(balances[_to],_value);
balances[_from] = sub(balances[_from],_value);
allowed[_from][msg.sender] = sub(_allowance,_value);
Transfer(_from, _to, _value);
return true;
}
| 2,079,835 |
[
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
225,
389,
2080,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
389,
1132,
2254,
5034,
326,
2125,
659,
434,
2430,
358,
506,
7412,
329,
19,
2073,
353,
486,
3577,
2724,
720,
24899,
5965,
1359,
16,
389,
1132,
13,
903,
1818,
604,
309,
333,
2269,
353,
486,
5100,
2583,
261,
67,
1132,
1648,
389,
5965,
1359,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1135,
261,
6430,
13,
288,
203,
565,
569,
389,
5965,
1359,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
15533,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
527,
12,
70,
26488,
63,
67,
869,
6487,
67,
1132,
1769,
203,
565,
324,
26488,
63,
67,
2080,
65,
273,
720,
12,
70,
26488,
63,
67,
2080,
6487,
67,
1132,
1769,
203,
565,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
720,
24899,
5965,
1359,
16,
67,
1132,
1769,
203,
565,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.3;
pragma experimental ABIEncoderV2;
contract Manageable {
address public owner;
mapping(address => uint) public admins;
bool public locked = false;
event onOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
emit onOwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
modifier onlyAdmin() {
require(msg.sender == owner || admins[msg.sender] == 1);
_;
}
modifier onlyUploader(address uploader) {
require(msg.sender == owner || msg.sender == uploader);
_;
}
function addAdminAccount(address _newAdminAccount, uint256 _status) public onlyOwner {
require(_newAdminAccount != address(0));
admins[_newAdminAccount] = _status;
}
/**
* @dev Modifier to make a function callable only when the contract is not locked.
*/
modifier isNotLocked() {
require(!locked || msg.sender == owner);
_;
}
/**
* @dev called by the owner to set lock state, triggers stop/continue state
*/
function setLock(bool _value) onlyAdmin public {
locked = _value;
}
}
contract Movies is Manageable {
// the movie information
struct Movie {
string name;
string cover_hash;
Thumbs thumbs; // the information about thumb up and thumb down.
uint256 trx_reward;
uint256 token_reward;
address uploader; // who call the setMovie func.
StringArray keywords;
}
// the thumbs up/down information
struct Thumbs {
address[] thumbsUpByWhom;
address[] thumbsDownByWhom;
mapping(address => uint) thumbsUpIndex; // store the address that thumb up;
mapping(address => uint) thumbsDownIndex; // store the address that thumb down;
}
mapping(string => StringArray) moviesByName; // name => hashes
mapping(string => Movie) movieInfo; // hash => move info
mapping(string => StringArray) keywordIndex; // keyword => the hash in the same key words.
mapping(address => StringArray) moviesByUploader; // address => hashes, store all the movies that somebody has uploaded.
StringArray allMovies; // all the movies' hash.
struct StringArray {
string[] array; // the string array
mapping(string => uint256) index; // the index of string array.
}
uint256 fee_percent;
uint256 tokenId;
constructor() public {
fee_percent = 20;
tokenId = 1002000;
}
// set the movie hash, poster hash and movie name in smart contract.
function setMovie(string name, string movieHash, string coverHash, string[] keywords) public onlyAdmin {
// if the movie hash been uploaded, revert.
require(movieInfo[movieHash].uploader == address(0), "This movie has been uploaded");
// set movie.
moviesByName[name].array.push(movieHash);
moviesByName[name].index[movieHash] = moviesByName[name].array.length;
movieInfo[movieHash].name = name;
movieInfo[movieHash].uploader = msg.sender;
movieInfo[movieHash].cover_hash = coverHash;
// set keywords.
addKeywords(movieHash, keywords);
// set the movie to moviesByUploader.
moviesByUploader[msg.sender].array.push(movieHash);
moviesByUploader[msg.sender].index[movieHash] = moviesByUploader[msg.sender].array.length;
// set the movie into allMovies.
allMovies.array.push(movieHash);
allMovies.index[movieHash] = allMovies.array.length;
}
// add keywords to the movie and keyword index.
function addKeywords(string hash, string[] keywords) public onlyUploader(movieInfo[hash].uploader) {
if(movieInfo[hash].uploader != address(0) ) {
for(uint i=0; i < keywords.length; i ++) {
// if the keyword doesn't been added.
if(movieInfo[hash].keywords.index[keywords[i]] == 0) {
// add the keywords to the movieInfo
movieInfo[hash].keywords.array.push(keywords[i]);
movieInfo[hash].keywords.index[keywords[i]] = movieInfo[hash].keywords.array.length;
// add the keyword to keywordIndex.
keywordIndex[keywords[i]].array.push(hash);
keywordIndex[keywords[i]].index[hash] = keywordIndex[keywords[i]].array.length;
}
}
}
}
// remove the movie's keyword.
function removeKeywords(string hash, string[] keywords) public onlyUploader(movieInfo[hash].uploader) {
if(movieInfo[hash].uploader != address(0)) {
for(uint j=0; j < keywords.length; j++){
uint index = movieInfo[hash].keywords.index[keywords[j]] - 1;
uint len = movieInfo[hash].keywords.array.length;
// remove keyword from movieInfo.
if (index != len-1) {
movieInfo[hash].keywords.index[movieInfo[hash].keywords.array[len-1]] = index+1;
movieInfo[hash].keywords.array[index] = movieInfo[hash].keywords.array[len-1];
}
delete movieInfo[hash].keywords.array[len-1];
movieInfo[hash].keywords.array.length--;
movieInfo[hash].keywords.index[keywords[j]] = 0;
// remove keyword from keywordIndex.
index = keywordIndex[keywords[j]].index[hash] - 1;
len = keywordIndex[keywords[j]].array.length;
if(index != len-1) {
keywordIndex[keywords[j]].index[keywordIndex[keywords[j]].array[len-1]] = index+1;
keywordIndex[keywords[j]].array[index] = keywordIndex[keywords[j]].array[len-1];
}
delete keywordIndex[keywords[j]].array[len-1];
keywordIndex[keywords[j]].array.length--;
keywordIndex[keywords[j]].index[hash] = 0;
}
}
}
// delete movie by movie hash.
function deleteMovie(string hash) public onlyUploader(movieInfo[hash].uploader) returns (bool){
// if the movie is exist, delete it form movieInfo and movies.
if (movieInfo[hash].uploader != address(0)) {
// delete reference keywords.
for(uint i=0; i<movieInfo[hash].keywords.array.length; i++) {
// remove keyword from keywordIndex and delete keyword map.
string keyword = movieInfo[hash].keywords.array[i];
index = keywordIndex[keyword].index[hash] - 1;
len = keywordIndex[keyword].array.length;
if(index != len-1) {
keywordIndex[keyword].index[keywordIndex[keyword].array[len-1]] = index+1;
keywordIndex[keyword].array[index] = keywordIndex[keyword].array[len-1];
}
delete keywordIndex[keyword].array[len-1];
keywordIndex[keyword].array.length--;
keywordIndex[keyword].index[hash] = 0;
// delete keywords map.
delete movieInfo[hash].keywords.index[keyword];
}
// delete it from movies.
uint len = moviesByName[movieInfo[hash].name].array.length;
uint index = moviesByName[movieInfo[hash].name].index[hash]-1;
if (index != len-1) {
moviesByName[movieInfo[hash].name].index[moviesByName[movieInfo[hash].name].array[len-1]] = index+1;
moviesByName[movieInfo[hash].name].array[index] = moviesByName[movieInfo[hash].name].array[len-1];
}
delete moviesByName[movieInfo[hash].name].array[len-1];
moviesByName[movieInfo[hash].name].array.length--;
moviesByName[movieInfo[hash].name].index[hash] = 0;
// delete from moviesByUploader.
index = moviesByUploader[movieInfo[hash].uploader].index[hash] - 1;
len = moviesByUploader[movieInfo[hash].uploader].array.length;
if (index != len-1) {
moviesByUploader[movieInfo[hash].uploader].index[moviesByUploader[movieInfo[hash].uploader].array[len-1]] = index+1;
moviesByUploader[movieInfo[hash].uploader].array[index] = moviesByUploader[movieInfo[hash].uploader].array[len-1];
}
delete moviesByUploader[movieInfo[hash].uploader].array[len-1];
moviesByUploader[movieInfo[hash].uploader].array.length--;
moviesByUploader[movieInfo[hash].uploader].index[hash] = 0;
// delete from moviesInfo.
// delete thumbs map.
for (i=0; i<movieInfo[hash].thumbs.thumbsUpByWhom.length; i++) {
delete movieInfo[hash].thumbs.thumbsUpIndex[movieInfo[hash].thumbs.thumbsUpByWhom[i]];
}
for (i=0; i<movieInfo[hash].thumbs.thumbsDownByWhom.length; i++) {
delete movieInfo[hash].thumbs.thumbsDownIndex[movieInfo[hash].thumbs.thumbsDownByWhom[i]];
}
// delete movieInfo.
delete movieInfo[hash];
// delete from allMovies and indexOfAllMovies.
index = allMovies.index[hash] -1;
len = allMovies.array.length;
if (index != len-1) {
allMovies.index[allMovies.array[len-1]] = index+1;
allMovies.array[index] = allMovies.array[len-1];
}
delete allMovies.array[len-1];
allMovies.array.length--;
allMovies.index[hash] = 0;
return true;
}
return false;
}
// get all the movie hashes which names the given name.
function getMovies(string s) public view returns (string[] hashesByName, string[] hashesByKeyword) {
hashesByName = moviesByName[s].array;
hashesByKeyword = keywordIndex[s].array;
}
// function to get all the movies.
function getAllMovies() public view returns (string[]) {
return allMovies.array;
}
// get all the movie hashes that somebody uploaded.
function getUploadedMovies() public view returns (string[]) {
return moviesByUploader[msg.sender].array;
}
// get the movie info by movie hash.
function getMovieInfo(string hash) public view returns (
string name, string cover_hash, string[] keywords, uint256 trx_reward, uint256 token_reward,
uint256 thumbsUp, uint256 thumbsDown, address uploader) {
name = movieInfo[hash].name;
trx_reward = movieInfo[hash].trx_reward;
token_reward = movieInfo[hash].token_reward;
thumbsUp = movieInfo[hash].thumbs.thumbsUpByWhom.length;
thumbsDown = movieInfo[hash].thumbs.thumbsDownByWhom.length;
uploader = movieInfo[hash].uploader;
cover_hash = movieInfo[hash].cover_hash;
keywords = movieInfo[hash].keywords.array;
}
// thumbs up a movie by movie hash.
function thumbsUp(string hash) public payable returns (uint256) {
require(movieInfo[hash].thumbs.thumbsUpIndex[msg.sender] == 0, "you've thumbs up before");
movieInfo[hash].thumbs.thumbsUpByWhom.push(msg.sender);
movieInfo[hash].thumbs.thumbsUpIndex[msg.sender] = 1;
return movieInfo[hash].thumbs.thumbsUpByWhom.length;
}
// get the movie thumbs up number by movie hash.
function getThumbsUp(string hash) public view returns (uint256) {
return movieInfo[hash].thumbs.thumbsUpByWhom.length;
}
// thumbs down a movie by hash.
function thumbsDown(string hash) public returns (uint256){
require(movieInfo[hash].thumbs.thumbsDownIndex[msg.sender] == 0, "you've thumbs down before");
movieInfo[hash].thumbs.thumbsDownByWhom.push(msg.sender);
movieInfo[hash].thumbs.thumbsDownIndex[msg.sender] = 1;
return movieInfo[hash].thumbs.thumbsDownByWhom.length;
}
// get the movie thumbs down number by movie hash.
function getThumbsDown(string hash) public view returns (uint256) {
return movieInfo[hash].thumbs.thumbsDownByWhom.length;
}
// tips token to the movie by hash, the token will give to by movie uploader and admin in percentage.
function tipToken(string hash) public payable returns (uint256) {
require(msg.tokenid == tokenId, "wrong token id");
if (msg.tokenvalue > 0 ) {
uint256 token_fee_amount = msg.tokenvalue * fee_percent / 100;
owner.transferToken(token_fee_amount, tokenId);
movieInfo[hash].uploader.transferToken(msg.tokenvalue-token_fee_amount, tokenId);
movieInfo[hash].token_reward += msg.tokenvalue-token_fee_amount;
}
return movieInfo[hash].token_reward;
}
// return how much token that the movie uploader get.
function getTokenTips(string hash) public view returns (uint256) {
return movieInfo[hash].token_reward;
}
// tips trx to the movie by hash, the trx will give to by movie uploader and admin in percentage.
function tipTrx(string hash) public payable returns (uint256) {
if (msg.value > 0) {
uint256 fee_amount = msg.value * fee_percent / 100;
owner.transfer(fee_amount);
movieInfo[hash].uploader.transfer(msg.value-fee_amount);
movieInfo[hash].trx_reward += msg.value-fee_amount;
}
return movieInfo[hash].trx_reward;
}
// return how much trx that the movie uploader get.
function getTrxTips(string hash) public view returns (uint256) {
return movieInfo[hash].trx_reward;
}
// get which token id that tips a token require.
function getTokenId() public view returns (uint256) {
return tokenId;
}
// function to change the fee percent.
function changeFeePercent(uint _percent) public onlyOwner {
require(_percent >= 0 && _percent <= 100, "fee percent should between 1~100");
fee_percent = _percent;
}
// function to change the tokenId.
function changeTokenId(uint256 _tokenId) public onlyOwner {
tokenId = _tokenId;
}
}
|
get all the movie hashes that somebody uploaded.
|
function getUploadedMovies() public view returns (string[]) {
return moviesByUploader[msg.sender].array;
}
| 13,136,421 |
[
1,
588,
777,
326,
21360,
9869,
716,
2690,
3432,
9140,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
336,
24585,
16727,
29028,
1435,
1071,
1476,
1135,
261,
1080,
63,
5717,
288,
203,
3639,
327,
7344,
29028,
858,
28161,
63,
3576,
18,
15330,
8009,
1126,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {PercentageMath} from '../libraries/math/PercentageMath.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol';
/**
* @title DefaultReserveInterestRateStrategy contract
* @notice Implements the calculation of the interest rates depending on the reserve state
* @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE`
* point of utilization and another from that one to 100%
* - An instance of this same contract, can't be used across different Aave markets, due to the caching
* of the LendingPoolAddressesProvider
* @author Aave
**/
contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy {
using WadRayMath for uint256;
using SafeMath for uint256;
using PercentageMath for uint256;
/**
* @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates.
* Expressed in ray
**/
uint256 public immutable OPTIMAL_UTILIZATION_RATE;
/**
* @dev This constant represents the excess utilization rate above the optimal. It's always equal to
* 1-optimal utilization rate. Added as a constant here for gas optimizations.
* Expressed in ray
**/
uint256 public immutable EXCESS_UTILIZATION_RATE;
ILendingPoolAddressesProvider public immutable addressesProvider;
// Base variable borrow rate when Utilization rate = 0. Expressed in ray
uint256 internal immutable _baseVariableBorrowRate;
// Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _variableRateSlope1;
// Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _variableRateSlope2;
// Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _stableRateSlope1;
// Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _stableRateSlope2;
constructor(
ILendingPoolAddressesProvider provider,
uint256 optimalUtilizationRate,
uint256 baseVariableBorrowRate,
uint256 variableRateSlope1,
uint256 variableRateSlope2,
uint256 stableRateSlope1,
uint256 stableRateSlope2
) public {
OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate;
EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate);
addressesProvider = provider;
_baseVariableBorrowRate = baseVariableBorrowRate;
_variableRateSlope1 = variableRateSlope1;
_variableRateSlope2 = variableRateSlope2;
_stableRateSlope1 = stableRateSlope1;
_stableRateSlope2 = stableRateSlope2;
}
function variableRateSlope1() external view returns (uint256) {
return _variableRateSlope1;
}
function variableRateSlope2() external view returns (uint256) {
return _variableRateSlope2;
}
function stableRateSlope1() external view returns (uint256) {
return _stableRateSlope1;
}
function stableRateSlope2() external view returns (uint256) {
return _stableRateSlope2;
}
function baseVariableBorrowRate() external view override returns (uint256) {
return _baseVariableBorrowRate;
}
function getMaxVariableBorrowRate() external view override returns (uint256) {
return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2);
}
struct CalcInterestRatesLocalVars {
uint256 totalDebt;
uint256 currentVariableBorrowRate;
uint256 currentStableBorrowRate;
uint256 currentLiquidityRate;
uint256 utilizationRate;
}
/**
* @dev Calculates the interest rates depending on the reserve's state and configurations
* @param reserve The address of the reserve
* @param availableLiquidity The liquidity available in the reserve
* @param totalStableDebt The total borrowed from the reserve a stable rate
* @param totalVariableDebt The total borrowed from the reserve at a variable rate
* @param averageStableBorrowRate The weighted average of all the stable rate loans
* @param reserveFactor The reserve portion of the interest that goes to the treasury of the market
* @return The liquidity rate, the stable borrow rate and the variable borrow rate
**/
function calculateInterestRates(
address reserve,
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
override
returns (
uint256,
uint256,
uint256
)
{
CalcInterestRatesLocalVars memory vars;
vars.totalDebt = totalStableDebt.add(totalVariableDebt);
vars.currentVariableBorrowRate = 0;
vars.currentStableBorrowRate = 0;
vars.currentLiquidityRate = 0;
uint256 utilizationRate =
vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt));
vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle())
.getMarketBorrowRate(reserve);
if (utilizationRate > OPTIMAL_UTILIZATION_RATE) {
uint256 excessUtilizationRateRatio =
utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE);
vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add(
_stableRateSlope2.rayMul(excessUtilizationRateRatio)
);
vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add(
_variableRateSlope2.rayMul(excessUtilizationRateRatio)
);
} else {
vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(
_stableRateSlope1.rayMul(utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE))
);
vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(
utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE)
);
}
vars.currentLiquidityRate = _getOverallBorrowRate(
totalStableDebt,
totalVariableDebt,
vars
.currentVariableBorrowRate,
averageStableBorrowRate
)
.rayMul(utilizationRate)
.percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor));
return (
vars.currentLiquidityRate,
vars.currentStableBorrowRate,
vars.currentVariableBorrowRate
);
}
/**
* @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt
* @param totalStableDebt The total borrowed from the reserve a stable rate
* @param totalVariableDebt The total borrowed from the reserve at a variable rate
* @param currentVariableBorrowRate The current variable borrow rate of the reserve
* @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans
* @return The weighted averaged borrow rate
**/
function _getOverallBorrowRate(
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 currentVariableBorrowRate,
uint256 currentAverageStableBorrowRate
) internal pure returns (uint256) {
uint256 totalDebt = totalStableDebt.add(totalVariableDebt);
if (totalDebt == 0) return 0;
uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate);
uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate);
uint256 overallBorrowRate =
weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay());
return overallBorrowRate;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title IReserveInterestRateStrategyInterface interface
* @dev Interface for the calculation of the interest rates
* @author Aave
*/
interface IReserveInterestRateStrategy {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
address reserve,
uint256 utilizationRate,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate
);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Errors} from '../helpers/Errors.sol';
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfWAD) / WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfRAY) / RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title Errors library
* @author Aave
* @notice Defines the error messages emitted by the different contracts of the Aave protocol
* @dev Error messages prefix glossary:
* - VL = ValidationLogic
* - MATH = Math libraries
* - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken)
* - AT = AToken
* - SDT = StableDebtToken
* - VDT = VariableDebtToken
* - LP = LendingPool
* - LPAPR = LendingPoolAddressesProviderRegistry
* - LPC = LendingPoolConfiguration
* - RL = ReserveLogic
* - LPCM = LendingPoolCollateralManager
* - P = Pausable
*/
library Errors {
//common errors
string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin'
string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small
//contract specific errors
string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0'
string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve'
string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen'
string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough'
string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance'
string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.'
string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled'
string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected'
string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0'
string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold'
string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow'
string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled
string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed
string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode
string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt'
string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed'
string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve'
string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve'
string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0'
string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral'
string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve'
string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met'
string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed'
string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow'
string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.'
string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent'
string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator'
string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28';
string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool'
string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself'
string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero'
string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized'
string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve'
string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin'
string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered'
string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold'
string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated'
string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency'
string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate"
string public constant LPCM_NO_ERRORS = '46'; // 'No errors'
string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected
string public constant MATH_MULTIPLICATION_OVERFLOW = '48';
string public constant MATH_ADDITION_OVERFLOW = '49';
string public constant MATH_DIVISION_BY_ZERO = '50';
string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128
string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128
string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128
string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128
string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128
string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint
string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57';
string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn
string public constant LP_FAILED_COLLATERAL_SWAP = '60';
string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61';
string public constant LP_REENTRANCY_NOT_ALLOWED = '62';
string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63';
string public constant LP_IS_PAUSED = '64'; // 'Pool is paused'
string public constant LP_NO_MORE_RESERVES_ALLOWED = '65';
string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66';
string public constant RC_INVALID_LTV = '67';
string public constant RC_INVALID_LIQ_THRESHOLD = '68';
string public constant RC_INVALID_LIQ_BONUS = '69';
string public constant RC_INVALID_DECIMALS = '70';
string public constant RC_INVALID_RESERVE_FACTOR = '71';
string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72';
string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73';
string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74';
string public constant UL_INVALID_INDEX = '77';
string public constant LP_NOT_CONTRACT = '78';
string public constant SDT_STABLE_DEBT_OVERFLOW = '79';
string public constant SDT_BURN_EXCEEDS_BALANCE = '80';
enum CollateralManagerErrors {
NO_ERROR,
NO_COLLATERAL_AVAILABLE,
COLLATERAL_CANNOT_BE_LIQUIDATED,
CURRRENCY_NOT_BORROWED,
HEALTH_FACTOR_ABOVE_THRESHOLD,
NOT_ENOUGH_LIQUIDITY,
NO_ACTIVE_RESERVE,
HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD,
INVALID_EQUAL_ASSETS_TO_SWAP,
FROZEN_RESERVE
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Errors} from '../helpers/Errors.sol';
/**
* @title PercentageMath library
* @author Aave
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
Errors.MATH_MULTIPLICATION_OVERFLOW
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {
require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfPercentage = percentage / 2;
require(
value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,
Errors.MATH_MULTIPLICATION_OVERFLOW
);
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title ILendingRateOracle interface
* @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations
**/
interface ILendingRateOracle {
/**
@dev returns the market borrow rate in ray
**/
function getMarketBorrowRate(address asset) external view returns (uint256);
/**
@dev sets the market borrow rate. Rate value must be in ray
**/
function setMarketBorrowRate(address asset, uint256 rate) external;
}
|
'The liquidity of the reserve needs to be 0'
|
string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40';
| 65,736 |
[
1,
11,
1986,
4501,
372,
24237,
434,
326,
20501,
4260,
358,
506,
374,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
533,
1071,
5381,
511,
3513,
67,
9347,
67,
8355,
7031,
1090,
55,
67,
26413,
67,
734,
273,
296,
7132,
13506,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
*
* $DEWO Token - The Native Token In DecentraWorld's Ecosystem
* DecentraWorld - Increasing Privacy Standards In DeFi
*
* Documentation: http://docs.decentraworld.co/
* GitHub: https://github.com/decentraworldDEWO
* DecentraWorld: https://DecentraWorld.co/
* DAO: https://dao.decentraworld.co/
* Governance: https://gov.decentraworld.co/
* DecentraMix: https://decentramix.io/
*
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*░░██████╗░███████╗░█████╗░███████╗███╗░░██╗████████╗██████╗░░█████╗░░░
*░░██╔══██╗██╔════╝██╔══██╗██╔════╝████╗░██║╚══██╔══╝██╔══██╗██╔══██╗░░
*░░██║░░██║█████╗░░██║░░╚═╝█████╗░░██╔██╗██║░░░██║░░░██████╔╝███████║░░
*░░██║░░██║██╔══╝░░██║░░██╗██╔══╝░░██║╚████║░░░██║░░░██╔══██╗██╔══██║░░
*░░██████╔╝███████╗╚█████╔╝███████╗██║░╚███║░░░██║░░░██║░░██║██║░░██║░░
*░░╚═════╝░╚══════╝░╚════╝░╚══════╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝░░
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*░░░░░░░░░░░░░██╗░░░░░░░██╗░█████╗░██████╗░██╗░░░░░██████╗░░░░░░░░░░░░░
*░░░░░░░░░░░░░██║░░██╗░░██║██╔══██╗██╔══██╗██║░░░░░██╔══██╗░░░░░░░░░░░░
*░░░░░░░░░░░░░╚██╗████╗██╔╝██║░░██║██████╔╝██║░░░░░██║░░██║░░░░░░░░░░░░
*░░░░░░░░░░░░░░████╔═████║░██║░░██║██╔══██╗██║░░░░░██║░░██║░░░░░░░░░░░░
*░░░░░░░░░░░░░░╚██╔╝░╚██╔╝░╚█████╔╝██║░░██║███████╗██████╔╝░░░░░░░░░░░░
*░░░░░░░░░░░░░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░░░░░░░░░░░░░
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*
*/
// SPDX-License-Identifier: MIT
// File: @OpenZeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @OpenZeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @OpenZeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/DecentraWorld_Multichain.sol
/*
*
* $DEWO Token - The Native Token In DecentraWorld's Ecosystem
* DecentraWorld - Increasing Privacy Standards In DeFi
*
* Documentation: http://docs.decentraworld.co/
* GitHub: https://github.com/decentraworldDEWO
* DecentraWorld: https://DecentraWorld.co/
* DAO: https://dao.decentraworld.co/
* Governance: https://gov.decentraworld.co/
* DecentraMix: https://decentramix.io/
*
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*░░██████╗░███████╗░█████╗░███████╗███╗░░██╗████████╗██████╗░░█████╗░░░
*░░██╔══██╗██╔════╝██╔══██╗██╔════╝████╗░██║╚══██╔══╝██╔══██╗██╔══██╗░░
*░░██║░░██║█████╗░░██║░░╚═╝█████╗░░██╔██╗██║░░░██║░░░██████╔╝███████║░░
*░░██║░░██║██╔══╝░░██║░░██╗██╔══╝░░██║╚████║░░░██║░░░██╔══██╗██╔══██║░░
*░░██████╔╝███████╗╚█████╔╝███████╗██║░╚███║░░░██║░░░██║░░██║██║░░██║░░
*░░╚═════╝░╚══════╝░╚════╝░╚══════╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝░░
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*░░░░░░░░░░░░░██╗░░░░░░░██╗░█████╗░██████╗░██╗░░░░░██████╗░░░░░░░░░░░░░
*░░░░░░░░░░░░░██║░░██╗░░██║██╔══██╗██╔══██╗██║░░░░░██╔══██╗░░░░░░░░░░░░
*░░░░░░░░░░░░░╚██╗████╗██╔╝██║░░██║██████╔╝██║░░░░░██║░░██║░░░░░░░░░░░░
*░░░░░░░░░░░░░░████╔═████║░██║░░██║██╔══██╗██║░░░░░██║░░██║░░░░░░░░░░░░
*░░░░░░░░░░░░░░╚██╔╝░╚██╔╝░╚█████╔╝██║░░██║███████╗██████╔╝░░░░░░░░░░░░
*░░░░░░░░░░░░░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░░░░░░░░░░░░░
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*
*/
pragma solidity ^0.8.7;
/**
* @dev Interfaces
*/
interface IDEXFactory {
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 IDEXRouter {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IPancakeswapV2Pair {
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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
/**
* @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);
}
/**
* @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);
}
contract DecentraWorld_Multichain is Context, IERC20, IERC20Metadata, Ownable {
using SafeMath for uint256;
// DecentraWorld - $DEWO
uint256 _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
// Mapping
mapping (string => uint) txTaxes;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping (address => bool) public excludeFromTax;
mapping (address => bool) public exclueFromMaxTx;
// Addresses Of Tax Receivers
address public daoandfarmingAddress;
address public marketingAddress;
address public developmentAddress;
address public coreteamAddress;
// Address of the bridge controling the mint/burn of the cross-chain
address public MPC;
// taxes for differnet levels
struct TaxLevels {
uint taxDiscount;
uint amount;
}
struct DEWOTokenTax {
uint forMarketing;
uint forCoreTeam;
uint forDevelopment;
uint forDAOAndFarming;
}
struct TxLimit {
uint buyMaxTx;
uint sellMaxTx;
uint txcooldown;
mapping(address => uint) buys;
mapping(address => uint) sells;
mapping(address => uint) lastTx;
}
mapping (uint => TaxLevels) taxTiers;
TxLimit txSettings;
IDEXRouter public router;
address public pair;
constructor() {
_name = "DecentraWorld";
_symbol = "$DEWO";
_decimals = 18;
//Temporary Tax Receivers
daoandfarmingAddress = msg.sender;
marketingAddress = 0x5d5a0368b8C383c45c625a7241473A1a4F61eA4E;
developmentAddress = 0xdA9f5e831b7D18c35CA7778eD271b4d4f3bE183E;
coreteamAddress = 0x797BD28BaE691B21e235E953043337F4794Ff9DB;
// Exclude From Taxes By Default
excludeFromTax[msg.sender] = true;
excludeFromTax[daoandfarmingAddress] = true;
excludeFromTax[marketingAddress] = true;
excludeFromTax[developmentAddress] = true;
excludeFromTax[coreteamAddress] = true;
// Exclude From MaxTx By Default
exclueFromMaxTx[msg.sender] = true;
exclueFromMaxTx[daoandfarmingAddress] = true;
exclueFromMaxTx[marketingAddress] = true;
exclueFromMaxTx[developmentAddress] = true;
exclueFromMaxTx[coreteamAddress] = true;
// Cross-Chain Bridge Temp Settings
MPC = msg.sender;
// Transaction taxes apply solely on swaps (buys/sells)
// Tier 1 - Default Buy Fee [6% Total]
// Tier 2 - Buy Fee [3% Total]
// Tier 3 - Buy Fee [0% Total]
//
// Automatically set the default transactions taxes
// [Tier 1: 6% Buy Fee]
txTaxes["marketingBuyTax"] = 3; // [3%] DAO, Governance, Farming Pools
txTaxes["developmentBuyTax"] = 1; // [1%] Marketing Fee
txTaxes["coreteamBuyTax"] = 1; // [1%] Development Fee
txTaxes["daoandfarmingBuyTax"] = 1; // [1%] DecentraWorld's Core-Team
// [Tier 1: 10% Sell Fee]
txTaxes["marketingSellTax"] = 4; // 4% DAO, Governance, Farming Pools
txTaxes["developmentSellTax"] = 3; // 3% Marketing Fee
txTaxes["coreteamSellTax"] = 1; // 1% Development Fee
txTaxes["daoandfarmingSellTax"] = 2; // 2% DecentraWorld's Core-Team
/*
Buy Transaction Tax - 3 tiers:
*** Must buy these amounts to qualify
Tier 1: 6%/10% (0+ $DEWO balance)
Tier 2: 3%/8% (100K+ $DEWO balance)
Tier 3: 0%/6% (400K+ $DEWO balance)
Sell Transaction Tax - 3 tiers:
*** Must hold these amounts to qualify
Tier 1: 6%/10% (0+ $DEWO balance)
Tier 2: 3%/8% (150K+ $DEWO balance)
Tier 3: 0%/6% (300K+ $DEWO balance)
Tax Re-distribution Buys (6%/3%/0%):
DAO Fund/Farming: 3% | 1% | 0%
Marketing Budget: 1% | 1% | 0%
Development Fund: 1% | 0% | 0%
Core-Team: 1% | 1% | 0%
Tax Re-distribution Sells (10%/8%/6%):
DAO Fund/Farming: 4% | 3% | 3%
Marketing Budget: 3% | 2% | 1%
Development Fund: 1% | 1% | 1%
Core-Team: 2% | 2% | 1%
The community can disable the holder rewards fee and migrate that
fee to the rewards/staking pool. This can be done via the Governance portal.
*/
// Default Tax Tiers & Discounts
// Get a 50% discount on purchase tax taxes
taxTiers[0].taxDiscount = 50;
// When buying over 0.1% of total supply (100,000 $DEWO)
taxTiers[0].amount = 100000 * (10 ** decimals());
// Get a 100% discount on purchase tax taxes
taxTiers[1].taxDiscount = 99;
// When buying over 0.4% of total supply (400,000 $DEWO)
taxTiers[1].amount = 400000 * (10 ** decimals());
// Get a 20% discount on sell tax taxes
taxTiers[2].taxDiscount = 20;
// When holding over 0.15% of total supply (150,000 $DEWO)
taxTiers[2].amount = 150000 * (10 ** decimals());
// Get a 40% discount on sell tax taxes
taxTiers[3].taxDiscount = 40;
// When holding over 0.3% of total supply (300,000 $DEWO)
taxTiers[3].amount = 300000 * (10 ** decimals());
// Default txcooldown limit in minutes
txSettings.txcooldown = 30 minutes;
// Default buy limit: 1.25% of total supply
txSettings.buyMaxTx = _totalSupply.div(80);
// Default sell limit: 0.25% of total supply
txSettings.sellMaxTx = _totalSupply.div(800);
/**
Removed from the cross-chain $DEWO token, the pair settings were replaced with a function,
and the mint function of 100,000,000 $DEWO to deployer was replaced with 0. Since this token is
a cross-chain token and not the native EVM chain where $DEWO was deployed (BSC) then there's no need
in any additional supply. The Multichain.org bridge will call burn/mint functions accordingly.
---
// Create a PancakeSwap (DEX) Pair For $DEWO
// This will be used to track the price of $DEWO & charge taxes to all pool buys/sells
address WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; // Wrapped BNB on Binance Smart Chain
address _router = 0x10ED43C718714eb63d5aA57B78B54704E256024E; // PancakeSwap Router (ChainID: 56 = BSC)
router = IDEXRouter(_router);
pair = IDEXFactory(router.factory()).createPair(WBNB, address(this));
_allowances[address(this)][address(router)] = _totalSupply;
approve(_router, _totalSupply);
// Send 100,000,000 $DEWO tokens to the dev (one time only)
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
*/
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
// onlyAuth = allow MPC contract address to call certain functions
// The MPC = Multichain bridge contract of each chain
modifier onlyAuth() {
require(msg.sender == mmpc(), "DecentraWorld: FORBIDDEN");
_;
}
function mmpc() public view returns (address) {
return MPC;
}
// This can only be done once by the deployer, once the MPC is set only the MPC can call this function again.
function setMPC(address _setmpc) external onlyAuth {
MPC = _setmpc;
}
// Mint will be used when individuals cross-chain $DEWO from one chain to another
function mint(address to, uint256 amount) external onlyAuth returns (bool) {
_mint(to, amount);
return true;
}
// The burn function will be used to burn tokens that were cross-chained into another EVM chain
function burn(address from, uint256 amount) external onlyAuth returns (bool) {
require(from != address(0), "DecentraWorld: address(0x0)");
_burn(from, amount);
return true;
}
function Swapin(bytes32 txhash, address account, uint256 amount) public onlyAuth returns (bool) {
_mint(account, amount);
emit LogSwapin(txhash, account, amount);
return true;
}
function Swapout(uint256 amount, address bindaddr) public returns (bool) {
require(bindaddr != address(0), "DecentraWorld: address(0x0)");
_burn(msg.sender, amount);
emit LogSwapout(msg.sender, bindaddr, amount);
return true;
}
event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount);
event LogSwapout(address indexed account, address indexed bindaddr, uint amount);
// Set the router & native token of each chain to tax the correct LP POOL of $DEWO
// This will always be the most popular DEX on the chain + its native token.
function setDEXPAIR(address _nativetoken, address _nativerouter) external onlyOwner {
// Create a DEX Pair For $DEWO
// This will be used to track the price of $DEWO & charge taxes to all pool buys/sells
router = IDEXRouter(_nativerouter);
pair = IDEXFactory(router.factory()).createPair(_nativetoken, address(this));
_allowances[address(this)][address(router)] = _totalSupply;
approve(_nativerouter, _totalSupply);
}
// Set Buy Taxes
event BuyTaxes(
uint _daoandfarmingBuyTax,
uint _coreteamBuyTax,
uint _developmentBuyTax,
uint _marketingBuyTax
);
function setBuyTaxes(
uint _daoandfarmingBuyTax,
uint _coreteamBuyTax,
uint _developmentBuyTax,
uint _marketingBuyTax
// Hardcoded limitation to the maximum tax fee per address
// Maximum tax for each buys/sells: 6% max tax per tax receiver, 24% max tax total
) external onlyOwner {
require(_daoandfarmingBuyTax <= 6, "DAO & Farming tax is above 6%!");
require(_coreteamBuyTax <= 6, "Core-Team Buy tax is above 6%!");
require(_developmentBuyTax <= 6, "Development Fund tax is above 6%!");
require(_marketingBuyTax <= 6, "Marketing tax is above 6%!");
txTaxes["daoandfarmingBuyTax"] = _daoandfarmingBuyTax;
txTaxes["coreteamBuyTax"] = _coreteamBuyTax;
txTaxes["developmentBuyTax"] = _developmentBuyTax;
txTaxes["marketingBuyTax"] = _marketingBuyTax;
emit BuyTaxes(
_daoandfarmingBuyTax,
_coreteamBuyTax,
_developmentBuyTax,
_marketingBuyTax
);
}
// Set Sell Taxes
event SellTaxes(
uint _daoandfarmingSellTax,
uint _coreteamSellTax,
uint _developmentSellTax,
uint _marketingSellTax
);
function setSellTaxes(
uint _daoandfarmingSellTax,
uint _coreteamSellTax,
uint _developmentSellTax,
uint _marketingSellTax
// Hardcoded limitation to the maximum tax fee per address
// Maximum tax for buys/sells: 6% max tax per tax receiver, 24% max tax total
) external onlyOwner {
require(_daoandfarmingSellTax <= 6, "DAO & Farming tax is above 6%!");
require(_coreteamSellTax <= 6, "Core-team tax is above 6%!");
require(_developmentSellTax <= 6, "Development tax is above 6%!");
require(_marketingSellTax <= 6, "Marketing tax is above 6%!");
txTaxes["daoandfarmingSellTax"] = _daoandfarmingSellTax;
txTaxes["coreteamSellTax"] = _coreteamSellTax;
txTaxes["developmentSellTax"] = _developmentSellTax;
txTaxes["marketingSellTax"] = _marketingSellTax;
emit SellTaxes(
_daoandfarmingSellTax,
_coreteamSellTax,
_developmentSellTax,
_marketingSellTax
);
}
// Displays a list of all current taxes
function getSellTaxes() public view returns(
uint marketingSellTax,
uint developmentSellTax,
uint coreteamSellTax,
uint daoandfarmingSellTax
) {
return (
txTaxes["marketingSellTax"],
txTaxes["developmentSellTax"],
txTaxes["coreteamSellTax"],
txTaxes["daoandfarmingSellTax"]
);
}
// Displays a list of all current taxes
function getBuyTaxes() public view returns(
uint marketingBuyTax,
uint developmentBuyTax,
uint coreteamBuyTax,
uint daoandfarmingBuyTax
) {
return (
txTaxes["marketingBuyTax"],
txTaxes["developmentBuyTax"],
txTaxes["coreteamBuyTax"],
txTaxes["daoandfarmingBuyTax"]
);
}
// Set the DAO and Farming Tax Receiver Address (daoandfarmingAddress)
function setDAOandFarmingAddress(address _daoandfarmingAddress) external onlyOwner {
daoandfarmingAddress = _daoandfarmingAddress;
}
// Set the Marketing Tax Receiver Address (marketingAddress)
function setMarketingAddress(address _marketingAddress) external onlyOwner {
marketingAddress = _marketingAddress;
}
// Set the Development Tax Receiver Address (developmentAddress)
function setDevelopmentAddress(address _developmentAddress) external onlyOwner {
developmentAddress = _developmentAddress;
}
// Set the Core-Team Tax Receiver Address (coreteamAddress)
function setCoreTeamAddress(address _coreteamAddress) external onlyOwner {
coreteamAddress = _coreteamAddress;
}
// Exclude an address from tax
function setExcludeFromTax(address _address, bool _value) external onlyOwner {
excludeFromTax[_address] = _value;
}
// Exclude an address from maximum transaction limit
function setExclueFromMaxTx(address _address, bool _value) external onlyOwner {
exclueFromMaxTx[_address] = _value;
}
// Set Buy Tax Tiers
function setBuyTaxTiers(uint _discount1, uint _amount1, uint _discount2, uint _amount2) external onlyOwner {
require(_discount1 > 0 && _discount1 < 100 && _discount2 > 0 && _discount2 < 100 && _amount1 > 0 && _amount2 > 0, "Values have to be bigger than zero!");
taxTiers[0].taxDiscount = _discount1;
taxTiers[0].amount = _amount1;
taxTiers[1].taxDiscount = _discount2;
taxTiers[1].amount = _amount2;
}
// Set Sell Tax Tiers
function setSellTaxTiers(uint _discount3, uint _amount3, uint _discount4, uint _amount4) external onlyOwner {
require(_discount3 > 0 && _discount3 < 100 && _discount4 > 0 && _discount4 < 100 && _amount3 > 0 && _amount4 > 0, "Values have to be bigger than zero!");
taxTiers[2].taxDiscount = _discount3;
taxTiers[2].amount = _amount3;
taxTiers[3].taxDiscount = _discount4;
taxTiers[3].amount = _amount4;
}
// Get Buy Tax Tiers
function getBuyTaxTiers() public view returns(uint discount1, uint amount1, uint discount2, uint amount2) {
return (taxTiers[0].taxDiscount, taxTiers[0].amount, taxTiers[1].taxDiscount, taxTiers[1].amount);
}
// Get Sell Tax Tiers
function getSellTaxTiers() public view returns(uint discount3, uint amount3, uint discount4, uint amount4) {
return (taxTiers[2].taxDiscount, taxTiers[2].amount, taxTiers[3].taxDiscount, taxTiers[3].amount);
}
// Set Transaction Settings: Max Buy Limit, Max Sell Limit, Cooldown Limit.
function setTxSettings(uint _buyMaxTx, uint _sellMaxTx, uint _txcooldown) external onlyOwner {
require(_buyMaxTx >= _totalSupply.div(200), "Buy transaction limit is too low!"); // 0.5%
require(_sellMaxTx >= _totalSupply.div(400), "Sell transaction limit is too low!"); // 0.25%
require(_txcooldown <= 4 minutes, "Cooldown should be 4 minutes or less!");
txSettings.buyMaxTx = _buyMaxTx;
txSettings.sellMaxTx = _sellMaxTx;
txSettings.txcooldown = _txcooldown;
}
// Get Max Transaction Settings: Max Buy, Max Sell, Cooldown Limit.
function getTxSettings() public view returns(uint buyMaxTx, uint sellMaxTx, uint txcooldown) {
return (txSettings.buyMaxTx, txSettings.sellMaxTx, txSettings.txcooldown);
}
// Check Buy Limit During A Cooldown (used in _transfer)
function checkBuyTxLimit(address _sender, uint256 _amount) internal view {
require(
exclueFromMaxTx[_sender] == true ||
txSettings.buys[_sender].add(_amount) < txSettings.buyMaxTx,
"Buy transaction limit reached!"
);
}
// Check Sell Limit During A Cooldown (used in _transfer)
function checkSellTxLimit(address _sender, uint256 _amount) internal view {
require(
exclueFromMaxTx[_sender] == true ||
txSettings.sells[_sender].add(_amount) < txSettings.sellMaxTx,
"Sell transaction limit reached!"
);
}
// Saves the recent buys & sells during a cooldown (used in _transfer)
function setRecentTx(bool _isSell, address _sender, uint _amount) internal {
if(txSettings.lastTx[_sender].add(txSettings.txcooldown) < block.timestamp) {
_isSell ? txSettings.sells[_sender] = _amount : txSettings.buys[_sender] = _amount;
} else {
_isSell ? txSettings.sells[_sender] += _amount : txSettings.buys[_sender] += _amount;
}
txSettings.lastTx[_sender] = block.timestamp;
}
// Get the recent buys, sells, and the last transaction
function getRecentTx(address _address) public view returns(uint buys, uint sells, uint lastTx) {
return (txSettings.buys[_address], txSettings.sells[_address], txSettings.lastTx[_address]);
}
// Get $DEWO Token Price In BNB
function getTokenPrice(uint _amount) public view returns(uint) {
IPancakeswapV2Pair pcsPair = IPancakeswapV2Pair(pair);
IERC20 token1 = IERC20(pcsPair.token1());
(uint Res0, uint Res1,) = pcsPair.getReserves();
uint res0 = Res0*(10**token1.decimals());
return((_amount.mul(res0)).div(Res1));
}
/**
* @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;
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += 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 {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] -= amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @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 taxes, 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");
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
uint marketingFee;
uint developmentFee;
uint coreteamFee;
uint daoandfarmingFee;
uint taxDiscount;
bool hasTaxes = true;
// Buys from PancakeSwap's $DEWO pool
if(from == pair) {
checkBuyTxLimit(to, amount);
setRecentTx(false, to, amount);
marketingFee = txTaxes["marketingBuyTax"];
developmentFee = txTaxes["developmentBuyTax"];
coreteamFee = txTaxes["coreteamBuyTax"];
daoandfarmingFee = txTaxes["daoandfarmingBuyTax"];
// Transaction Tax Tiers 2 & 3 - Discounted Rate
if(amount >= taxTiers[0].amount && amount < taxTiers[1].amount) {
taxDiscount = taxTiers[0].taxDiscount;
} else if(amount >= taxTiers[1].amount) {
taxDiscount = taxTiers[1].taxDiscount;
}
}
// Sells from PancakeSwap's $DEWO pool
else if(to == pair) {
checkSellTxLimit(from, amount);
setRecentTx(true, from, amount);
marketingFee = txTaxes["marketingSellTax"];
developmentFee = txTaxes["developmentSellTax"];
coreteamFee = txTaxes["coreteamSellTax"];
daoandfarmingFee = txTaxes["daoandfarmingSellTax"];
// Calculate the balance after this transaction
uint newBalanceAmount = fromBalance.sub(amount);
// Transaction Tax Tiers 2 & 3 - Discounted Rate
if(newBalanceAmount >= taxTiers[2].amount && newBalanceAmount < taxTiers[3].amount) {
taxDiscount = taxTiers[2].taxDiscount;
} else if(newBalanceAmount >= taxTiers[3].amount) {
taxDiscount = taxTiers[3].taxDiscount;
}
}
unchecked {
_balances[from] = fromBalance - amount;
}
if(excludeFromTax[to] || excludeFromTax[from]) {
hasTaxes = false;
}
// Calculate taxes if this wallet is not excluded and buys/sells from $DEWO's PCS pair pool
if(hasTaxes && (to == pair || from == pair)) {
DEWOTokenTax memory DEWOTokenTaxes;
DEWOTokenTaxes.forDAOAndFarming = amount.mul(daoandfarmingFee).mul(100 - taxDiscount).div(10000);
DEWOTokenTaxes.forDevelopment = amount.mul(developmentFee).mul(100 - taxDiscount).div(10000);
DEWOTokenTaxes.forCoreTeam = amount.mul(coreteamFee).mul(100 - taxDiscount).div(10000);
DEWOTokenTaxes.forMarketing = amount.mul(marketingFee).mul(100 - taxDiscount).div(10000);
// Calculate total taxes and deduct from the transfered amount
uint totalTaxes =
DEWOTokenTaxes.forDAOAndFarming
.add(DEWOTokenTaxes.forDevelopment)
.add(DEWOTokenTaxes.forCoreTeam)
.add(DEWOTokenTaxes.forMarketing);
amount = amount.sub(totalTaxes);
// Pay DAO And Farming Taxes
_balances[daoandfarmingAddress] += DEWOTokenTaxes.forDAOAndFarming;
emit Transfer(from, daoandfarmingAddress, DEWOTokenTaxes.forDAOAndFarming);
// Pay Development Fund Taxes
_balances[developmentAddress] += DEWOTokenTaxes.forDevelopment;
emit Transfer(from, developmentAddress, DEWOTokenTaxes.forDevelopment);
// Pay Core-Team Taxes
_balances[coreteamAddress] += DEWOTokenTaxes.forCoreTeam;
emit Transfer(from, coreteamAddress, DEWOTokenTaxes.forCoreTeam);
// Pay Marketing Taxes
_balances[marketingAddress] += DEWOTokenTaxes.forMarketing;
emit Transfer(from, marketingAddress, DEWOTokenTaxes.forMarketing);
}
_balances[to] += amount;
emit Transfer(from, to, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
}
|
Set the Development Tax Receiver Address (developmentAddress)
|
function setDevelopmentAddress(address _developmentAddress) external onlyOwner {
developmentAddress = _developmentAddress;
}
| 14,413,856 |
[
1,
694,
326,
1505,
11284,
18240,
31020,
5267,
261,
26630,
1887,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
26438,
1887,
12,
2867,
389,
26630,
1887,
13,
3903,
1338,
5541,
288,
203,
3639,
17772,
1887,
273,
389,
26630,
1887,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x9b3aaE4283C11eB463A55Cbd56F552346c2fCb4E/sources/FarmMaster.sol
|
In [0, 60000) blocks, 160 XDEX per block, 9600000 XDEX distributed; In [60000, 180000) blocks, 80 XDEX per block, 9600000 XDEX distributed; In [180000, 420000) blocks, 40 XDEX per block, 9600000 XDEX distributed; In [420000, 900000) blocks, 20 XDEX per block, 9600000 XDEX distributed; After 900000 blocks, 8 XDEX distributed per block./
|
uint256[4] public bonusEndBlocks = [60000, 180000, 420000, 900000];
| 3,433,387 |
[
1,
382,
306,
20,
16,
1666,
2787,
13,
4398,
16,
25430,
1139,
6832,
1534,
1203,
16,
19332,
11706,
1139,
6832,
16859,
31,
657,
306,
26,
2787,
16,
6549,
2787,
13,
4398,
16,
8958,
1139,
6832,
1534,
1203,
16,
19332,
11706,
1139,
6832,
16859,
31,
657,
306,
2643,
2787,
16,
14856,
2787,
13,
4398,
16,
8063,
1139,
6832,
1534,
1203,
16,
19332,
11706,
1139,
6832,
16859,
31,
657,
306,
9452,
2787,
16,
2468,
11706,
13,
4398,
16,
4200,
1139,
6832,
1534,
1203,
16,
19332,
11706,
1139,
6832,
16859,
31,
7360,
2468,
11706,
4398,
16,
1725,
1139,
6832,
16859,
1534,
1203,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
63,
24,
65,
1071,
324,
22889,
1638,
6450,
273,
306,
26,
2787,
16,
6549,
2787,
16,
14856,
2787,
16,
2468,
11706,
15533,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xa5a23CA8bf1f6285aCd14fab6441FA9bCc50323e/sources/project_/contracts/WorldCup.sol
|
@notice pauses the contract from use
|
function toggleOff() external onlyRole(REFEREE) {
require(active, "toggleOff: game not live");
active = false;
emit GameDisabled();
}
| 9,450,006 |
[
1,
8774,
6117,
326,
6835,
628,
999,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
10486,
7210,
1435,
3903,
1338,
2996,
12,
30269,
9383,
13,
288,
203,
3639,
2583,
12,
3535,
16,
315,
14401,
7210,
30,
7920,
486,
8429,
8863,
203,
3639,
2695,
273,
629,
31,
203,
203,
3639,
3626,
14121,
8853,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import "./IArbitrator.sol";
/** @title Centralized Arbitrator
* @dev This is a centralized arbitrator deciding alone on the result of disputes. It illustrates how IArbitrator interface can be implemented.
* Note that this contract supports appeals. The ruling given by the arbitrator can be appealed by crowdfunding a desired choice.
*/
contract CentralizedArbitrator is IArbitrator {
/* Constants */
// The required fee stake that a party must pay depends on who won the previous round and is proportional to the appeal cost such that the fee stake for a round is stake multiplier * appeal cost for that round.
uint256 public constant WINNER_STAKE_MULTIPLIER = 10000; // Multiplier of the appeal cost that the winner has to pay as fee stake for a round in basis points. Default is 1x of appeal fee.
uint256 public constant LOSER_STAKE_MULTIPLIER = 20000; // Multiplier of the appeal cost that the loser has to pay as fee stake for a round in basis points. Default is 2x of appeal fee.
uint256 public constant LOSER_APPEAL_PERIOD_MULTIPLIER = 5000; // Multiplier of the appeal period for the choice that wasn't voted for in the previous round, in basis points. Default is 1/2 of original appeal period.
uint256 public constant MULTIPLIER_DIVISOR = 10000;
/* Enums */
enum DisputeStatus {
Waiting, // The dispute is waiting for the ruling or not created.
Appealable, // The dispute can be appealed.
Solved // The dispute is resolved.
}
/* Structs */
struct DisputeStruct {
IArbitrable arbitrated; // The address of the arbitrable contract.
bytes arbitratorExtraData; // Extra data for the arbitrator.
uint256 choices; // The number of choices the arbitrator can choose from.
uint256 appealPeriodStart; // Time when the appeal funding becomes possible.
uint256 arbitrationFee; // Fee paid by the arbitrable for the arbitration. Must be equal or higher than arbitration cost.
uint256 ruling; // Ruling given by the arbitrator.
DisputeStatus status; // A current status of the dispute.
}
struct Round {
mapping(uint256 => uint256) paidFees; // Tracks the fees paid for each choice in this round.
mapping(uint256 => bool) hasPaid; // True if this choice was fully funded, false otherwise.
mapping(address => mapping(uint256 => uint256)) contributions; // Maps contributors to their contributions for each choice.
uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the ruling that ultimately wins a dispute.
uint256[] fundedChoices; // Stores the choices that are fully funded.
}
/* Storage */
address public owner = msg.sender; // Owner of the contract.
uint256 public appealDuration; // The duration of the appeal period.
uint256 private arbitrationFee; // The cost to create a dispute. Made private because of the arbitrationCost() getter.
uint256 public appealFee; // The cost to fund one of the choices, not counting the additional fee stake amount.
DisputeStruct[] public disputes; // Stores the dispute info. disputes[disputeID].
mapping(uint256 => Round[]) public disputeIDtoRoundArray; // Maps dispute IDs to Round array that contains the info about crowdfunding.
/* Events */
/**
* @dev To be emitted when a dispute can be appealed.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);
/**
* @dev To be emitted when the current ruling is appealed.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);
/** @dev Raised when a contribution is made, inside fundAppeal function.
* @param _disputeID ID of the dispute.
* @param _round The round the contribution was made to.
* @param _choice Indicates the choice option which got the contribution.
* @param _contributor Caller of fundAppeal function.
* @param _amount Contribution amount.
*/
event Contribution(
uint256 indexed _disputeID,
uint256 indexed _round,
uint256 _choice,
address indexed _contributor,
uint256 _amount
);
/** @dev Raised when a contributor withdraws a non-zero value.
* @param _disputeID ID of the dispute.
* @param _round The round the withdrawal was made from.
* @param _choice Indicates the choice which contributor gets rewards from.
* @param _contributor The beneficiary of the withdrawal.
* @param _amount Total withdrawn amount, consists of reimbursed deposits and rewards.
*/
event Withdrawal(
uint256 indexed _disputeID,
uint256 indexed _round,
uint256 _choice,
address indexed _contributor,
uint256 _amount
);
/** @dev To be raised when a choice is fully funded for appeal.
* @param _disputeID ID of the dispute.
* @param _round ID of the round where the choice was funded.
* @param _choice The choice that just got fully funded.
*/
event ChoiceFunded(uint256 indexed _disputeID, uint256 indexed _round, uint256 indexed _choice);
/* Modifiers */
modifier onlyOwner() {
require(msg.sender == owner, "Can only be called by the owner.");
_;
}
/** @dev Constructor.
* @param _arbitrationFee Amount to be paid for arbitration.
* @param _appealDuration Duration of the appeal period.
* @param _appealFee Amount to be paid to fund one of the appeal choices, not counting the additional fee stake amount.
*/
constructor(
uint256 _arbitrationFee,
uint256 _appealDuration,
uint256 _appealFee
) {
arbitrationFee = _arbitrationFee;
appealDuration = _appealDuration;
appealFee = _appealFee;
}
/* External and Public */
/** @dev Set the arbitration fee. Only callable by the owner.
* @param _arbitrationFee Amount to be paid for arbitration.
*/
function setArbitrationFee(uint256 _arbitrationFee) external onlyOwner {
arbitrationFee = _arbitrationFee;
}
/** @dev Set the duration of the appeal period. Only callable by the owner.
* @param _appealDuration New duration of the appeal period.
*/
function setAppealDuration(uint256 _appealDuration) external onlyOwner {
appealDuration = _appealDuration;
}
/** @dev Set the appeal fee. Only callable by the owner.
* @param _appealFee Amount to be paid for appeal.
*/
function setAppealFee(uint256 _appealFee) external onlyOwner {
appealFee = _appealFee;
}
/** @dev Create a dispute. Must be called by the arbitrable contract.
* Must be paid at least arbitrationCost().
* @param _choices Amount of choices the arbitrator can make in this dispute.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return disputeID ID of the dispute created.
*/
function createDispute(uint256 _choices, bytes calldata _extraData)
external
payable
override
returns (uint256 disputeID)
{
uint256 localArbitrationCost = arbitrationCost(_extraData);
require(msg.value >= localArbitrationCost, "Not enough ETH to cover arbitration costs.");
disputeID = disputes.length;
disputes.push(
DisputeStruct({
arbitrated: IArbitrable(msg.sender),
arbitratorExtraData: _extraData,
choices: _choices,
appealPeriodStart: 0,
arbitrationFee: msg.value,
ruling: 0,
status: DisputeStatus.Waiting
})
);
disputeIDtoRoundArray[disputeID].push();
emit DisputeCreation(disputeID, IArbitrable(msg.sender));
}
/** @dev TRUSTED. Manages contributions, and appeals a dispute if at least two choices are fully funded. This function allows the appeals to be crowdfunded.
* Note that the surplus deposit will be reimbursed.
* @param _disputeID Index of the dispute to appeal.
* @param _choice A choice that receives funding.
*/
function fundAppeal(uint256 _disputeID, uint256 _choice) external payable {
DisputeStruct storage dispute = disputes[_disputeID];
require(dispute.status == DisputeStatus.Appealable, "Dispute not appealable.");
require(_choice <= dispute.choices, "There is no such ruling to fund.");
(uint256 appealPeriodStart, uint256 appealPeriodEnd) = appealPeriod(_disputeID);
require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Appeal period is over.");
uint256 multiplier;
if (dispute.ruling == _choice) {
multiplier = WINNER_STAKE_MULTIPLIER;
} else {
require(
block.timestamp - appealPeriodStart <
((appealPeriodEnd - appealPeriodStart) * LOSER_APPEAL_PERIOD_MULTIPLIER) / MULTIPLIER_DIVISOR,
"Appeal period is over for loser"
);
multiplier = LOSER_STAKE_MULTIPLIER;
}
Round[] storage rounds = disputeIDtoRoundArray[_disputeID];
uint256 lastRoundIndex = rounds.length - 1;
Round storage lastRound = rounds[lastRoundIndex];
require(!lastRound.hasPaid[_choice], "Appeal fee is already paid.");
uint256 totalCost = appealFee + (appealFee * multiplier) / MULTIPLIER_DIVISOR;
// Take up to the amount necessary to fund the current round at the current costs.
uint256 contribution;
if (totalCost > lastRound.paidFees[_choice]) {
contribution = totalCost - lastRound.paidFees[_choice] > msg.value // Overflows and underflows will be managed on the compiler level.
? msg.value
: totalCost - lastRound.paidFees[_choice];
emit Contribution(_disputeID, lastRoundIndex, _choice, msg.sender, contribution);
}
lastRound.contributions[msg.sender][_choice] += contribution;
lastRound.paidFees[_choice] += contribution;
if (lastRound.paidFees[_choice] >= totalCost) {
lastRound.feeRewards += lastRound.paidFees[_choice];
lastRound.fundedChoices.push(_choice);
lastRound.hasPaid[_choice] = true;
emit ChoiceFunded(_disputeID, lastRoundIndex, _choice);
}
if (lastRound.fundedChoices.length > 1) {
// At least two sides are fully funded.
rounds.push();
lastRound.feeRewards = lastRound.feeRewards - appealFee;
dispute.status = DisputeStatus.Waiting;
dispute.appealPeriodStart = 0;
emit AppealDecision(_disputeID, dispute.arbitrated);
}
if (msg.value > contribution) payable(msg.sender).send(msg.value - contribution);
}
/** @dev Give a ruling to a dispute. Once it's given the dispute can be appealed, and after the appeal period has passed this function should be called again to finalize the ruling.
* Accounts for the situation where the winner loses a case due to paying less appeal fees than expected.
* @param _disputeID ID of the dispute to rule.
* @param _ruling Ruling given by the arbitrator. Note that 0 means that arbitrator chose "Refused to rule".
*/
function giveRuling(uint256 _disputeID, uint256 _ruling) external onlyOwner {
DisputeStruct storage dispute = disputes[_disputeID];
require(_ruling <= dispute.choices, "Invalid ruling.");
require(dispute.status != DisputeStatus.Solved, "The dispute must not be solved.");
if (dispute.status == DisputeStatus.Waiting) {
dispute.ruling = _ruling;
dispute.status = DisputeStatus.Appealable;
dispute.appealPeriodStart = block.timestamp;
emit AppealPossible(_disputeID, dispute.arbitrated);
} else {
require(block.timestamp > dispute.appealPeriodStart + appealDuration, "Appeal period not passed yet.");
dispute.ruling = _ruling;
dispute.status = DisputeStatus.Solved;
Round[] storage rounds = disputeIDtoRoundArray[_disputeID];
Round storage lastRound = rounds[rounds.length - 1];
// If only one ruling option is funded, it wins by default. Note that if any other ruling had funded, an appeal would have been created.
if (lastRound.fundedChoices.length == 1) {
dispute.ruling = lastRound.fundedChoices[0];
}
payable(msg.sender).send(dispute.arbitrationFee); // Avoid blocking.
dispute.arbitrated.rule(_disputeID, dispute.ruling);
}
}
/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets resolved.
* @param _disputeID Index of the dispute in disputes array.
* @param _beneficiary The address which rewards to withdraw.
* @param _round The round the caller wants to withdraw from.
* @param _choice The ruling option that the caller wants to withdraw from.
* @return amount The withdrawn amount.
*/
function withdrawFeesAndRewards(
uint256 _disputeID,
address payable _beneficiary,
uint256 _round,
uint256 _choice
) external returns (uint256 amount) {
DisputeStruct storage dispute = disputes[_disputeID];
require(dispute.status == DisputeStatus.Solved, "Dispute should be resolved.");
Round storage round = disputeIDtoRoundArray[_disputeID][_round];
if (!round.hasPaid[_choice]) {
// Allow to reimburse if funding was unsuccessful for this ruling option.
amount = round.contributions[_beneficiary][_choice];
} else {
// Funding was successful for this ruling option.
if (_choice == dispute.ruling) {
// This ruling option is the ultimate winner.
amount = round.paidFees[_choice] > 0
? (round.contributions[_beneficiary][_choice] * round.feeRewards) / round.paidFees[_choice]
: 0;
} else if (!round.hasPaid[dispute.ruling]) {
// The ultimate winner was not funded in this round. In this case funded ruling option(s) are reimbursed.
amount =
(round.contributions[_beneficiary][_choice] * round.feeRewards) /
(round.paidFees[round.fundedChoices[0]] + round.paidFees[round.fundedChoices[1]]);
}
}
round.contributions[_beneficiary][_choice] = 0;
if (amount != 0) {
_beneficiary.send(amount); // Deliberate use of send to prevent reverting fallback. It's the user's responsibility to accept ETH.
emit Withdrawal(_disputeID, _round, _choice, _beneficiary, amount);
}
}
// ************************ //
// * Getters * //
// ************************ //
/** @dev Cost of arbitration.
* @return fee The required amount.
*/
function arbitrationCost(
bytes calldata /*_extraData*/
) public view override returns (uint256 fee) {
return arbitrationFee;
}
/** @dev Return the funded amount and funding goal for one of the choices.
* @param _disputeID The ID of the dispute to appeal.
* @param _choice The choice to check the funding status of.
* @return funded The amount funded so far for this choice in wei.
* @return goal The amount to fully fund this choice in wei.
*/
function fundingStatus(uint256 _disputeID, uint256 _choice) external view returns (uint256 funded, uint256 goal) {
DisputeStruct storage dispute = disputes[_disputeID];
require(_choice <= dispute.choices, "There is no such ruling to fund.");
require(dispute.status == DisputeStatus.Appealable, "Dispute not appealable.");
if (dispute.ruling == _choice) {
goal = appealFee + (appealFee * WINNER_STAKE_MULTIPLIER) / MULTIPLIER_DIVISOR;
} else {
goal = appealFee + (appealFee * LOSER_STAKE_MULTIPLIER) / MULTIPLIER_DIVISOR;
}
Round[] storage rounds = disputeIDtoRoundArray[_disputeID];
Round storage lastRound = rounds[rounds.length - 1];
return (lastRound.paidFees[_choice], goal);
}
/** @dev Compute the start and end of the dispute's appeal period, if possible. If the dispute is not appealble return (0, 0).
* @param _disputeID ID of the dispute.
* @return start The start of the period.
* @return end The end of the period.
*/
function appealPeriod(uint256 _disputeID) public view returns (uint256 start, uint256 end) {
DisputeStruct storage dispute = disputes[_disputeID];
if (dispute.status == DisputeStatus.Appealable) {
start = dispute.appealPeriodStart;
end = start + appealDuration;
}
return (start, end);
}
}
|
Ruling given by the arbitrator.
|
uint256 ruling;
| 1,009,475 |
[
1,
54,
332,
310,
864,
635,
326,
10056,
86,
639,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
436,
332,
310,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IKeeperSubsidyPool.sol";
import "./interfaces/IUniswapRouterV2.sol";
import "./interfaces/IUniswapFactory.sol";
import "./interfaces/IUniswapV2Pair.sol";
import "./interfaces/IEToken.sol";
import "./interfaces/IEPoolPeriphery.sol";
import "./interfaces/IEPool.sol";
import "./utils/ControllerMixin.sol";
import "./utils/TokenUtils.sol";
import "./EPoolLibrary.sol";
import "hardhat/console.sol";
contract EPoolPeriphery is ControllerMixin, IEPoolPeriphery {
using SafeERC20 for IERC20;
using TokenUtils for IERC20;
using TokenUtils for IEToken;
IUniswapV2Factory public immutable override factory;
IUniswapV2Router01 public immutable override router;
// Keeper subsidy pool for making rebalancing via flash swaps capital neutral for msg.sender
IKeeperSubsidyPool public immutable override keeperSubsidyPool;
// supported EPools by the periphery
mapping(address => bool) public override ePools;
// max. allowed slippage between EPool oracle and uniswap when executing a flash swap
uint256 public override maxFlashSwapSlippage;
event IssuedEToken(
address indexed ePool, address indexed eToken, uint256 amount, uint256 amountA, uint256 amountB, address user
);
event RedeemedEToken(
address indexed ePool, address indexed eToken, uint256 amount, uint256 amountA, uint256 amountB, address user
);
event SetEPoolApproval(address indexed ePool, bool approval);
event SetMaxFlashSwapSlippage(uint256 maxFlashSwapSlippage);
event RecoveredToken(address token, uint256 amount);
/**
* @param _controller Address of the controller
* @param _factory Address of the Uniswap V2 factory
* @param _router Address of the Uniswap V2 router
* @param _keeperSubsidyPool Address of keeper subsidiy pool
* @param _maxFlashSwapSlippage Max. allowed slippage between EPool oracle and uniswap
*/
constructor(
IController _controller,
IUniswapV2Factory _factory,
IUniswapV2Router01 _router,
IKeeperSubsidyPool _keeperSubsidyPool,
uint256 _maxFlashSwapSlippage
) ControllerMixin(_controller) {
factory = _factory;
router = _router;
keeperSubsidyPool = _keeperSubsidyPool;
maxFlashSwapSlippage = _maxFlashSwapSlippage; // e.g. 1.05e18 -> 5% slippage
}
/**
* @notice Returns the address of the current Aggregator which provides the exchange rate between TokenA and TokenB
* @return Address of aggregator
*/
function getController() external view override returns (address) {
return address(controller);
}
/**
* @notice Updates the Controller
* @dev Can only called by an authorized sender
* @param _controller Address of the new Controller
* @return True on success
*/
function setController(address _controller) external override onlyDao("EPoolPeriphery: not dao") returns (bool) {
_setController(_controller);
return true;
}
/**
* @notice Give or revoke approval a EPool for the EPoolPeriphery
* @dev Can only called by the DAO or the guardian
* @param ePool Address of the EPool
* @param approval Boolean on whether approval for EPool should be given or revoked
* @return True on success
*/
function setEPoolApproval(
IEPool ePool,
bool approval
) external override onlyDaoOrGuardian("EPoolPeriphery: not dao or guardian") returns (bool) {
if (approval) {
// assuming EPoolPeriphery only holds funds within calls
ePool.tokenA().approve(address(ePool), type(uint256).max);
ePool.tokenB().approve(address(ePool), type(uint256).max);
ePools[address(ePool)] = true;
} else {
ePool.tokenA().approve(address(ePool), 0);
ePool.tokenB().approve(address(ePool), 0);
ePools[address(ePool)] = false;
}
emit SetEPoolApproval(address(ePool), approval);
return true;
}
/**
* @notice Set max. slippage between EPool oracle and uniswap when performing flash swap
* @dev Can only be callede by the DAO or the guardian
* @param _maxFlashSwapSlippage Max. flash swap slippage
* @return True on success
*/
function setMaxFlashSwapSlippage(
uint256 _maxFlashSwapSlippage
) external override onlyDaoOrGuardian("EPoolPeriphery: not dao or guardian") returns (bool) {
maxFlashSwapSlippage = _maxFlashSwapSlippage;
emit SetMaxFlashSwapSlippage(maxFlashSwapSlippage);
return true;
}
/**
* @notice Issues an amount of EToken for maximum amount of TokenA
* @dev Reverts if maxInputAmountA is exceeded. Unused amount of TokenA is refunded to msg.sender.
* Requires setting allowance for TokenA.
* @param ePool Address of the EPool
* @param eToken Address of the EToken of the tranche
* @param amount Amount of EToken to issue
* @param maxInputAmountA Max. amount of TokenA to deposit
* @param deadline Timestamp at which tx expires
* @return True on success
*/
function issueForMaxTokenA(
IEPool ePool,
address eToken,
uint256 amount,
uint256 maxInputAmountA,
uint256 deadline
) external override returns (bool) {
require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool");
(IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB());
tokenA.safeTransferFrom(msg.sender, address(this), maxInputAmountA);
IEPool.Tranche memory t = ePool.getTranche(eToken);
(uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken(
t, amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()
);
// swap part of input amount for amountB
require(maxInputAmountA >= amountA, "EPoolPeriphery: insufficient max. input");
uint256 amountAToSwap = maxInputAmountA - amountA;
address[] memory path = new address[](2);
path[0] = address(tokenA);
path[1] = address(tokenB);
tokenA.approve(address(router), amountAToSwap);
uint256[] memory amountsOut = router.swapTokensForExactTokens(
amountB, amountAToSwap, path, address(this), deadline
);
// do the deposit (TokenA is already approved)
ePool.issueExact(eToken, amount);
// transfer EToken to msg.sender
IERC20(eToken).safeTransfer(msg.sender, amount);
// refund unused maxInputAmountA -= amountA + amountASwappedForAmountB
tokenA.safeTransfer(msg.sender, maxInputAmountA - amountA - amountsOut[0]);
emit IssuedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender);
return true;
}
/**
* @notice Issues an amount of EToken for maximum amount of TokenB
* @dev Reverts if maxInputAmountB is exceeded. Unused amount of TokenB is refunded to msg.sender.
* Requires setting allowance for TokenB.
* @param ePool Address of the EPool
* @param eToken Address of the EToken of the tranche
* @param amount Amount of EToken to issue
* @param maxInputAmountB Max. amount of TokenB to deposit
* @param deadline Timestamp at which tx expires
* @return True on success
*/
function issueForMaxTokenB(
IEPool ePool,
address eToken,
uint256 amount,
uint256 maxInputAmountB,
uint256 deadline
) external override returns (bool) {
require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool");
(IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB());
tokenB.safeTransferFrom(msg.sender, address(this), maxInputAmountB);
IEPool.Tranche memory t = ePool.getTranche(eToken);
(uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken(
t, amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()
);
// swap part of input amount for amountB
require(maxInputAmountB >= amountB, "EPoolPeriphery: insufficient max. input");
uint256 amountBToSwap = maxInputAmountB - amountB;
address[] memory path = new address[](2);
path[0] = address(tokenB);
path[1] = address(tokenA);
tokenB.approve(address(router), amountBToSwap);
uint256[] memory amountsOut = router.swapTokensForExactTokens(
amountA, amountBToSwap, path, address(this), deadline
);
// do the deposit (TokenB is already approved)
ePool.issueExact(eToken, amount);
// transfer EToken to msg.sender
IERC20(eToken).safeTransfer(msg.sender, amount);
// refund unused maxInputAmountB -= amountB + amountBSwappedForAmountA
tokenB.safeTransfer(msg.sender, maxInputAmountB - amountB - amountsOut[0]);
emit IssuedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender);
return true;
}
/**
* @notice Redeems an amount of EToken for a min. amount of TokenA
* @dev Reverts if minOutputA is not met. Requires setting allowance for EToken
* @param ePool Address of the EPool
* @param eToken Address of the EToken of the tranche
* @param amount Amount of EToken to redeem
* @param minOutputA Min. amount of TokenA to withdraw
* @param deadline Timestamp at which tx expires
* @return True on success
*/
function redeemForMinTokenA(
IEPool ePool,
address eToken,
uint256 amount,
uint256 minOutputA,
uint256 deadline
) external override returns (bool) {
require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool");
(IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB());
IERC20(eToken).safeTransferFrom(msg.sender, address(this), amount);
// do the withdraw
IERC20(eToken).approve(address(ePool), amount);
(uint256 amountA, uint256 amountB) = ePool.redeemExact(eToken, amount);
// convert amountB withdrawn from EPool into TokenA
address[] memory path = new address[](2);
path[0] = address(tokenB);
path[1] = address(tokenA);
tokenB.approve(address(router), amountB);
uint256[] memory amountsOut = router.swapExactTokensForTokens(
amountB, 0, path, address(this), deadline
);
uint256 outputA = amountA + amountsOut[1];
require(outputA >= minOutputA, "EPoolPeriphery: insufficient output amount");
IERC20(tokenA).safeTransfer(msg.sender, outputA);
emit RedeemedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender);
return true;
}
/**
* @notice Redeems an amount of EToken for a min. amount of TokenB
* @dev Reverts if minOutputB is not met. Requires setting allowance for EToken
* @param ePool Address of the EPool
* @param eToken Address of the EToken of the tranche
* @param amount Amount of EToken to redeem
* @param minOutputB Min. amount of TokenB to withdraw
* @param deadline Timestamp at which tx expires
* @return True on success
*/
function redeemForMinTokenB(
IEPool ePool,
address eToken,
uint256 amount,
uint256 minOutputB,
uint256 deadline
) external override returns (bool) {
require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool");
(IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB());
IERC20(eToken).safeTransferFrom(msg.sender, address(this), amount);
// do the withdraw
IERC20(eToken).approve(address(ePool), amount);
(uint256 amountA, uint256 amountB) = ePool.redeemExact(eToken, amount);
// convert amountB withdrawn from EPool into TokenA
address[] memory path = new address[](2);
path[0] = address(tokenA);
path[1] = address(tokenB);
tokenA.approve(address(router), amountA);
uint256[] memory amountsOut = router.swapExactTokensForTokens(
amountA, 0, path, address(this), deadline
);
uint256 outputB = amountB + amountsOut[1];
require(outputB >= minOutputB, "EPoolPeriphery: insufficient output amount");
IERC20(tokenB).safeTransfer(msg.sender, outputB);
emit RedeemedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender);
return true;
}
/**
* @notice Rebalances a EPool. Capital required for rebalancing is obtained via a flash swap.
* The potential slippage between the EPool oracle and uniswap is covered by the KeeperSubsidyPool.
* @dev Fails if maxFlashSwapSlippage is exceeded in uniswapV2Call
* @param ePool Address of the EPool to rebalance
* @param fracDelta Fraction of the delta to rebalance (1e18 for rebalancing the entire delta)
* @return True on success
*/
function rebalanceWithFlashSwap(
IEPool ePool,
uint256 fracDelta
) external override returns (bool) {
require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool");
(address tokenA, address tokenB) = (address(ePool.tokenA()), address(ePool.tokenB()));
(uint256 deltaA, uint256 deltaB, uint256 rChange, ) = EPoolLibrary.delta(
ePool.getTranches(), ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()
);
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(address(tokenA), address(tokenB)));
// map deltaA, deltaB to amountOut0, amountOut1
uint256 amountOut0; uint256 amountOut1;
if (rChange == 0) {
(amountOut0, amountOut1) = (address(tokenA) == pair.token0())
? (uint256(0), deltaB) : (deltaB, uint256(0));
} else {
(amountOut0, amountOut1) = (address(tokenA) == pair.token0())
? (deltaA, uint256(0)) : (uint256(0), deltaA);
}
bytes memory data = abi.encode(ePool, fracDelta);
pair.swap(amountOut0, amountOut1, address(this), data);
return true;
}
/**
* @notice rebalanceAllWithFlashSwap callback called by the uniswap pair
* @dev Trusts that deltas are actually forwarded by the EPool.
* Verifies that funds are forwarded from flash swap of the uniswap pair.
* param sender Address of the flash swap initiator
* param amount0
* param amount1
* @param data Data forwarded in the flash swap
*/
function uniswapV2Call(
address /* sender */, // skip sender check, check for forwarded funds by flash swap is sufficient
uint256 /* amount0 */,
uint256 /* amount1 */,
bytes calldata data
) external {
(IEPool ePool, uint256 fracDelta) = abi.decode(data, (IEPool, uint256));
require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool");
// fails if no funds are forwarded in the flash swap callback from the uniswap pair
// TokenA, TokenB are already approved
(uint256 deltaA, uint256 deltaB, uint256 rChange, ) = ePool.rebalance(fracDelta);
address[] memory path = new address[](2); // [0] flash swap repay token, [1] flash lent token
uint256 amountsIn; // flash swap repay amount
uint256 deltaOut;
if (rChange == 0) {
// release TokenA, add TokenB to EPool -> flash swap TokenB, repay with TokenA
path[0] = address(ePool.tokenA()); path[1] = address(ePool.tokenB());
(amountsIn, deltaOut) = (router.getAmountsIn(deltaB, path)[0], deltaA);
} else {
// add TokenA, release TokenB to EPool -> flash swap TokenA, repay with TokenB
path[0] = address(ePool.tokenB()); path[1] = address(ePool.tokenA());
(amountsIn, deltaOut) = (router.getAmountsIn(deltaA, path)[0], deltaB);
}
// if slippage is negative request subsidy, if positive top of KeeperSubsidyPool
if (amountsIn > deltaOut) {
require(
amountsIn * EPoolLibrary.sFactorI / deltaOut <= maxFlashSwapSlippage,
"EPoolPeriphery: excessive slippage"
);
keeperSubsidyPool.requestSubsidy(path[0], amountsIn - deltaOut);
} else if (amountsIn < deltaOut) {
IERC20(path[0]).safeTransfer(address(keeperSubsidyPool), deltaOut - amountsIn);
}
// repay flash swap by sending amountIn to pair
IERC20(path[0]).safeTransfer(msg.sender, amountsIn);
}
/**
* @notice Recovers untracked amounts
* @dev Can only called by an authorized sender
* @param token Address of the token
* @param amount Amount to recover
* @return True on success
*/
function recover(IERC20 token, uint256 amount) external override onlyDao("EPool: not dao") returns (bool) {
token.safeTransfer(msg.sender, amount);
emit RecoveredToken(address(token), amount);
return true;
}
/* ------------------------------------------------------------------------------------------------------- */
/* view and pure methods */
/* ------------------------------------------------------------------------------------------------------- */
function minInputAmountAForEToken(
IEPool ePool,
address eToken,
uint256 amount
) external view returns (uint256 minTokenA) {
(uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken(
ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()
);
address[] memory path = new address[](2);
path[0] = address(ePool.tokenA());
path[1] = address(ePool.tokenB());
minTokenA = amountA + router.getAmountsIn(amountB, path)[0];
}
// does not include price impact, which would result in a smaller EToken amount
function eTokenForMinInputAmountA_Unsafe(
IEPool ePool,
address eToken,
uint256 minInputAmountA
) external view returns (uint256 amount) {
IEPool.Tranche memory t = ePool.getTranche(eToken);
uint256 rate = ePool.getRate();
uint256 sFactorA = ePool.sFactorA();
uint256 sFactorB = ePool.sFactorB();
uint256 ratio = EPoolLibrary.currentRatio(t, rate, sFactorA, sFactorB);
(uint256 amountAIdeal, uint256 amountBIdeal) = EPoolLibrary.tokenATokenBForTokenA(
minInputAmountA, ratio, rate, sFactorA, sFactorB
);
return EPoolLibrary.eTokenForTokenATokenB(t, amountAIdeal, amountBIdeal, rate, sFactorA, sFactorB);
}
function minInputAmountBForEToken(
IEPool ePool,
address eToken,
uint256 amount
) external view returns (uint256 minTokenB) {
(uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken(
ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()
);
address[] memory path = new address[](2);
path[0] = address(ePool.tokenB());
path[1] = address(ePool.tokenA());
minTokenB = amountB + router.getAmountsIn(amountA, path)[0];
}
// does not include price impact, which would result in a smaller EToken amount
function eTokenForMinInputAmountB_Unsafe(
IEPool ePool,
address eToken,
uint256 minInputAmountB
) external view returns (uint256 amount) {
IEPool.Tranche memory t = ePool.getTranche(eToken);
uint256 rate = ePool.getRate();
uint256 sFactorA = ePool.sFactorA();
uint256 sFactorB = ePool.sFactorB();
uint256 ratio = EPoolLibrary.currentRatio(t, rate, sFactorA, sFactorB);
(uint256 amountAIdeal, uint256 amountBIdeal) = EPoolLibrary.tokenATokenBForTokenB(
minInputAmountB, ratio, rate, sFactorA, sFactorB
);
return EPoolLibrary.eTokenForTokenATokenB(t, amountAIdeal, amountBIdeal, rate, sFactorA, sFactorB);
}
function maxOutputAmountAForEToken(
IEPool ePool,
address eToken,
uint256 amount
) external view returns (uint256 maxTokenA) {
(uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken(
ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()
);
uint256 feeRate = ePool.feeRate();
amountA = amountA - amountA * feeRate / EPoolLibrary.sFactorI;
amountB = amountB - amountB * feeRate / EPoolLibrary.sFactorI;
address[] memory path = new address[](2);
path[0] = address(ePool.tokenB());
path[1] = address(ePool.tokenA());
maxTokenA = amountA + router.getAmountsOut(amountB, path)[1];
}
function maxOutputAmountBForEToken(
IEPool ePool,
address eToken,
uint256 amount
) external view returns (uint256 maxTokenB) {
(uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken(
ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB()
);
uint256 feeRate = ePool.feeRate();
amountA = amountA - amountA * feeRate / EPoolLibrary.sFactorI;
amountB = amountB - amountB * feeRate / EPoolLibrary.sFactorI;
address[] memory path = new address[](2);
path[0] = address(ePool.tokenA());
path[1] = address(ePool.tokenB());
maxTokenB = amountB + router.getAmountsOut(amountA, path)[1];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// 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: Apache-2.0
pragma solidity ^0.8.1;
pragma experimental ABIEncoderV2;
interface IKeeperSubsidyPool {
function getController() external view returns (address);
function setController(address _controller) external returns (bool);
function setBeneficiary(address beneficiary, bool canRequest) external returns (bool);
function isBeneficiary(address beneficiary) external view returns (bool);
function requestSubsidy(address token, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: GNU
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);
}
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: GNU
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed tokenA, address pair, uint);
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 feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
// SPDX-License-Identifier: GNU
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 amountA);
event Burn(address indexed sender, uint amount0, uint amountA, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amountAIn,
uint amount0Out,
uint amountAOut,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserveA);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function tokenA() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserveA, 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 amountA);
function swap(uint amount0Out, uint amountAOut, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IEToken is IERC20 {
function getController() external view returns (address);
function setController(address _controller) external returns (bool);
function mint(address account, uint256 amount) external returns (bool);
function burn(address account, uint256 amount) external returns (bool);
function recover(IERC20 token, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
pragma experimental ABIEncoderV2;
import "./IKeeperSubsidyPool.sol";
import "./IUniswapRouterV2.sol";
import "./IUniswapFactory.sol";
import "./IEPool.sol";
interface IEPoolPeriphery {
function getController() external view returns (address);
function setController(address _controller) external returns (bool);
function factory() external view returns (IUniswapV2Factory);
function router() external view returns (IUniswapV2Router01);
function ePools(address) external view returns (bool);
function keeperSubsidyPool() external view returns (IKeeperSubsidyPool);
function maxFlashSwapSlippage() external view returns (uint256);
function setEPoolApproval(IEPool ePool, bool approval) external returns (bool);
function setMaxFlashSwapSlippage(uint256 _maxFlashSwapSlippage) external returns (bool);
function issueForMaxTokenA(
IEPool ePool,
address eToken,
uint256 amount,
uint256 maxInputAmountA,
uint256 deadline
) external returns (bool);
function issueForMaxTokenB(
IEPool ePool,
address eToken,
uint256 amount,
uint256 maxInputAmountB,
uint256 deadline
) external returns (bool);
function redeemForMinTokenA(
IEPool ePool,
address eToken,
uint256 amount,
uint256 minOutputA,
uint256 deadline
) external returns (bool);
function redeemForMinTokenB(
IEPool ePool,
address eToken,
uint256 amount,
uint256 minOutputB,
uint256 deadline
) external returns (bool);
function rebalanceWithFlashSwap(IEPool ePool, uint256 fracDelta) external returns (bool);
function recover(IERC20 token, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IEToken.sol";
interface IEPool {
struct Tranche {
IEToken eToken;
uint256 sFactorE;
uint256 reserveA;
uint256 reserveB;
uint256 targetRatio;
}
function getController() external view returns (address);
function setController(address _controller) external returns (bool);
function tokenA() external view returns (IERC20);
function tokenB() external view returns (IERC20);
function sFactorA() external view returns (uint256);
function sFactorB() external view returns (uint256);
function getTranche(address eToken) external view returns (Tranche memory);
function getTranches() external view returns(Tranche[] memory _tranches);
function addTranche(uint256 targetRatio, string memory eTokenName, string memory eTokenSymbol) external returns (bool);
function getAggregator() external view returns (address);
function setAggregator(address oracle, bool inverseRate) external returns (bool);
function rebalanceMinRDiv() external view returns (uint256);
function rebalanceInterval() external view returns (uint256);
function lastRebalance() external view returns (uint256);
function feeRate() external view returns (uint256);
function cumulativeFeeA() external view returns (uint256);
function cumulativeFeeB() external view returns (uint256);
function setFeeRate(uint256 _feeRate) external returns (bool);
function transferFees() external returns (bool);
function getRate() external view returns (uint256);
function rebalance(uint256 fracDelta) external returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv);
function issueExact(address eToken, uint256 amount) external returns (uint256 amountA, uint256 amountB);
function redeemExact(address eToken, uint256 amount) external returns (uint256 amountA, uint256 amountB);
function recover(IERC20 token, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
import "../interfaces/IController.sol";
contract ControllerMixin {
event SetController(address controller);
IController internal controller;
constructor(IController _controller) {
controller = _controller;
}
modifier onlyDao(string memory revertMsg) {
require(msg.sender == controller.dao(), revertMsg);
_;
}
modifier onlyDaoOrGuardian(string memory revertMsg) {
require(controller.isDaoOrGuardian(msg.sender), revertMsg);
_;
}
modifier issuanceNotPaused(string memory revertMsg) {
require(controller.pausedIssuance() == false, revertMsg);
_;
}
function _setController(address _controller) internal {
controller = IController(_controller);
emit SetController(_controller);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IERC20Optional.sol";
library TokenUtils {
function decimals(IERC20 token) internal view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSignature("decimals()"));
require(success, "TokenUtils: no decimals");
uint8 _decimals = abi.decode(data, (uint8));
return _decimals;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IETokenFactory.sol";
import "./interfaces/IEToken.sol";
import "./interfaces/IEPool.sol";
import "./utils/TokenUtils.sol";
import "./utils/Math.sol";
library EPoolLibrary {
using TokenUtils for IERC20;
uint256 internal constant sFactorI = 1e18; // internal scaling factor (18 decimals)
/**
* @notice Returns the target ratio if reserveA and reserveB are 0 (for initial deposit)
* currentRatio := (reserveA denominated in tokenB / reserveB denominated in tokenB) with decI decimals
*/
function currentRatio(
IEPool.Tranche memory t,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns(uint256) {
if (t.reserveA == 0 || t.reserveB == 0) {
if (t.reserveA == 0 && t.reserveB == 0) return t.targetRatio;
if (t.reserveA == 0) return 0;
if (t.reserveB == 0) return type(uint256).max;
}
return ((t.reserveA * rate / sFactorA) * sFactorI) / (t.reserveB * sFactorI / sFactorB);
}
/**
* @notice Returns the deviation of reserveA and reserveB from target ratio
* currentRatio > targetRatio: release TokenA liquidity and add TokenB liquidity
* currentRatio < targetRatio: add TokenA liquidity and release TokenB liquidity
* deltaA := abs(t.reserveA, (t.reserveB / rate * t.targetRatio)) / (1 + t.targetRatio)
* deltaB := deltaA * rate
*/
function trancheDelta(
IEPool.Tranche memory t,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange) {
rChange = (currentRatio(t, rate, sFactorA, sFactorB) < t.targetRatio) ? 1 : 0;
deltaA = (
Math.abs(t.reserveA, tokenAForTokenB(t.reserveB, t.targetRatio, rate, sFactorA, sFactorB)) * sFactorA
) / (sFactorA + (t.targetRatio * sFactorA / sFactorI));
// (convert to TokenB precision first to avoid altering deltaA)
deltaB = ((deltaA * sFactorB / sFactorA) * rate) / sFactorI;
}
/**
* @notice Returns the sum of the tranches reserve deltas
*/
function delta(
IEPool.Tranche[] memory ts,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv) {
uint256 totalReserveA;
int256 totalDeltaA;
int256 totalDeltaB;
for (uint256 i = 0; i < ts.length; i++) {
totalReserveA += ts[i].reserveA;
(uint256 _deltaA, uint256 _deltaB, uint256 _rChange) = trancheDelta(
ts[i], rate, sFactorA, sFactorB
);
(totalDeltaA, totalDeltaB) = (_rChange == 0)
? (totalDeltaA - int256(_deltaA), totalDeltaB + int256(_deltaB))
: (totalDeltaA + int256(_deltaA), totalDeltaB - int256(_deltaB));
}
if (totalDeltaA > 0) {
(deltaA, deltaB, rChange) = (uint256(totalDeltaA), uint256(-totalDeltaB), 1);
} else {
(deltaA, deltaB, rChange) = (uint256(-totalDeltaA), uint256(totalDeltaB), 0);
}
rDiv = (totalReserveA == 0) ? 0 : deltaA * EPoolLibrary.sFactorI / totalReserveA;
}
/**
* @notice how much EToken can be issued, redeemed for amountA and amountB
* initial issuance / last redemption: sqrt(amountA * amountB)
* subsequent issuances / non nullifying redemptions: claim on reserve * EToken total supply
*/
function eTokenForTokenATokenB(
IEPool.Tranche memory t,
uint256 amountA,
uint256 amountB,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal view returns (uint256) {
uint256 amountsA = totalA(amountA, amountB, rate, sFactorA, sFactorB);
if (t.reserveA + t.reserveB == 0) {
return (Math.sqrt((amountsA * t.sFactorE / sFactorA) * t.sFactorE));
}
uint256 reservesA = totalA(t.reserveA, t.reserveB, rate, sFactorA, sFactorB);
uint256 share = ((amountsA * t.sFactorE / sFactorA) * t.sFactorE) / (reservesA * t.sFactorE / sFactorA);
return share * t.eToken.totalSupply() / t.sFactorE;
}
/**
* @notice Given an amount of EToken, how much TokenA and TokenB have to be deposited, withdrawn for it
* initial issuance / last redemption: sqrt(amountA * amountB) -> such that the inverse := EToken amount ** 2
* subsequent issuances / non nullifying redemptions: claim on EToken supply * reserveA/B
*/
function tokenATokenBForEToken(
IEPool.Tranche memory t,
uint256 amount,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal view returns (uint256 amountA, uint256 amountB) {
if (t.reserveA + t.reserveB == 0) {
uint256 amountsA = amount * sFactorA / t.sFactorE;
(amountA, amountB) = tokenATokenBForTokenA(
amountsA * amountsA / sFactorA , t.targetRatio, rate, sFactorA, sFactorB
);
} else {
uint256 eTokenTotalSupply = t.eToken.totalSupply();
if (eTokenTotalSupply == 0) return(0, 0);
uint256 share = amount * t.sFactorE / eTokenTotalSupply;
amountA = share * t.reserveA / t.sFactorE;
amountB = share * t.reserveB / t.sFactorE;
}
}
/**
* @notice Given amountB, which amountA is required such that amountB / amountA is equal to the ratio
* amountA := amountBInTokenA * ratio
*/
function tokenAForTokenB(
uint256 amountB,
uint256 ratio,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns(uint256) {
return (((amountB * sFactorI / sFactorB) * ratio) / rate) * sFactorA / sFactorI;
}
/**
* @notice Given amountA, which amountB is required such that amountB / amountA is equal to the ratio
* amountB := amountAInTokenB / ratio
*/
function tokenBForTokenA(
uint256 amountA,
uint256 ratio,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns(uint256) {
return (((amountA * sFactorI / sFactorA) * rate) / ratio) * sFactorB / sFactorI;
}
/**
* @notice Given an amount of TokenA, how can it be split up proportionally into amountA and amountB
* according to the ratio
* amountA := total - (total / (1 + ratio)) == (total * ratio) / (1 + ratio)
* amountB := (total / (1 + ratio)) * rate
*/
function tokenATokenBForTokenA(
uint256 _totalA,
uint256 ratio,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 amountA, uint256 amountB) {
amountA = _totalA - (_totalA * sFactorI / (sFactorI + ratio));
amountB = (((_totalA * sFactorI / sFactorA) * rate) / (sFactorI + ratio)) * sFactorB / sFactorI;
}
/**
* @notice Given an amount of TokenB, how can it be split up proportionally into amountA and amountB
* according to the ratio
* amountA := (total * ratio) / (rate * (1 + ratio))
* amountB := total / (1 + ratio)
*/
function tokenATokenBForTokenB(
uint256 _totalB,
uint256 ratio,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 amountA, uint256 amountB) {
amountA = ((((_totalB * sFactorI / sFactorB) * ratio) / (sFactorI + ratio)) * sFactorA) / rate;
amountB = (_totalB * sFactorI) / (sFactorI + ratio);
}
/**
* @notice Return the total value of amountA and amountB denominated in TokenA
* totalA := amountA + (amountB / rate)
*/
function totalA(
uint256 amountA,
uint256 amountB,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 _totalA) {
return amountA + ((((amountB * sFactorI / sFactorB) * sFactorI) / rate) * sFactorA) / sFactorI;
}
/**
* @notice Return the total value of amountA and amountB denominated in TokenB
* totalB := amountB + (amountA * rate)
*/
function totalB(
uint256 amountA,
uint256 amountB,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 _totalB) {
return amountB + ((amountA * rate / sFactorA) * sFactorB) / sFactorI;
}
/**
* @notice Return the withdrawal fee for a given amount of TokenA and TokenB
* feeA := amountA * feeRate
* feeB := amountB * feeRate
*/
function feeAFeeBForTokenATokenB(
uint256 amountA,
uint256 amountB,
uint256 feeRate
) internal pure returns (uint256 feeA, uint256 feeB) {
feeA = amountA * feeRate / EPoolLibrary.sFactorI;
feeB = amountB * feeRate / EPoolLibrary.sFactorI;
}
}
// 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
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;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
pragma experimental ABIEncoderV2;
interface IController {
function dao() external view returns (address);
function guardian() external view returns (address);
function isDaoOrGuardian(address sender) external view returns (bool);
function setDao(address _dao) external returns (bool);
function setGuardian(address _guardian) external returns (bool);
function feesOwner() external view returns (address);
function pausedIssuance() external view returns (bool);
function setFeesOwner(address _feesOwner) external returns (bool);
function setPausedIssuance(bool _pausedIssuance) external returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
/**
* @dev Interface of the the optional methods of the ERC20 standard as defined in the EIP.
*/
interface IERC20Optional {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.1;
import "./IEToken.sol";
interface IETokenFactory {
function getController() external view returns (address);
function setController(address _controller) external returns (bool);
function createEToken(string memory name, string memory symbol) external returns (IEToken);
}
// SPDX-License-Identifier: GNU
pragma solidity ^0.8.1;
library Math {
function abs(uint256 a, uint256 b) internal pure returns (uint256) {
return (a > b) ? a - b : b - a;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
|
* @notice Return the total value of amountA and amountB denominated in TokenB totalB := amountB + (amountA rate)/
|
function totalB(
uint256 amountA,
uint256 amountB,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 _totalB) {
return amountB + ((amountA * rate / sFactorA) * sFactorB) / sFactorI;
}
| 1,224,830 |
[
1,
990,
326,
2078,
460,
434,
3844,
37,
471,
3844,
38,
10716,
7458,
316,
3155,
38,
2078,
38,
519,
3844,
38,
397,
261,
8949,
37,
225,
4993,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2078,
38,
12,
203,
3639,
2254,
5034,
3844,
37,
16,
203,
3639,
2254,
5034,
3844,
38,
16,
203,
3639,
2254,
5034,
4993,
16,
203,
3639,
2254,
5034,
272,
6837,
37,
16,
203,
3639,
2254,
5034,
272,
6837,
38,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
5034,
389,
4963,
38,
13,
288,
203,
3639,
327,
3844,
38,
397,
14015,
8949,
37,
380,
4993,
342,
272,
6837,
37,
13,
380,
272,
6837,
38,
13,
342,
272,
6837,
45,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
website: cityswap.io
██████╗ ██╗██╗ ██╗ █████╗ ██████╗ ██╗ ██╗ ██████╗██╗████████╗██╗ ██╗
██╔══██╗██║╚██╗ ██╔╝██╔══██╗██╔══██╗██║ ██║ ██╔════╝██║╚══██╔══╝╚██╗ ██╔╝
██████╔╝██║ ╚████╔╝ ███████║██║ ██║███████║ ██║ ██║ ██║ ╚████╔╝
██╔══██╗██║ ╚██╔╝ ██╔══██║██║ ██║██╔══██║ ██║ ██║ ██║ ╚██╔╝
██║ ██║██║ ██║ ██║ ██║██████╔╝██║ ██║ ╚██████╗██║ ██║ ██║
╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝
*/
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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");
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// CityToken with Governance.
contract RiyadhCityToken is ERC20("RIYADH.cityswap.io", "RIYADH"), Ownable {
uint256 public constant MAX_SUPPLY = 5041000 * 10**18;
/**
* @notice Creates `_amount` token to `_to`. Must only be called by the owner (TravelAgency).
*/
function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _totalSupply = totalSupply();
if(_totalSupply.add(_amount) > MAX_SUPPLY) {
_amount = MAX_SUPPLY.sub(_totalSupply);
}
require(_totalSupply.add(_amount) <= MAX_SUPPLY);
_mint(_to, _amount);
}
}
contract RiyadhAgency is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of CITYs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCityPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accCityPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CITYs to distribute per block.
uint256 lastRewardBlock; // Last block number that CITYs distribution occurs.
uint256 accCityPerShare; // Accumulated CITYs per share, times 1e12. See below.
}
// The CITY TOKEN!
RiyadhCityToken public city;
// Dev address.
address public devaddr;
// Block number when bonus CITY period ends.
uint256 public bonusEndBlock;
// CITY tokens created per block.
uint256 public cityPerBlock;
// Bonus muliplier for early city travels.
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when CITY mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
RiyadhCityToken _city,
address _devaddr,
uint256 _cityPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
city = _city;
devaddr = _devaddr;
cityPerBlock = _cityPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCityPerShare: 0
}));
}
// Update the given pool's CITY allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending CITYs on frontend.
function pendingCity(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCityPerShare = pool.accCityPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cityReward = multiplier.mul(cityPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCityPerShare = accCityPerShare.add(cityReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCityPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function mint(uint256 amount) public onlyOwner{
city.mint(devaddr, amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cityReward = multiplier.mul(cityPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
city.mint(devaddr, cityReward.div(20)); // 5%
city.mint(address(this), cityReward);
pool.accCityPerShare = pool.accCityPerShare.add(cityReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to TravelAgency for CITY allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCityPerShare).div(1e12).sub(user.rewardDebt);
safeCityTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accCityPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCityPerShare).div(1e12).sub(user.rewardDebt);
safeCityTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accCityPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe city transfer function, just in case if rounding error causes pool to not have enough CITYs.
function safeCityTransfer(address _to, uint256 _amount) internal {
uint256 cityBal = city.balanceOf(address(this));
if (_amount > cityBal) {
city.transfer(_to, cityBal);
} else {
city.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
CityToken with Governance.
|
contract RiyadhCityToken is ERC20("RIYADH.cityswap.io", "RIYADH"), Ownable {
uint256 public constant MAX_SUPPLY = 5041000 * 10**18;
function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _totalSupply = totalSupply();
if(_totalSupply.add(_amount) > MAX_SUPPLY) {
_amount = MAX_SUPPLY.sub(_totalSupply);
}
require(_totalSupply.add(_amount) <= MAX_SUPPLY);
_mint(_to, _amount);
}
function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _totalSupply = totalSupply();
if(_totalSupply.add(_amount) > MAX_SUPPLY) {
_amount = MAX_SUPPLY.sub(_totalSupply);
}
require(_totalSupply.add(_amount) <= MAX_SUPPLY);
_mint(_to, _amount);
}
}
| 2,175,548 |
[
1,
22236,
1345,
598,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
21688,
93,
361,
76,
22236,
1345,
353,
4232,
39,
3462,
2932,
2259,
61,
1880,
44,
18,
14240,
22270,
18,
1594,
3113,
315,
2259,
61,
1880,
44,
6,
3631,
14223,
6914,
288,
203,
377,
203,
565,
2254,
5034,
1071,
5381,
4552,
67,
13272,
23893,
273,
1381,
3028,
18088,
380,
1728,
636,
2643,
31,
203,
540,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
389,
4963,
3088,
1283,
273,
2078,
3088,
1283,
5621,
203,
540,
203,
3639,
309,
24899,
4963,
3088,
1283,
18,
1289,
24899,
8949,
13,
405,
4552,
67,
13272,
23893,
13,
288,
203,
5411,
389,
8949,
273,
4552,
67,
13272,
23893,
18,
1717,
24899,
4963,
3088,
1283,
1769,
203,
3639,
289,
203,
203,
3639,
2583,
24899,
4963,
3088,
1283,
18,
1289,
24899,
8949,
13,
1648,
4552,
67,
13272,
23893,
1769,
203,
540,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
389,
4963,
3088,
1283,
273,
2078,
3088,
1283,
5621,
203,
540,
203,
3639,
309,
24899,
4963,
3088,
1283,
18,
1289,
24899,
8949,
13,
405,
4552,
67,
13272,
23893,
13,
288,
203,
5411,
389,
8949,
273,
4552,
67,
13272,
23893,
18,
1717,
24899,
4963,
3088,
1283,
1769,
203,
3639,
289,
203,
203,
3639,
2583,
24899,
4963,
3088,
1283,
18,
1289,
24899,
8949,
13,
1648,
4552,
67,
13272,
23893,
1769,
203,
2
] |
pragma solidity 0.5.16;
import "openzeppelin-solidity-2.3.0/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol";
import "./BankConfig.sol";
import "./GoblinConfig.sol";
interface InterestModel {
/// @dev Return the interest rate per second, using 1e18 as denom.
function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256);
}
contract TripleSlopeModel {
using SafeMath for uint256;
/// @dev Return the interest rate per second, using 1e18 as denom.
function getInterestRate(uint256 debt, uint256 floating) external pure returns (uint256) {
uint256 total = debt.add(floating);
uint256 utilization = debt.mul(10000).div(total);
if (utilization < 5000) {
// Less than 50% utilization - 10% APY
return uint256(10e16) / 365 days;
} else if (utilization < 9500) {
// Between 50% and 95% - 10%-25% APY
return (10e16 + utilization.sub(5000).mul(15e16).div(10000)) / 365 days;
} else if (utilization < 10000) {
// Between 95% and 100% - 25%-100% APY
return (25e16 + utilization.sub(7500).mul(75e16).div(10000)) / 365 days;
} else {
// Not possible, but just in case - 100% APY
return uint256(100e16) / 365 days;
}
}
}
contract ConfigurableInterestBankConfig is BankConfig, Ownable {
/// The minimum ETH debt size per position.
uint256 public minDebtSize;
/// The portion of interests allocated to the reserve pool.
uint256 public getReservePoolBps;
/// The reward for successfully killing a position.
uint256 public getKillBps;
/// Mapping for goblin address to its configuration.
mapping (address => GoblinConfig) public goblins;
/// Interest rate model
InterestModel public interestModel;
constructor(
uint256 _minDebtSize,
uint256 _reservePoolBps,
uint256 _killBps,
InterestModel _interestModel
) public {
setParams(_minDebtSize, _reservePoolBps, _killBps, _interestModel);
}
/// @dev Set all the basic parameters. Must only be called by the owner.
/// @param _minDebtSize The new minimum debt size value.
/// @param _reservePoolBps The new interests allocated to the reserve pool value.
/// @param _killBps The new reward for killing a position value.
/// @param _interestModel The new interest rate model contract.
function setParams(
uint256 _minDebtSize,
uint256 _reservePoolBps,
uint256 _killBps,
InterestModel _interestModel
) public onlyOwner {
minDebtSize = _minDebtSize;
getReservePoolBps = _reservePoolBps;
getKillBps = _killBps;
interestModel = _interestModel;
}
/// @dev Set the configuration for the given goblins. Must only be called by the owner.
function setGoblins(address[] calldata addrs, GoblinConfig[] calldata configs) external onlyOwner {
require(addrs.length == configs.length, "bad length");
for (uint256 idx = 0; idx < addrs.length; idx++) {
goblins[addrs[idx]] = configs[idx];
}
}
/// @dev Return the interest rate per second, using 1e18 as denom.
function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256) {
return interestModel.getInterestRate(debt, floating);
}
/// @dev Return whether the given address is a goblin.
function isGoblin(address goblin) external view returns (bool) {
return address(goblins[goblin]) != address(0);
}
/// @dev Return whether the given goblin accepts more debt. Revert on non-goblin.
function acceptDebt(address goblin) external view returns (bool) {
return goblins[goblin].acceptDebt(goblin);
}
/// @dev Return the work factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin.
function workFactor(address goblin, uint256 debt) external view returns (uint256) {
return goblins[goblin].workFactor(goblin, debt);
}
/// @dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin.
function killFactor(address goblin, uint256 debt) external view returns (uint256) {
return goblins[goblin].killFactor(goblin, debt);
}
}
|
@dev Return the kill factor for the goblin + ETH debt, using 1e4 as denom. Revert on non-goblin.
|
function killFactor(address goblin, uint256 debt) external view returns (uint256) {
return goblins[goblin].killFactor(goblin, debt);
}
| 952,242 |
[
1,
990,
326,
8673,
5578,
364,
326,
20062,
7511,
397,
512,
2455,
18202,
88,
16,
1450,
404,
73,
24,
487,
10716,
18,
868,
1097,
603,
1661,
17,
75,
947,
7511,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
8673,
6837,
12,
2867,
20062,
7511,
16,
2254,
5034,
18202,
88,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
20062,
80,
2679,
63,
75,
947,
7511,
8009,
16418,
6837,
12,
75,
947,
7511,
16,
18202,
88,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
// todo: allow participants to be able to withdraw supported tokens if softcap not reached
// todo: allow participants to contribute other ethereum based cryptocurrency with approve function
// todo: then allow them to notify contract of approval
// todo: create a way to buy tokens using ether, update totalAllowed and specific phase allowed.
// todo: Also update totalContributions with amount of wei
// For safe math operations
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
assert(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
assert(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// sets owner of contract, allows for ownership transfer
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner, "Only Owner Can Use This Function");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// basic token implementation, with only required functions
interface token{
function approve(address _spender, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint _tokens) external returns (bool success);
function transfer(address _to, uint _value)external returns (bool success);
function balanceOf(address tokenOwner) external view returns (uint balance);
}
// basic Crowdsale contract
contract Crowdsale{
using SafeMath for uint;
// wallet in which ether will be sent to
address public organizationWallet;
// token to be used fo reward
token public tokenForReward;
// name of tokenForReward
string public nameOfTokenForReward;
// How many token units a buyer gets per wei
uint24 public ratePer;
// amount raised in wei
uint public weiRaised;
// event logging purchase of token
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);
modifier isNotNullAddress{
require(tokenForReward != address(0));
_;
}
modifier isNotNullWallet{
require(organizationWallet != address(0));
_;
}
function etherRaised() public view returns(uint){
return weiRaised / 1 ether;
}
}
contract AdvancedCrowdsale is Crowdsale, Owned{
bool public isPaused; // if crowdsale is paused
bool public isStarted; // if crowdsale has started
bool public isEnded; // if crowdsale has ended
uint8 public phase; // phase of sale
uint public rewardTokensAvailable ; // reduces with every purchase
uint public tokensApprovedForReward; // constant amount after funding
uint public minimumPurchase; // minimum purchase amount in wei. if 0 then no minimum
uint public maximumPurchase; // maximum purchase amount in wei. if 0 then no maximum
bool public refundAllowed; // if refund is allowed,
// add to functions which should only execute if sale is on
modifier saleIsOn{
require(isStarted && !isEnded && !isPaused, "Sale Not Started, Paused Or Completed");
_;
}
// add to functions which should only execute when sale is paused
modifier onlyWhenPaused{
if(!isPaused && isStarted) revert();
_;
}
// returns if crowdsale is accepting purchase
function isAcceptingPurchase() public view returns(bool){
return (isStarted && !isEnded && !isPaused);
}
// returns if crowdsale has been completed
function isCompleted() public view returns(bool){
return (isEnded&&isStarted); // if isStarted is True and isEnded is True then sale completed
}
// used by owner to pause or unpause sale
function onlyOwnerPauseOrUnpause() public onlyOwner{
require(isStarted&&!isEnded, "sale has not started");
if(isPaused){
isPaused = false;
}else{
isPaused = true;
}
}
//used by owner to end sale
function onlyOwnerEndSale() public onlyOwner{
require(!isEnded);
isEnded = true;
}
// used by owner to change organizationWallet
function onlyOwnerChangeOrgWallet(address _wallet) public onlyOwner{
require(_wallet != address(0));
organizationWallet = _wallet;
}
// used by owner to set a token for reward, if not set during deployment
function onlyOwnerSetTokenForReward(address _tokenAddress) public onlyOwner onlyWhenPaused{
require(isContract(_tokenAddress)); // address must be a contract
// check balance of previous tokenForReward and transfer back to owner
if (tokenForReward != address(0)){
uint balance = tokenForReward.balanceOf(address(this));
if(balance > 0){
tokenForReward.transfer(owner, balance);
}
}
// set rewardTokensAvailable and tokensApprovedForReward back to zero
// set tokenForReward to new token address
rewardTokensAvailable = 0;
tokensApprovedForReward = 0;
tokenForReward = token(_tokenAddress);
}
// used by owner to set name of token
function onlyOwnerSetTokenRewardName(string _name) public onlyOwner isNotNullAddress{
nameOfTokenForReward = _name;
}
// used by owner to start sale
function onlyOwnerStartSale() public onlyOwner{
require(!isEnded&&!isStarted);
require(tokenForReward != address(0), "set a token to use for reward");
require(tokensApprovedForReward > 0, "must send tokens to crowdsale using approveAndCall");
phase = 1;
isStarted = true;
isPaused = false;
}
// set minimum purchase turned into ether equivalent. 100 == 1 ether
// 10 equals 0.10 ether and so on
function onlyOwnerSetMinimum(uint _minimum)public onlyOwner onlyWhenPaused{
if(_minimum == 0){
require(minimumPurchase != 0);
minimumPurchase = 0;
}else{
uint minimumAmount = _minimum * 1 ether;
minimumPurchase = minimumAmount / 100;
require(minimumPurchase < maximumPurchase || maximumPurchase == 0); // minimum must be greater than max or max unlimited
}
}
// set maximum purchase turned into ether equivalent. 100 == 1 ether
// 10 equals 0.10 ether and so on
function onlyOwnerSetMaximum(uint _maximum)public onlyOwner onlyWhenPaused{
if(_maximum == 0){
require(maximumPurchase != 0, "Already set to zero");
maximumPurchase = _maximum; // sets to zero == no maximum, if you would like to remove individual caps
}else{
uint maximumAmount = _maximum * 1 ether;
maximumPurchase = maximumAmount / 100;
require(maximumPurchase > minimumPurchase);
}
}
// used to change rate of tokens per ether
function onlyOwnerChangeRate(uint24 _rate)public onlyOwner onlyWhenPaused returns (bool success){
ratePer = _rate;
return true;
}
// change the phase
function onlyOwnerChangePhase(uint8 _phase) public onlyOwner onlyWhenPaused returns (bool success){
phase = _phase;
return true;
}
function onlyOwnerChangeWallet(address _newWallet) public onlyOwner onlyWhenPaused returns(bool success){
require(!isContract(_newWallet));
organizationWallet = _newWallet;
return true;
}
// use to approve refund or revoke approval
function onlyOwnerApproveRefund() public onlyOwner returns(bool) {
require(isCompleted());
if (refundAllowed == false){
refundAllowed = true;
}else{
refundAllowed = false;
}
}
// withdraw ether raised to Organization Wallet
function onlyOwnerWithdraw() public onlyOwner returns (bool){
require(isCompleted());
// get ether balance
uint amount = address(this).balance;
require(amount > 0, "No Ether In contract");
// transfer balance of ether to Organization's Wallet
organizationWallet.transfer(amount);
return true;
}
// function used to check if address is a contract
function isContract(address _addr) internal view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
}
contract OPresale is AdvancedCrowdsale{
mapping(address => bool) public whitelist; // mapping of whitelisted addresses
mapping(uint8 => mapping(address => uint)) public allowed; // allowed is divided in phases, this can be used to lock tokens
mapping(address => uint) public totalContributions; // used if refund required. stores total contribution of an address
mapping(address => uint)totalAllowed; // used if refund required. stores total tokens to receive of an address
mapping(uint8 => bool)phaseAbleToWithdraw; // if phase is able to withdraw
mapping(address => bool) notAbleToGetRefund; //
uint public softcap; // minimum to raise in ether
event OPresaleFunded(address indexed _funder, uint _amount,address indexed _rewardToken, bytes _data); // log when contract is funded
event TokensWithdrawn(address indexed _backer, address indexed _beneficiary, uint _amount); // emitted when participant withdraws token
event OPresaleDefunded(address indexed _funder, uint _amount,address indexed _rewardToken); // log when contract is funded
event RefundSent(address indexed _receiver, uint _amount);
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary], "address not whitelisted");
_;
}
modifier onlySoftcapReached(){
require(weiRaised >= softcap, "softcap not reached");
_;
}
constructor(address _orgWallet, address _tokenAddress, uint24 _rate, uint _softcap) public{
isPaused = true; // if sale is paused
isStarted = false; // if sale has started
isEnded = false; // if sale has ended
organizationWallet = address(_orgWallet); // beneficiary wallet
tokenForReward = token(_tokenAddress); // the address for the token being offered
ratePer = _rate; // reward token per ether
softcap = _softcap * 1 ether; // softcap is sent in ether, this converts to wei
}
// called when sent spending approval using approveAndCall() of token
function receiveApproval(address _from, uint _tokens, address _theToken, bytes _data) public{
require(address(tokenForReward) == address(_theToken));
require(address(_from) == owner, "must be funded by owner");
require(tokensApprovedForReward == 0 && _tokens > 0);
// sets the total tokens available
tokensApprovedForReward = _tokens;
rewardTokensAvailable = tokensApprovedForReward;
bool success = token(_theToken).transferFrom(_from, this, _tokens);
require(success);
emit OPresaleFunded(_from, _tokens, _theToken, _data);
}
// used by owner to add an address to the whitelist
function addToWhitelist(address _participant) external onlyOwner {
whitelist[_participant] = true;
}
// used to add multiple addresses to whitelist
function addManyToWhitelist(address[] _participants) external onlyOwner {
for (uint256 i = 0; i < _participants.length; i++) {
whitelist[_participants[i]] = true;
}
}
// used to remove already added address from whitelist
function removeFromWhitelist(address _participant) external onlyOwner {
whitelist[_participant] = false;
}
// used to remove already added address from whitelist
function removManyeFromWhitelist(address[] _participants) external onlyOwner {
for (uint256 i = 0; i < _participants.length; i++) {
whitelist[_participants[i]] = false;
}
}
// validate pre purchase
function _preValidatePurchase( uint256 _weiAmount) internal view isWhitelisted(msg.sender) {
require(_weiAmount != 0);
}
// validate post purchase
function _postValidatePurchase(uint _totalcontributed) internal view{
// if minimum contribution is set (minimumPurchase > 0) then check if minimums met
if(minimumPurchase > 0){
require(_totalcontributed >= minimumPurchase, "contributions less than minimum");
}
// if maximum contribution is set (maximumPurchase > 0)
if(maximumPurchase > 0){
require(_totalcontributed <= maximumPurchase, "contributions greater than maximum");
}
}
// return tokens to msg.sender will be receiving. can't check for others
function tokensToReceive() public view returns (uint){
return totalAllowed[msg.sender];
}
// can only get refund per phase, if bought in multiple phase must getRefund for each phase
function getRefund() external {
require(refundAllowed, "refund Not Allowed");
require(isCompleted());
require(!notAbleToGetRefund[msg.sender], "Already withdrawn token, can not withdraw contributed ether"); // msg.sender must be able to get refund
uint weiContributed = totalContributions[msg.sender];
require(weiContributed > 0, "No Ether To Refund For This Phase"); // msg.sender must have contributed
totalContributions[msg.sender] = 0; // finds contributions of sender in phase turns to zero
uint prevAllowed = totalAllowed[msg.sender];
totalAllowed[msg.sender] = 0; // finds tokens to receive by phase turns to zero
rewardTokensAvailable = rewardTokensAvailable.add(prevAllowed); // add back to reward tokens available
msg.sender.transfer(weiContributed); // send wei contributed back
emit RefundSent(msg.sender, weiContributed);
}
function getYourTokens(uint8 _phaseBought, address _beneficiary) public returns(bool success) {
require(isCompleted(), "sale not completed yet"); // sale must have ended
require(!refundAllowed, "refund of ether is being allowed, can not withdraw tokens"); // make sure refund not allowed (which might allow to withdraw wei and tokens)
require(totalAllowed[msg.sender] > 0, "You Do Not Have Any Tokens"); // this will be zero if wei was refunded and will stop from getting ERC20 tokens also
require(phaseAbleToWithdraw[_phaseBought], "Tokens Are Locked For That Phase"); // checks to make sure tokens bought in phase is unlocked
uint payoutAmount = allowed[_phaseBought][msg.sender]; // tokens can't be partially withdrawn
require(payoutAmount > 0, "You Have No Tokens In This Phase");
allowed[_phaseBought][msg.sender] = 0; // withdraws all tokens
totalAllowed[msg.sender] = totalAllowed[msg.sender].sub(payoutAmount); // subtract from totalAllowed.
notAbleToGetRefund[msg.sender] = true; // msg.sender is not able to get wei refunded after withdrawing tokens
// send token to msg.sender if _beneficiary not provided
if (_beneficiary == address(0)){
success = tokenForReward.transfer(msg.sender, payoutAmount);
require(success);
emit TokensWithdrawn(msg.sender, msg.sender, payoutAmount);
}
// send token to _beneficiary if _beneficiary provided
else {
success = tokenForReward.transfer(_beneficiary, payoutAmount);
require(success);
emit TokensWithdrawn(msg.sender, _beneficiary, payoutAmount);
}
}
function buyToken() public saleIsOn isWhitelisted(msg.sender) payable{
uint weiAmount = msg.value;
_preValidatePurchase(weiAmount);
uint numOfTokens = weiAmount.mul(ratePer);
require(rewardTokensAvailable >= numOfTokens); // makes sure enough tokens are available
uint totalContributed = totalContributions[msg.sender].add(weiAmount);
_postValidatePurchase(totalContributed);
totalContributions[msg.sender] = totalContributed; // update amount after post validation
weiRaised = weiRaised.add(weiAmount); // add to total wei raised
rewardTokensAvailable = rewardTokensAvailable.sub(numOfTokens);
totalAllowed[msg.sender] = totalAllowed[msg.sender].add(numOfTokens); // add totals for
allowed[phase][msg.sender] = allowed[phase][msg.sender].add(numOfTokens);
}
function onlyOwnerTransferRemainingTokens(address _beneficiary) public{
require(isCompleted());
require(rewardTokensAvailable > 0, "no reward token left");
if(_beneficiary == address(0)){
require(tokenForReward.transfer(msg.sender, rewardTokensAvailable)); // transfer remaing tokens
emit OPresaleDefunded(msg.sender, rewardTokensAvailable, address(tokenForReward));
rewardTokensAvailable = 0;
}else{
require(tokenForReward.transfer(_beneficiary, rewardTokensAvailable));
emit OPresaleDefunded(_beneficiary, rewardTokensAvailable, address(tokenForReward));
rewardTokensAvailable = 0;
}
}
function onlyOwnerUnlockOrLockPhase(uint8 _phase) public onlyOwner returns(bool) {
require(isCompleted());
if (phaseAbleToWithdraw[_phase]){
phaseAbleToWithdraw[_phase] = false;
}else{
phaseAbleToWithdraw[_phase] = true;
}
return true;
}
// withdraw ether raised to Organization Wallet if softcap is reached
function onlyOwnerWithdraw() public onlyOwner onlySoftcapReached returns (bool){
super.onlyOwnerWithdraw();
}
}
|
minimum purchase amount in wei. if 0 then no minimum
|
uint public minimumPurchase;
| 2,491,360 |
[
1,
15903,
23701,
3844,
316,
732,
77,
18,
309,
374,
1508,
1158,
5224,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
1071,
5224,
23164,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.6.11;
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint a, uint b) internal pure returns (bool, uint) {
uint 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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (bool, uint) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint 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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (bool, uint) {
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(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) return 0;
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint a, uint b) internal pure returns (uint) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint a, uint b) internal pure returns (uint) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
uint newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
uint newAllowance =
token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File: contracts/protocol/IStrategy.sol
/*
version 1.2.0
Changes
Changes listed here do not affect interaction with other contracts (Vault and Controller)
- removed function assets(address _token) external view returns (bool);
- remove function deposit(uint), declared in IStrategyERC20
- add function setSlippage(uint _slippage);
- add function setDelta(uint _delta);
*/
interface IStrategy {
function admin() external view returns (address);
function controller() external view returns (address);
function vault() external view returns (address);
/*
@notice Returns address of underlying asset (ETH or ERC20)
@dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy
*/
function underlying() external view returns (address);
/*
@notice Returns total amount of underlying transferred from vault
*/
function totalDebt() external view returns (uint);
function performanceFee() external view returns (uint);
function slippage() external view returns (uint);
/*
@notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN
*/
function delta() external view returns (uint);
/*
@dev Flag to force exit in case normal exit fails
*/
function forceExit() external view returns (bool);
function setAdmin(address _admin) external;
function setController(address _controller) external;
function setPerformanceFee(uint _fee) external;
function setSlippage(uint _slippage) external;
function setDelta(uint _delta) external;
function setForceExit(bool _forceExit) external;
/*
@notice Returns amount of underlying asset locked in this contract
@dev Output may vary depending on price of liquidity provider token
where the underlying asset is invested
*/
function totalAssets() external view returns (uint);
/*
@notice Withdraw `_amount` underlying asset
@param amount Amount of underlying asset to withdraw
*/
function withdraw(uint _amount) external;
/*
@notice Withdraw all underlying asset from strategy
*/
function withdrawAll() external;
/*
@notice Sell any staking rewards for underlying and then deposit undelying
*/
function harvest() external;
/*
@notice Increase total debt if profit > 0 and total assets <= max,
otherwise transfers profit to vault.
@dev Guard against manipulation of external price feed by checking that
total assets is below factor of total debt
*/
function skim() external;
/*
@notice Exit from strategy
@dev Must transfer all underlying tokens back to vault
*/
function exit() external;
/*
@notice Transfer token accidentally sent here to admin
@param _token Address of token to transfer
@dev _token must not be equal to underlying token
*/
function sweep(address _token) external;
}
// File: contracts/protocol/IStrategyERC20.sol
interface IStrategyERC20 is IStrategy {
/*
@notice Deposit `amount` underlying ERC20 token
@param amount Amount of underlying ERC20 token to deposit
*/
function deposit(uint _amount) external;
}
// File: contracts/protocol/IController.sol
interface IController {
function ADMIN_ROLE() external view returns (bytes32);
function HARVESTER_ROLE() external view returns (bytes32);
function admin() external view returns (address);
function treasury() external view returns (address);
function setAdmin(address _admin) external;
function setTreasury(address _treasury) external;
function grantRole(bytes32 _role, address _addr) external;
function revokeRole(bytes32 _role, address _addr) external;
/*
@notice Set strategy for vault
@param _vault Address of vault
@param _strategy Address of strategy
@param _min Minimum undelying token current strategy must return. Prevents slippage
*/
function setStrategy(
address _vault,
address _strategy,
uint _min
) external;
// calls to strategy
/*
@notice Invest token in vault into strategy
@param _vault Address of vault
*/
function invest(address _vault) external;
function harvest(address _strategy) external;
function skim(address _strategy) external;
/*
@notice Withdraw from strategy to vault
@param _strategy Address of strategy
@param _amount Amount of underlying token to withdraw
@param _min Minimum amount of underlying token to withdraw
*/
function withdraw(
address _strategy,
uint _amount,
uint _min
) external;
/*
@notice Withdraw all from strategy to vault
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function withdrawAll(address _strategy, uint _min) external;
/*
@notice Exit from strategy
@param _strategy Address of strategy
@param _min Minimum amount of underlying token to withdraw
*/
function exit(address _strategy, uint _min) external;
}
// File: contracts/StrategyERC20.sol
/*
version 1.2.0
Changes from StrategyBase
- performance fee capped at 20%
- add slippage gaurd
- update skim(), increments total debt withoud withdrawing if total assets
is near total debt
- sweep - delete mapping "assets" and use require to explicitly check protected tokens
- add immutable to vault
- add immutable to underlying
- add force exit
*/
// used inside harvest
abstract contract StrategyERC20 is IStrategyERC20 {
using SafeERC20 for IERC20;
using SafeMath for uint;
address public override admin;
address public override controller;
address public immutable override vault;
address public immutable override underlying;
// total amount of underlying transferred from vault
uint public override totalDebt;
// performance fee sent to treasury when harvest() generates profit
uint public override performanceFee = 500;
uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee
uint internal constant PERFORMANCE_FEE_MAX = 10000;
// prevent slippage from deposit / withdraw
uint public override slippage = 100;
uint internal constant SLIPPAGE_MAX = 10000;
/*
Multiplier used to check totalAssets() is <= total debt * delta / DELTA_MIN
*/
uint public override delta = 10050;
uint private constant DELTA_MIN = 10000;
// Force exit, in case normal exit fails
bool public override forceExit;
constructor(
address _controller,
address _vault,
address _underlying
) public {
require(_controller != address(0), "controller = zero address");
require(_vault != address(0), "vault = zero address");
require(_underlying != address(0), "underlying = zero address");
admin = msg.sender;
controller = _controller;
vault = _vault;
underlying = _underlying;
}
modifier onlyAdmin() {
require(msg.sender == admin, "!admin");
_;
}
modifier onlyAuthorized() {
require(
msg.sender == admin || msg.sender == controller || msg.sender == vault,
"!authorized"
);
_;
}
function setAdmin(address _admin) external override onlyAdmin {
require(_admin != address(0), "admin = zero address");
admin = _admin;
}
function setController(address _controller) external override onlyAdmin {
require(_controller != address(0), "controller = zero address");
controller = _controller;
}
function setPerformanceFee(uint _fee) external override onlyAdmin {
require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap");
performanceFee = _fee;
}
function setSlippage(uint _slippage) external override onlyAdmin {
require(_slippage <= SLIPPAGE_MAX, "slippage > max");
slippage = _slippage;
}
function setDelta(uint _delta) external override onlyAdmin {
require(_delta >= DELTA_MIN, "delta < min");
delta = _delta;
}
function setForceExit(bool _forceExit) external override onlyAdmin {
forceExit = _forceExit;
}
function _increaseDebt(uint _underlyingAmount) private {
uint balBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransferFrom(vault, address(this), _underlyingAmount);
uint balAfter = IERC20(underlying).balanceOf(address(this));
totalDebt = totalDebt.add(balAfter.sub(balBefore));
}
function _decreaseDebt(uint _underlyingAmount) private {
uint balBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, _underlyingAmount);
uint balAfter = IERC20(underlying).balanceOf(address(this));
uint diff = balBefore.sub(balAfter);
if (diff >= totalDebt) {
totalDebt = 0;
} else {
totalDebt -= diff;
}
}
function _totalAssets() internal view virtual returns (uint);
/*
@notice Returns amount of underlying tokens locked in this contract
*/
function totalAssets() external view override returns (uint) {
return _totalAssets();
}
function _deposit() internal virtual;
/*
@notice Deposit underlying token into this strategy
@param _underlyingAmount Amount of underlying token to deposit
*/
function deposit(uint _underlyingAmount) external override onlyAuthorized {
require(_underlyingAmount > 0, "deposit = 0");
_increaseDebt(_underlyingAmount);
_deposit();
}
/*
@notice Returns total shares owned by this contract for depositing underlying
into external Defi
*/
function _getTotalShares() internal view virtual returns (uint);
function _getShares(uint _underlyingAmount, uint _totalUnderlying)
internal
view
returns (uint)
{
/*
calculate shares to withdraw
w = amount of underlying to withdraw
U = total redeemable underlying
s = shares to withdraw
P = total shares deposited into external liquidity pool
w / U = s / P
s = w / U * P
*/
if (_totalUnderlying > 0) {
uint totalShares = _getTotalShares();
return _underlyingAmount.mul(totalShares) / _totalUnderlying;
}
return 0;
}
function _withdraw(uint _shares) internal virtual;
/*
@notice Withdraw undelying token to vault
@param _underlyingAmount Amount of underlying token to withdraw
@dev Caller should implement guard against slippage
*/
function withdraw(uint _underlyingAmount) external override onlyAuthorized {
require(_underlyingAmount > 0, "withdraw = 0");
uint totalUnderlying = _totalAssets();
require(_underlyingAmount <= totalUnderlying, "withdraw > total");
uint shares = _getShares(_underlyingAmount, totalUnderlying);
if (shares > 0) {
_withdraw(shares);
}
// transfer underlying token to vault
/*
WARNING: Here we are transferring all funds in this contract.
This operation is safe under 2 conditions:
1. This contract does not hold any funds at rest.
2. Vault does not allow user to withdraw excess > _underlyingAmount
*/
uint underlyingBal = IERC20(underlying).balanceOf(address(this));
if (underlyingBal > 0) {
_decreaseDebt(underlyingBal);
}
}
function _withdrawAll() internal {
uint totalShares = _getTotalShares();
if (totalShares > 0) {
_withdraw(totalShares);
}
uint underlyingBal = IERC20(underlying).balanceOf(address(this));
if (underlyingBal > 0) {
IERC20(underlying).safeTransfer(vault, underlyingBal);
totalDebt = 0;
}
}
/*
@notice Withdraw all underlying to vault
@dev Caller should implement guard agains slippage
*/
function withdrawAll() external override onlyAuthorized {
_withdrawAll();
}
/*
@notice Sell any staking rewards for underlying and then deposit undelying
*/
function harvest() external virtual override;
/*
@notice Increase total debt if profit > 0 and total assets <= max,
otherwise transfers profit to vault.
@dev Guard against manipulation of external price feed by checking that
total assets is below factor of total debt
*/
function skim() external override onlyAuthorized {
uint totalUnderlying = _totalAssets();
require(totalUnderlying > totalDebt, "total underlying < debt");
uint profit = totalUnderlying - totalDebt;
// protect against price manipulation
uint max = totalDebt.mul(delta) / DELTA_MIN;
if (totalUnderlying <= max) {
/*
total underlying is within reasonable bounds, probaly no price
manipulation occured.
*/
/*
If we were to withdraw profit followed by deposit, this would
increase the total debt roughly by the profit.
Withdrawing consumes high gas, so here we omit it and
directly increase debt, as if withdraw and deposit were called.
*/
totalDebt = totalDebt.add(profit);
} else {
/*
Possible reasons for total underlying > max
1. total debt = 0
2. total underlying really did increase over max
3. price was manipulated
*/
uint shares = _getShares(profit, totalUnderlying);
if (shares > 0) {
uint balBefore = IERC20(underlying).balanceOf(address(this));
_withdraw(shares);
uint balAfter = IERC20(underlying).balanceOf(address(this));
uint diff = balAfter.sub(balBefore);
if (diff > 0) {
IERC20(underlying).safeTransfer(vault, diff);
}
}
}
}
function exit() external virtual override;
function sweep(address) external virtual override;
}
// File: contracts/interfaces/uniswap/Uniswap.sol
interface Uniswap {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
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);
}
// File: contracts/interfaces/curve/LiquidityGauge.sol
// https://github.com/curvefi/curve-contract/blob/master/contracts/gauges/LiquidityGauge.vy
interface LiquidityGauge {
function deposit(uint) external;
function balanceOf(address) external view returns (uint);
function withdraw(uint) external;
}
// File: contracts/interfaces/curve/Minter.sol
// https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy
interface Minter {
function mint(address) external;
}
// File: contracts/interfaces/curve/StableSwapGusd.sol
interface StableSwapGusd {
function get_virtual_price() external view returns (uint);
/*
0 GUSD
1 3CRV
*/
function balances(uint index) external view returns (uint);
}
// File: contracts/interfaces/curve/StableSwap3Pool.sol
interface StableSwap3Pool {
function get_virtual_price() external view returns (uint);
function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external;
function remove_liquidity_one_coin(
uint token_amount,
int128 i,
uint min_uamount
) external;
function balances(uint index) external view returns (uint);
}
// File: contracts/interfaces/curve/DepositGusd.sol
interface DepositGusd {
/*
0 GUSD
1 DAI
2 USDC
3 USDT
*/
function add_liquidity(uint[4] memory amounts, uint min) external returns (uint);
function remove_liquidity_one_coin(
uint amount,
int128 index,
uint min
) external returns (uint);
}
// File: contracts/strategies/StrategyGusdV2.sol
contract StrategyGusdV2 is StrategyERC20 {
// Uniswap //
address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address internal constant GUSD = 0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd;
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
// GUSD = 0 | DAI = 1 | USDC = 2 | USDT = 3
uint private immutable UNDERLYING_INDEX;
// precision to convert 10 ** 18 to underlying decimals
uint[4] private PRECISION_DIV = [1e16, 1, 1e12, 1e12];
// precision div of underlying token (used to save gas)
uint private immutable PRECISION_DIV_UNDERLYING;
// Curve //
// StableSwap3Pool
address private constant BASE_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
// StableSwapGusd
address private constant SWAP = 0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956;
// liquidity provider token (GUSD / 3CRV)
address private constant LP = 0xD2967f45c4f384DEEa880F807Be904762a3DeA07;
// DepositGusd
address private constant DEPOSIT = 0x64448B78561690B70E17CBE8029a3e5c1bB7136e;
// LiquidityGauge
address private constant GAUGE = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023;
// Minter
address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// CRV
address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
constructor(
address _controller,
address _vault,
address _underlying,
uint _underlyingIndex
) public StrategyERC20(_controller, _vault, _underlying) {
UNDERLYING_INDEX = _underlyingIndex;
PRECISION_DIV_UNDERLYING = PRECISION_DIV[_underlyingIndex];
// These tokens are never held by this contract
// so the risk of them getting stolen is minimal
IERC20(CRV).safeApprove(UNISWAP, uint(-1));
}
function _totalAssets() internal view override returns (uint) {
uint lpBal = LiquidityGauge(GAUGE).balanceOf(address(this));
uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price();
return lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18);
}
/*
@notice deposit token into curve
*/
function _depositIntoCurve(address _token, uint _index) private {
// token to LP
uint bal = IERC20(_token).balanceOf(address(this));
if (bal > 0) {
IERC20(_token).safeApprove(DEPOSIT, 0);
IERC20(_token).safeApprove(DEPOSIT, bal);
// mint LP
uint[4] memory amounts;
amounts[_index] = bal;
/*
shares = underlying amount * precision div * 1e18 / price per share
*/
uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price();
uint shares = bal.mul(PRECISION_DIV[_index]).mul(1e18).div(pricePerShare);
uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX;
DepositGusd(DEPOSIT).add_liquidity(amounts, min);
}
// stake into LiquidityGauge
uint lpBal = IERC20(LP).balanceOf(address(this));
if (lpBal > 0) {
IERC20(LP).safeApprove(GAUGE, 0);
IERC20(LP).safeApprove(GAUGE, lpBal);
LiquidityGauge(GAUGE).deposit(lpBal);
}
}
/*
@notice Deposits underlying to LiquidityGauge
*/
function _deposit() internal override {
_depositIntoCurve(underlying, UNDERLYING_INDEX);
}
function _getTotalShares() internal view override returns (uint) {
return LiquidityGauge(GAUGE).balanceOf(address(this));
}
function _withdraw(uint _lpAmount) internal override {
// withdraw LP from LiquidityGauge
LiquidityGauge(GAUGE).withdraw(_lpAmount);
// withdraw underlying //
uint lpBal = IERC20(LP).balanceOf(address(this));
// remove liquidity
IERC20(LP).safeApprove(DEPOSIT, 0);
IERC20(LP).safeApprove(DEPOSIT, lpBal);
/*
underlying amount = (shares * price per shares) / (1e18 * precision div)
*/
uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price();
uint underlyingAmount =
lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18);
uint min = underlyingAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX;
// withdraw creates LP dust
DepositGusd(DEPOSIT).remove_liquidity_one_coin(
lpBal,
int128(UNDERLYING_INDEX),
min
);
// Now we have underlying
}
/*
@notice Returns address and index of token with lowest balance in Curve StableSwap
*/
function _getMostPremiumToken() internal view returns (address, uint) {
// meta pool balances
uint[2] memory balances;
balances[0] = StableSwapGusd(SWAP).balances(0).mul(1e16); // GUSD
balances[1] = StableSwapGusd(SWAP).balances(1); // 3CRV
if (balances[0] <= balances[1]) {
return (GUSD, 0);
} else {
// base pool balances
uint[3] memory baseBalances;
baseBalances[0] = StableSwap3Pool(BASE_POOL).balances(0); // DAI
baseBalances[1] = StableSwap3Pool(BASE_POOL).balances(1).mul(1e12); // USDC
baseBalances[2] = StableSwap3Pool(BASE_POOL).balances(2).mul(1e12); // USDT
/*
DAI 1
USDC 2
USDT 3
*/
// DAI
if (
baseBalances[0] <= baseBalances[1] && baseBalances[0] <= baseBalances[2]
) {
return (DAI, 1);
}
// USDC
if (
baseBalances[1] <= baseBalances[0] && baseBalances[1] <= baseBalances[2]
) {
return (USDC, 2);
}
return (USDT, 3);
}
}
/*
@dev Uniswap fails with zero address so no check is necessary here
*/
function _swap(
address _from,
address _to,
uint _amount
) private {
// create dynamic array with 3 elements
address[] memory path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
Uniswap(UNISWAP).swapExactTokensForTokens(
_amount,
1,
path,
address(this),
block.timestamp
);
}
function _claimRewards(address _token) private {
// claim CRV
Minter(MINTER).mint(GAUGE);
uint crvBal = IERC20(CRV).balanceOf(address(this));
// Swap only if CRV >= 1, otherwise swap may fail for small amount of GUSD
if (crvBal >= 1e18) {
_swap(CRV, _token, crvBal);
// Now this contract has token
}
}
/*
@notice Claim CRV and deposit most premium token into Curve
*/
function harvest() external override onlyAuthorized {
(address token, uint index) = _getMostPremiumToken();
_claimRewards(token);
uint bal = IERC20(token).balanceOf(address(this));
if (bal > 0) {
// transfer fee to treasury
uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;
if (fee > 0) {
address treasury = IController(controller).treasury();
require(treasury != address(0), "treasury = zero address");
IERC20(token).safeTransfer(treasury, fee);
}
_depositIntoCurve(token, index);
}
}
/*
@notice Exit strategy by harvesting CRV to underlying token and then
withdrawing all underlying to vault
@dev Must return all underlying token to vault
@dev Caller should implement guard agains slippage
*/
function exit() external override onlyAuthorized {
if (forceExit) {
return;
}
_claimRewards(underlying);
_withdrawAll();
}
function sweep(address _token) external override onlyAdmin {
require(_token != underlying, "protected token");
IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
}
}
// File: contracts/strategies/StrategyGusdDaiV2.sol
contract StrategyGusdDaiV2 is StrategyGusdV2 {
constructor(address _controller, address _vault)
public
StrategyGusdV2(_controller, _vault, DAI, 1)
{}
}
|
stake into LiquidityGauge
|
uint lpBal = IERC20(LP).balanceOf(address(this));
| 54,485 |
[
1,
334,
911,
1368,
511,
18988,
24237,
18941,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
12423,
38,
287,
273,
467,
654,
39,
3462,
12,
14461,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x61e5541cD9a4387A72272FF0F49d62c0e7BBaBA7/sources/contracts/AdaDeUsofAnasah.sol
|
================== Variables Start ======================= mapping to keep track total mint trackersunlimited mintsroyalties ================== Variables End ======================= ================== Constructor Start =======================
|
contract AdaDeUsofAnasah is ERC721A,Ownable, ReentrancyGuard, DefaultOperatorFilterer {
using Strings for uint256;
string internal uri;
string public uriSuffix = ".json";
string public hiddenMetadataUri ;
uint256 public price ;
uint256 public maxSupply;
uint256 public maxMintAmountPerTx;
uint256 public maxLimitPerWallet;
bool public publicSale=false;
mapping(address => uint256) public userMintCount;
uint256 public publicMinted;
mapping(address=>bool) allowedUnlimitedMint;
address public royaltyReceiver;
uint96 public royaltyFeesInBeeps=1000;
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
uint public extra_nft_count;
mapping(address => bool) public whitelist;
bool public set_wl_sale = false;
constructor(
uint _maxSupply,
uint _maxMintAmountPerTx,
uint _maxLimitPerWallet,
uint _price,
string memory _hiddenMetadataUri,
string memory _revealuri,
address _royalityAddress,
uint96 _royaltyFeesInBeeps
) ERC721A("GHOSTLERS", "GHOST") {
hiddenMetadataUri=_hiddenMetadataUri;
price=_price;
maxMintAmountPerTx=_maxMintAmountPerTx;
maxLimitPerWallet=_maxLimitPerWallet;
maxSupply=_maxSupply;
seturi(_revealuri);
royaltyFeesInBeeps=_royaltyFeesInBeeps;
royaltyReceiver=_royalityAddress;
}
function Public_Sale(uint256 _mintAmount) public payable {
require(publicSale==true, 'The Public Sale is Paused!');
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, 'Invalid Mint Amount!');
require(totalSupply() + _mintAmount <= maxSupply, 'Max supply exceeded!');
require(msg.value >= price * _mintAmount, 'Insufficient Funds!');
if(allowedUnlimitedMint[msg.sender]==true){
_safeMint(_msgSender(), _mintAmount);
}
else{
require(userMintCount[msg.sender] + _mintAmount<= maxLimitPerWallet+extra_nft_count, 'Max Mint per Wallet Exceeded!');
_safeMint(_msgSender(), _mintAmount);
}
publicMinted += _mintAmount;
}
function Public_Sale(uint256 _mintAmount) public payable {
require(publicSale==true, 'The Public Sale is Paused!');
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, 'Invalid Mint Amount!');
require(totalSupply() + _mintAmount <= maxSupply, 'Max supply exceeded!');
require(msg.value >= price * _mintAmount, 'Insufficient Funds!');
if(allowedUnlimitedMint[msg.sender]==true){
_safeMint(_msgSender(), _mintAmount);
}
else{
require(userMintCount[msg.sender] + _mintAmount<= maxLimitPerWallet+extra_nft_count, 'Max Mint per Wallet Exceeded!');
_safeMint(_msgSender(), _mintAmount);
}
publicMinted += _mintAmount;
}
function Public_Sale(uint256 _mintAmount) public payable {
require(publicSale==true, 'The Public Sale is Paused!');
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, 'Invalid Mint Amount!');
require(totalSupply() + _mintAmount <= maxSupply, 'Max supply exceeded!');
require(msg.value >= price * _mintAmount, 'Insufficient Funds!');
if(allowedUnlimitedMint[msg.sender]==true){
_safeMint(_msgSender(), _mintAmount);
}
else{
require(userMintCount[msg.sender] + _mintAmount<= maxLimitPerWallet+extra_nft_count, 'Max Mint per Wallet Exceeded!');
_safeMint(_msgSender(), _mintAmount);
}
publicMinted += _mintAmount;
}
userMintCount[msg.sender] += _mintAmount;
function OwnerMint(uint256 _mintAmount, address _receiver) public onlyOwner {
require(totalSupply() + _mintAmount <= maxSupply, 'Max supply exceeded!');
_safeMint(_receiver, _mintAmount);
}
function WL_Mint(uint256 _mintAmount) public payable {
require(set_wl_sale==true, 'Free Mint Phase 1 is Paused.');
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, 'Invalid Mint Amount!');
require(totalSupply() + _mintAmount <= maxSupply, 'Max Supply Exceeded!');
require(whitelist[msg.sender], "You are not Whitelisted For Phase 1.");
require(msg.value >= price * _mintAmount, 'Insufficient Funds!');
if(allowedUnlimitedMint[msg.sender]==true){
_safeMint(_msgSender(), _mintAmount);
}
else{
require(userMintCount[msg.sender] + _mintAmount <= maxLimitPerWallet, 'Max Mint per Wallet Exceeded!');
_safeMint(_msgSender(), _mintAmount);
}
publicMinted += _mintAmount;
}
function WL_Mint(uint256 _mintAmount) public payable {
require(set_wl_sale==true, 'Free Mint Phase 1 is Paused.');
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, 'Invalid Mint Amount!');
require(totalSupply() + _mintAmount <= maxSupply, 'Max Supply Exceeded!');
require(whitelist[msg.sender], "You are not Whitelisted For Phase 1.");
require(msg.value >= price * _mintAmount, 'Insufficient Funds!');
if(allowedUnlimitedMint[msg.sender]==true){
_safeMint(_msgSender(), _mintAmount);
}
else{
require(userMintCount[msg.sender] + _mintAmount <= maxLimitPerWallet, 'Max Mint per Wallet Exceeded!');
_safeMint(_msgSender(), _mintAmount);
}
publicMinted += _mintAmount;
}
function WL_Mint(uint256 _mintAmount) public payable {
require(set_wl_sale==true, 'Free Mint Phase 1 is Paused.');
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, 'Invalid Mint Amount!');
require(totalSupply() + _mintAmount <= maxSupply, 'Max Supply Exceeded!');
require(whitelist[msg.sender], "You are not Whitelisted For Phase 1.");
require(msg.value >= price * _mintAmount, 'Insufficient Funds!');
if(allowedUnlimitedMint[msg.sender]==true){
_safeMint(_msgSender(), _mintAmount);
}
else{
require(userMintCount[msg.sender] + _mintAmount <= maxLimitPerWallet, 'Max Mint per Wallet Exceeded!');
_safeMint(_msgSender(), _mintAmount);
}
publicMinted += _mintAmount;
}
userMintCount[msg.sender] += _mintAmount;
function extra_nft_to_mint(uint _extra_nft_to_mint) public onlyOwner{
extra_nft_count=_extra_nft_to_mint;
}
function addTowhitelist(address[] calldata toAddAddresses) external onlyOwner {
for (uint i = 0; i < toAddAddresses.length; i++) {
whitelist[toAddAddresses[i]] = true;
}
}
function addTowhitelist(address[] calldata toAddAddresses) external onlyOwner {
for (uint i = 0; i < toAddAddresses.length; i++) {
whitelist[toAddAddresses[i]] = true;
}
}
function removeFromwhitelist(address[] calldata toRemoveAddresses)external onlyOwner {
for (uint i = 0; i < toRemoveAddresses.length; i++) {
delete whitelist[toRemoveAddresses[i]];
}
}
function removeFromwhitelist(address[] calldata toRemoveAddresses)external onlyOwner {
for (uint i = 0; i < toRemoveAddresses.length; i++) {
delete whitelist[toRemoveAddresses[i]];
}
}
function setWhitelistSale(bool _whitelistSale) public onlyOwner{
set_wl_sale=_whitelistSale;
}
function checIskWhitelist(address _address) public view returns(bool){
return whitelist[_address];
}
function seturi(string memory _uri) public onlyOwner {
uri = _uri;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setpublicSale(bool _publicSale) public onlyOwner {
publicSale = _publicSale;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setmaxLimitPerWallet(uint256 _maxLimitPerWallet) public onlyOwner {
maxLimitPerWallet = _maxLimitPerWallet;
}
function setPrice(uint256 _price) public onlyOwner {
price = _price;
}
function setmaxSupply(uint256 _maxSupply) public onlyOwner {
maxSupply = _maxSupply;
}
function withdraw() public onlyOwner {
require(os);
}
(bool os, ) = payable(owner()).call{value: address(this).balance}('');
function tokensOfOwner(address owner) external view returns (uint256[] memory) {
unchecked {
uint256[] memory a = new uint256[](balanceOf(owner));
uint256 end = _nextTokenId();
uint256 tokenIdsIdx;
address currOwnershipAddr;
for (uint256 i; i < end; i++) {
TokenOwnership memory ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
a[tokenIdsIdx++] = i;
}
}
return a;
}
}
function tokensOfOwner(address owner) external view returns (uint256[] memory) {
unchecked {
uint256[] memory a = new uint256[](balanceOf(owner));
uint256 end = _nextTokenId();
uint256 tokenIdsIdx;
address currOwnershipAddr;
for (uint256 i; i < end; i++) {
TokenOwnership memory ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
a[tokenIdsIdx++] = i;
}
}
return a;
}
}
function tokensOfOwner(address owner) external view returns (uint256[] memory) {
unchecked {
uint256[] memory a = new uint256[](balanceOf(owner));
uint256 end = _nextTokenId();
uint256 tokenIdsIdx;
address currOwnershipAddr;
for (uint256 i; i < end; i++) {
TokenOwnership memory ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
a[tokenIdsIdx++] = i;
}
}
return a;
}
}
function tokensOfOwner(address owner) external view returns (uint256[] memory) {
unchecked {
uint256[] memory a = new uint256[](balanceOf(owner));
uint256 end = _nextTokenId();
uint256 tokenIdsIdx;
address currOwnershipAddr;
for (uint256 i; i < end; i++) {
TokenOwnership memory ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
a[tokenIdsIdx++] = i;
}
}
return a;
}
}
function tokensOfOwner(address owner) external view returns (uint256[] memory) {
unchecked {
uint256[] memory a = new uint256[](balanceOf(owner));
uint256 end = _nextTokenId();
uint256 tokenIdsIdx;
address currOwnershipAddr;
for (uint256 i; i < end; i++) {
TokenOwnership memory ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
a[tokenIdsIdx++] = i;
}
}
return a;
}
}
function tokensOfOwner(address owner) external view returns (uint256[] memory) {
unchecked {
uint256[] memory a = new uint256[](balanceOf(owner));
uint256 end = _nextTokenId();
uint256 tokenIdsIdx;
address currOwnershipAddr;
for (uint256 i; i < end; i++) {
TokenOwnership memory ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
a[tokenIdsIdx++] = i;
}
}
return a;
}
}
function priceForQuantity(uint _amount) public view returns (uint){
return price*_amount;
}
function _startTokenId() internal view virtual override returns (uint256) {
return 1;
}
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token');
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: '';
}
function _baseURI() internal view virtual override returns (string memory) {
return uri;
}
function setUnlimitedMintPerAddress(address _address) public onlyOwner{
allowedUnlimitedMint[_address] = true;
}
function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721A) returns (bool) {
if (interfaceId == _INTERFACE_ID_ERC2981) {
return true;
}
return super.supportsInterface(interfaceId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721A) returns (bool) {
if (interfaceId == _INTERFACE_ID_ERC2981) {
return true;
}
return super.supportsInterface(interfaceId);
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount){
require(_exists(_tokenId), "ERC2981Royality: Cannot query non-existent token");
return (royaltyReceiver, (_salePrice * royaltyFeesInBeeps) / 10000);
}
function calculatingRoyalties(uint256 _salePrice) view public returns (uint256) {
return (_salePrice / 10000) * royaltyFeesInBeeps;
}
function checkRoalties() view public returns (uint256) {
return royaltyFeesInBeeps/100;
}
function setRoyalty(uint96 _royaltyFeesInBeeps) external onlyOwner {
royaltyFeesInBeeps = _royaltyFeesInBeeps;
}
function setRoyaltyReceiver(address _receiver) external onlyOwner{
royaltyReceiver = _receiver;
}
function transferFrom(address from, address to, uint256 tokenId) public payable override onlyAllowedOperator(from) {
super.transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public payable override onlyAllowedOperator(from) {
super.safeTransferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public payable override onlyAllowedOperator(from) {
super.safeTransferFrom(from, to, tokenId, data);
}
Developed by Shubham Kunwar
}
| 7,068,698 |
[
1,
2429,
631,
23536,
3603,
28562,
894,
33,
2874,
358,
3455,
3298,
2078,
312,
474,
3298,
414,
318,
21325,
312,
28142,
3800,
2390,
606,
28562,
23536,
4403,
28562,
894,
33,
28562,
11417,
3603,
28562,
894,
33,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
432,
2414,
758,
3477,
792,
979,
345,
9795,
353,
4232,
39,
27,
5340,
37,
16,
5460,
429,
16,
868,
8230,
12514,
16709,
16,
2989,
5592,
1586,
264,
288,
203,
203,
225,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
203,
21281,
225,
533,
2713,
2003,
31,
203,
225,
533,
1071,
2003,
5791,
273,
3552,
1977,
14432,
21281,
225,
533,
1071,
5949,
2277,
3006,
274,
21281,
225,
2254,
5034,
1071,
6205,
274,
7010,
225,
2254,
5034,
1071,
943,
3088,
1283,
31,
21281,
225,
2254,
5034,
1071,
943,
49,
474,
6275,
2173,
4188,
31,
203,
225,
2254,
5034,
1071,
943,
3039,
2173,
16936,
31,
203,
225,
1426,
1071,
1071,
30746,
33,
5743,
31,
203,
203,
7010,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
729,
49,
474,
1380,
31,
203,
203,
225,
2254,
5034,
1071,
1071,
49,
474,
329,
31,
203,
203,
225,
2874,
12,
2867,
9207,
6430,
13,
2935,
984,
21325,
49,
474,
31,
203,
203,
225,
1758,
1071,
721,
93,
15006,
12952,
31,
203,
225,
2254,
10525,
1071,
721,
93,
15006,
2954,
281,
382,
1919,
13058,
33,
18088,
31,
203,
225,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
654,
39,
5540,
11861,
273,
374,
92,
22,
69,
2539,
31777,
69,
31,
203,
21281,
565,
2254,
1071,
2870,
67,
82,
1222,
67,
1883,
31,
203,
203,
203,
203,
1377,
2874,
12,
2867,
516,
1426,
13,
1071,
10734,
31,
203,
1377,
203,
1377,
1426,
1071,
444,
67,
21504,
67,
87,
5349,
273,
629,
31,
203,
27699,
203,
203,
203,
203,
203,
21281,
2
] |
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
pragma experimental "ABIEncoderV2";
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.2;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is 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;
}
/**
* @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;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: set-protocol-contracts/contracts/core/interfaces/ICore.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title ICore
* @author Set Protocol
*
* The ICore Contract defines all the functions exposed in the Core through its
* various extensions and is a light weight way to interact with the contract.
*/
interface ICore {
/**
* Return transferProxy address.
*
* @return address transferProxy address
*/
function transferProxy()
external
view
returns (address);
/**
* Return vault address.
*
* @return address vault address
*/
function vault()
external
view
returns (address);
/**
* Return address belonging to given exchangeId.
*
* @param _exchangeId ExchangeId number
* @return address Address belonging to given exchangeId
*/
function exchangeIds(
uint8 _exchangeId
)
external
view
returns (address);
/*
* Returns if valid set
*
* @return bool Returns true if Set created through Core and isn't disabled
*/
function validSets(address)
external
view
returns (bool);
/*
* Returns if valid module
*
* @return bool Returns true if valid module
*/
function validModules(address)
external
view
returns (bool);
/**
* Return boolean indicating if address is a valid Rebalancing Price Library.
*
* @param _priceLibrary Price library address
* @return bool Boolean indicating if valid Price Library
*/
function validPriceLibraries(
address _priceLibrary
)
external
view
returns (bool);
/**
* Exchanges components for Set Tokens
*
* @param _set Address of set to issue
* @param _quantity Quantity of set to issue
*/
function issue(
address _set,
uint256 _quantity
)
external;
/**
* Issues a specified Set for a specified quantity to the recipient
* using the caller's components from the wallet and vault.
*
* @param _recipient Address to issue to
* @param _set Address of the Set to issue
* @param _quantity Number of tokens to issue
*/
function issueTo(
address _recipient,
address _set,
uint256 _quantity
)
external;
/**
* Converts user's components into Set Tokens held directly in Vault instead of user's account
*
* @param _set Address of the Set
* @param _quantity Number of tokens to redeem
*/
function issueInVault(
address _set,
uint256 _quantity
)
external;
/**
* Function to convert Set Tokens into underlying components
*
* @param _set The address of the Set token
* @param _quantity The number of tokens to redeem. Should be multiple of natural unit.
*/
function redeem(
address _set,
uint256 _quantity
)
external;
/**
* Redeem Set token and return components to specified recipient. The components
* are left in the vault
*
* @param _recipient Recipient of Set being issued
* @param _set Address of the Set
* @param _quantity Number of tokens to redeem
*/
function redeemTo(
address _recipient,
address _set,
uint256 _quantity
)
external;
/**
* Function to convert Set Tokens held in vault into underlying components
*
* @param _set The address of the Set token
* @param _quantity The number of tokens to redeem. Should be multiple of natural unit.
*/
function redeemInVault(
address _set,
uint256 _quantity
)
external;
/**
* Composite method to redeem and withdraw with a single transaction
*
* Normally, you should expect to be able to withdraw all of the tokens.
* However, some have central abilities to freeze transfers (e.g. EOS). _toExclude
* allows you to optionally specify which component tokens to exclude when
* redeeming. They will remain in the vault under the users' addresses.
*
* @param _set Address of the Set
* @param _to Address to withdraw or attribute tokens to
* @param _quantity Number of tokens to redeem
* @param _toExclude Mask of indexes of tokens to exclude from withdrawing
*/
function redeemAndWithdrawTo(
address _set,
address _to,
uint256 _quantity,
uint256 _toExclude
)
external;
/**
* Deposit multiple tokens to the vault. Quantities should be in the
* order of the addresses of the tokens being deposited.
*
* @param _tokens Array of the addresses of the ERC20 tokens
* @param _quantities Array of the number of tokens to deposit
*/
function batchDeposit(
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
/**
* Withdraw multiple tokens from the vault. Quantities should be in the
* order of the addresses of the tokens being withdrawn.
*
* @param _tokens Array of the addresses of the ERC20 tokens
* @param _quantities Array of the number of tokens to withdraw
*/
function batchWithdraw(
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
/**
* Deposit any quantity of tokens into the vault.
*
* @param _token The address of the ERC20 token
* @param _quantity The number of tokens to deposit
*/
function deposit(
address _token,
uint256 _quantity
)
external;
/**
* Withdraw a quantity of tokens from the vault.
*
* @param _token The address of the ERC20 token
* @param _quantity The number of tokens to withdraw
*/
function withdraw(
address _token,
uint256 _quantity
)
external;
/**
* Transfer tokens associated with the sender's account in vault to another user's
* account in vault.
*
* @param _token Address of token being transferred
* @param _to Address of user receiving tokens
* @param _quantity Amount of tokens being transferred
*/
function internalTransfer(
address _token,
address _to,
uint256 _quantity
)
external;
/**
* Deploys a new Set Token and adds it to the valid list of SetTokens
*
* @param _factory The address of the Factory to create from
* @param _components The address of component tokens
* @param _units The units of each component token
* @param _naturalUnit The minimum unit to be issued or redeemed
* @param _name The bytes32 encoded name of the new Set
* @param _symbol The bytes32 encoded symbol of the new Set
* @param _callData Byte string containing additional call parameters
* @return setTokenAddress The address of the new Set
*/
function createSet(
address _factory,
address[] calldata _components,
uint256[] calldata _units,
uint256 _naturalUnit,
bytes32 _name,
bytes32 _symbol,
bytes calldata _callData
)
external
returns (address);
/**
* Exposes internal function that deposits a quantity of tokens to the vault and attributes
* the tokens respectively, to system modules.
*
* @param _from Address to transfer tokens from
* @param _to Address to credit for deposit
* @param _token Address of token being deposited
* @param _quantity Amount of tokens to deposit
*/
function depositModule(
address _from,
address _to,
address _token,
uint256 _quantity
)
external;
/**
* Exposes internal function that withdraws a quantity of tokens from the vault and
* deattributes the tokens respectively, to system modules.
*
* @param _from Address to decredit for withdraw
* @param _to Address to transfer tokens to
* @param _token Address of token being withdrawn
* @param _quantity Amount of tokens to withdraw
*/
function withdrawModule(
address _from,
address _to,
address _token,
uint256 _quantity
)
external;
/**
* Exposes internal function that deposits multiple tokens to the vault, to system
* modules. Quantities should be in the order of the addresses of the tokens being
* deposited.
*
* @param _from Address to transfer tokens from
* @param _to Address to credit for deposits
* @param _tokens Array of the addresses of the tokens being deposited
* @param _quantities Array of the amounts of tokens to deposit
*/
function batchDepositModule(
address _from,
address _to,
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
/**
* Exposes internal function that withdraws multiple tokens from the vault, to system
* modules. Quantities should be in the order of the addresses of the tokens being withdrawn.
*
* @param _from Address to decredit for withdrawals
* @param _to Address to transfer tokens to
* @param _tokens Array of the addresses of the tokens being withdrawn
* @param _quantities Array of the amounts of tokens to withdraw
*/
function batchWithdrawModule(
address _from,
address _to,
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
/**
* Expose internal function that exchanges components for Set tokens,
* accepting any owner, to system modules
*
* @param _owner Address to use tokens from
* @param _recipient Address to issue Set to
* @param _set Address of the Set to issue
* @param _quantity Number of tokens to issue
*/
function issueModule(
address _owner,
address _recipient,
address _set,
uint256 _quantity
)
external;
/**
* Expose internal function that exchanges Set tokens for components,
* accepting any owner, to system modules
*
* @param _burnAddress Address to burn token from
* @param _incrementAddress Address to increment component tokens to
* @param _set Address of the Set to redeem
* @param _quantity Number of tokens to redeem
*/
function redeemModule(
address _burnAddress,
address _incrementAddress,
address _set,
uint256 _quantity
)
external;
/**
* Expose vault function that increments user's balance in the vault.
* Available to system modules
*
* @param _tokens The addresses of the ERC20 tokens
* @param _owner The address of the token owner
* @param _quantities The numbers of tokens to attribute to owner
*/
function batchIncrementTokenOwnerModule(
address[] calldata _tokens,
address _owner,
uint256[] calldata _quantities
)
external;
/**
* Expose vault function that decrement user's balance in the vault
* Only available to system modules.
*
* @param _tokens The addresses of the ERC20 tokens
* @param _owner The address of the token owner
* @param _quantities The numbers of tokens to attribute to owner
*/
function batchDecrementTokenOwnerModule(
address[] calldata _tokens,
address _owner,
uint256[] calldata _quantities
)
external;
/**
* Expose vault function that transfer vault balances between users
* Only available to system modules.
*
* @param _tokens Addresses of tokens being transferred
* @param _from Address tokens being transferred from
* @param _to Address tokens being transferred to
* @param _quantities Amounts of tokens being transferred
*/
function batchTransferBalanceModule(
address[] calldata _tokens,
address _from,
address _to,
uint256[] calldata _quantities
)
external;
/**
* Transfers token from one address to another using the transfer proxy.
* Only available to system modules.
*
* @param _token The address of the ERC20 token
* @param _quantity The number of tokens to transfer
* @param _from The address to transfer from
* @param _to The address to transfer to
*/
function transferModule(
address _token,
uint256 _quantity,
address _from,
address _to
)
external;
/**
* Expose transfer proxy function to transfer tokens from one address to another
* Only available to system modules.
*
* @param _tokens The addresses of the ERC20 token
* @param _quantities The numbers of tokens to transfer
* @param _from The address to transfer from
* @param _to The address to transfer to
*/
function batchTransferModule(
address[] calldata _tokens,
uint256[] calldata _quantities,
address _from,
address _to
)
external;
}
// File: set-protocol-contracts/contracts/core/lib/RebalancingLibrary.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title RebalancingLibrary
* @author Set Protocol
*
* The RebalancingLibrary contains functions for facilitating the rebalancing process for
* Rebalancing Set Tokens. Removes the old calculation functions
*
*/
library RebalancingLibrary {
/* ============ Enums ============ */
enum State { Default, Proposal, Rebalance, Drawdown }
/* ============ Structs ============ */
struct AuctionPriceParameters {
uint256 auctionStartTime;
uint256 auctionTimeToPivot;
uint256 auctionStartPrice;
uint256 auctionPivotPrice;
}
struct BiddingParameters {
uint256 minimumBid;
uint256 remainingCurrentSets;
uint256[] combinedCurrentUnits;
uint256[] combinedNextSetUnits;
address[] combinedTokenArray;
}
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetToken.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title IRebalancingSetToken
* @author Set Protocol
*
* The IRebalancingSetToken interface provides a light-weight, structured way to interact with the
* RebalancingSetToken contract from another contract.
*/
interface IRebalancingSetToken {
/*
* Get totalSupply of Rebalancing Set
*
* @return totalSupply
*/
function totalSupply()
external
view
returns (uint256);
/*
* Get lastRebalanceTimestamp of Rebalancing Set
*
* @return lastRebalanceTimestamp
*/
function lastRebalanceTimestamp()
external
view
returns (uint256);
/*
* Get rebalanceInterval of Rebalancing Set
*
* @return rebalanceInterval
*/
function rebalanceInterval()
external
view
returns (uint256);
/*
* Get rebalanceState of Rebalancing Set
*
* @return rebalanceState
*/
function rebalanceState()
external
view
returns (RebalancingLibrary.State);
/**
* Gets the balance of the specified address.
*
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(
address owner
)
external
view
returns (uint256);
/**
* Function used to set the terms of the next rebalance and start the proposal period
*
* @param _nextSet The Set to rebalance into
* @param _auctionLibrary The library used to calculate the Dutch Auction price
* @param _auctionTimeToPivot The amount of time for the auction to go ffrom start to pivot price
* @param _auctionStartPrice The price to start the auction at
* @param _auctionPivotPrice The price at which the price curve switches from linear to exponential
*/
function propose(
address _nextSet,
address _auctionLibrary,
uint256 _auctionTimeToPivot,
uint256 _auctionStartPrice,
uint256 _auctionPivotPrice
)
external;
/*
* Get natural unit of Set
*
* @return uint256 Natural unit of Set
*/
function naturalUnit()
external
view
returns (uint256);
/**
* Returns the address of the current Base Set
*
* @return A address representing the base Set Token
*/
function currentSet()
external
view
returns (address);
/*
* Get the unit shares of the rebalancing Set
*
* @return unitShares Unit Shares of the base Set
*/
function unitShares()
external
view
returns (uint256);
/*
* Burn set token for given address.
* Can only be called by authorized contracts.
*
* @param _from The address of the redeeming account
* @param _quantity The number of sets to burn from redeemer
*/
function burn(
address _from,
uint256 _quantity
)
external;
/*
* Place bid during rebalance auction. Can only be called by Core.
*
* @param _quantity The amount of currentSet to be rebalanced
* @return combinedTokenArray Array of token addresses invovled in rebalancing
* @return inflowUnitArray Array of amount of tokens inserted into system in bid
* @return outflowUnitArray Array of amount of tokens taken out of system in bid
*/
function placeBid(
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
/*
* Get combinedTokenArray of Rebalancing Set
*
* @return combinedTokenArray
*/
function getCombinedTokenArrayLength()
external
view
returns (uint256);
/*
* Get combinedTokenArray of Rebalancing Set
*
* @return combinedTokenArray
*/
function getCombinedTokenArray()
external
view
returns (address[] memory);
/*
* Get failedAuctionWithdrawComponents of Rebalancing Set
*
* @return failedAuctionWithdrawComponents
*/
function getFailedAuctionWithdrawComponents()
external
view
returns (address[] memory);
/*
* Get biddingParameters for current auction
*
* @return biddingParameters
*/
function getBiddingParameters()
external
view
returns (uint256[] memory);
}
// File: set-protocol-contracts/contracts/core/interfaces/ISetToken.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title ISetToken
* @author Set Protocol
*
* The ISetToken interface provides a light-weight, structured way to interact with the
* SetToken contract from another contract.
*/
interface ISetToken {
/* ============ External Functions ============ */
/*
* Get natural unit of Set
*
* @return uint256 Natural unit of Set
*/
function naturalUnit()
external
view
returns (uint256);
/*
* Get addresses of all components in the Set
*
* @return componentAddresses Array of component tokens
*/
function getComponents()
external
view
returns (address[] memory);
/*
* Get units of all tokens in Set
*
* @return units Array of component units
*/
function getUnits()
external
view
returns (uint256[] memory);
/*
* Checks to make sure token is component of Set
*
* @param _tokenAddress Address of token being checked
* @return bool True if token is component of Set
*/
function tokenIsComponent(
address _tokenAddress
)
external
view
returns (bool);
/*
* Mint set token for given address.
* Can only be called by authorized contracts.
*
* @param _issuer The address of the issuing account
* @param _quantity The number of sets to attribute to issuer
*/
function mint(
address _issuer,
uint256 _quantity
)
external;
/*
* Burn set token for given address
* Can only be called by authorized contracts
*
* @param _from The address of the redeeming account
* @param _quantity The number of sets to burn from redeemer
*/
function burn(
address _from,
uint256 _quantity
)
external;
/**
* 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
)
external;
}
// File: set-protocol-contracts/contracts/core/lib/SetTokenLibrary.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
library SetTokenLibrary {
using SafeMath for uint256;
struct SetDetails {
uint256 naturalUnit;
address[] components;
uint256[] units;
}
/**
* Validates that passed in tokens are all components of the Set
*
* @param _set Address of the Set
* @param _tokens List of tokens to check
*/
function validateTokensAreComponents(
address _set,
address[] calldata _tokens
)
external
view
{
for (uint256 i = 0; i < _tokens.length; i++) {
// Make sure all tokens are members of the Set
require(
ISetToken(_set).tokenIsComponent(_tokens[i]),
"SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set"
);
}
}
/**
* Validates that passed in quantity is a multiple of the natural unit of the Set.
*
* @param _set Address of the Set
* @param _quantity Quantity to validate
*/
function isMultipleOfSetNaturalUnit(
address _set,
uint256 _quantity
)
external
view
{
require(
_quantity.mod(ISetToken(_set).naturalUnit()) == 0,
"SetTokenLibrary.isMultipleOfSetNaturalUnit: Quantity is not a multiple of nat unit"
);
}
/**
* Retrieves the Set's natural unit, components, and units.
*
* @param _set Address of the Set
* @return SetDetails Struct containing the natural unit, components, and units
*/
function getSetDetails(
address _set
)
internal
view
returns (SetDetails memory)
{
// Declare interface variables
ISetToken setToken = ISetToken(_set);
// Fetch set token properties
uint256 naturalUnit = setToken.naturalUnit();
address[] memory components = setToken.getComponents();
uint256[] memory units = setToken.getUnits();
return SetDetails({
naturalUnit: naturalUnit,
components: components,
units: units
});
}
}
// File: contracts/meta-oracles/interfaces/IOracle.sol
/*
Copyright 2019 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title IOracle
* @author Set Protocol
*
* Interface for operating with any external Oracle that returns uint256 or
* an adapting contract that converts oracle output to uint256
*/
interface IOracle {
/**
* Returns the queried data from an oracle returning uint256
*
* @return Current price of asset represented in uint256
*/
function read()
external
view
returns (uint256);
}
// File: contracts/meta-oracles/interfaces/IMetaOracleV2.sol
/*
Copyright 2019 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title IMetaOracleV2
* @author Set Protocol
*
* Interface for operating with any MetaOracleV2 (moving average, bollinger, etc.)
*
* CHANGELOG:
* - read returns uint256 instead of bytes
*/
interface IMetaOracleV2 {
/**
* Returns the queried data from a meta oracle.
*
* @return Current price of asset in uint256
*/
function read(
uint256 _dataDays
)
external
view
returns (uint256);
}
// File: contracts/external/DappHub/interfaces/IMedian.sol
/*
Copyright 2019 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title IMedian
* @author Set Protocol
*
* Interface for operating with a price feed Medianizer contract
*/
interface IMedian {
/**
* Returns the current price set on the medianizer. Throws if the price is set to 0 (initialization)
*
* @return Current price of asset represented in hex as bytes32
*/
function read()
external
view
returns (bytes32);
/**
* Returns the current price set on the medianizer and whether the value has been initialized
*
* @return Current price of asset represented in hex as bytes32, and whether value is non-zero
*/
function peek()
external
view
returns (bytes32, bool);
}
// File: contracts/managers/lib/FlexibleTimingManagerLibrary.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title FlexibleTimingManagerLibrary
* @author Set Protocol
*
* The FlexibleTimingManagerLibrary contains functions for helping Managers create proposals
*
*/
library FlexibleTimingManagerLibrary {
using SafeMath for uint256;
/*
* Validates whether the Rebalancing Set is in the correct state and sufficient time has elapsed.
*
* @param _rebalancingSetInterface Instance of the Rebalancing Set Token
*/
function validateManagerPropose(
IRebalancingSetToken _rebalancingSetInterface
)
internal
{
// Require that enough time has passed from last rebalance
uint256 lastRebalanceTimestamp = _rebalancingSetInterface.lastRebalanceTimestamp();
uint256 rebalanceInterval = _rebalancingSetInterface.rebalanceInterval();
require(
block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval),
"FlexibleTimingManagerLibrary.proposeNewRebalance: Rebalance interval not elapsed"
);
// Require that Rebalancing Set Token is in Default state, won't allow for re-proposals
// because malicious actor could prevent token from ever rebalancing
require(
_rebalancingSetInterface.rebalanceState() == RebalancingLibrary.State.Default,
"FlexibleTimingManagerLibrary.proposeNewRebalance: State must be in Default"
);
}
/*
/*
* Calculates the auction price parameters, targetting 1% slippage every 10 minutes. Fair value
* placed in middle of price range.
*
* @param _currentSetDollarAmount The 18 decimal value of one currenSet
* @param _nextSetDollarAmount The 18 decimal value of one nextSet
* @param _timeIncrement Amount of time to explore 1% of fair value price change
* @param _auctionLibraryPriceDivisor The auction library price divisor
* @param _auctionTimeToPivot The auction time to pivot
* @return uint256 The auctionStartPrice for rebalance auction
* @return uint256 The auctionPivotPrice for rebalance auction
*/
function calculateAuctionPriceParameters(
uint256 _currentSetDollarAmount,
uint256 _nextSetDollarAmount,
uint256 _timeIncrement,
uint256 _auctionLibraryPriceDivisor,
uint256 _auctionTimeToPivot
)
internal
view
returns (uint256, uint256)
{
// Determine fair value of nextSet/currentSet and put in terms of auction library price divisor
uint256 fairValue = _nextSetDollarAmount.mul(_auctionLibraryPriceDivisor).div(_currentSetDollarAmount);
// Calculate how much one percent slippage from fair value is
uint256 onePercentSlippage = fairValue.div(100);
// Calculate how many time increments are in auctionTimeToPivot
uint256 timeIncrements = _auctionTimeToPivot.div(_timeIncrement);
// Since we are targeting a 1% slippage every time increment the price range is defined as
// the price of a 1% move multiplied by the amount of time increments in the auctionTimeToPivot
// This value is then divided by two to get half the price range
uint256 halfPriceRange = timeIncrements.mul(onePercentSlippage).div(2);
// Auction start price is fair value minus half price range to center the auction at fair value
uint256 auctionStartPrice = fairValue.sub(halfPriceRange);
// Auction pivot price is fair value plus half price range to center the auction at fair value
uint256 auctionPivotPrice = fairValue.add(halfPriceRange);
return (auctionStartPrice, auctionPivotPrice);
}
/*
* Query the Medianizer price feeds for a value that is returned as a Uint. Prices
* have 18 decimals.
*
* @param _priceFeedAddress Address of the medianizer price feed
* @return uint256 The price from the price feed with 18 decimals
*/
function queryPriceData(
address _priceFeedAddress
)
internal
view
returns (uint256)
{
// Get prices from oracles
bytes32 priceInBytes = IMedian(_priceFeedAddress).read();
return uint256(priceInBytes);
}
/*
* Calculates the USD Value of a Set Token - by taking the individual token prices, units
* and decimals.
*
* @param _tokenPrices The 18 decimal values of components
* @param _naturalUnit The naturalUnit of the set being component belongs to
* @param _units The units of the components in the Set
* @param _tokenDecimals The components decimal values
* @return uint256 The USD value of the Set (in cents)
*/
function calculateSetTokenDollarValue(
uint256[] memory _tokenPrices,
uint256 _naturalUnit,
uint256[] memory _units,
uint256[] memory _tokenDecimals
)
internal
view
returns (uint256)
{
uint256 setDollarAmount = 0;
// Loop through assets
for (uint256 i = 0; i < _tokenPrices.length; i++) {
uint256 tokenDollarValue = calculateTokenAllocationAmountUSD(
_tokenPrices[i],
_naturalUnit,
_units[i],
_tokenDecimals[i]
);
setDollarAmount = setDollarAmount.add(tokenDollarValue);
}
return setDollarAmount;
}
/*
* Get USD value of one component in a Set to 18 decimals
*
* @param _tokenPrice The 18 decimal value of one full token
* @param _naturalUnit The naturalUnit of the set being component belongs to
* @param _unit The unit of the component in the set
* @param _tokenDecimals The component token's decimal value
* @return uint256 The USD value of the component's allocation in the Set
*/
function calculateTokenAllocationAmountUSD(
uint256 _tokenPrice,
uint256 _naturalUnit,
uint256 _unit,
uint256 _tokenDecimals
)
internal
view
returns (uint256)
{
uint256 SET_TOKEN_DECIMALS = 18;
// Calculate the amount of component base units are in one full set token
uint256 componentUnitsInFullToken = _unit
.mul(10 ** SET_TOKEN_DECIMALS)
.div(_naturalUnit);
// Return value of component token in one full set token, to 18 decimals
uint256 allocationUSDValue = _tokenPrice
.mul(componentUnitsInFullToken)
.div(10 ** _tokenDecimals);
require(
allocationUSDValue > 0,
"FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD: Value must be > 0"
);
return allocationUSDValue;
}
}
// File: contracts/managers/MACOStrategyManagerV2.sol
/*
Copyright 2019 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title MACOStrategyManager
* @author Set Protocol
*
* Rebalancing Manager contract for implementing the Moving Average (MA) Crossover
* Strategy between a risk asset's MA and the spot price of the risk asset. The time
* frame for the MA is defined on instantiation. When the spot price dips below the MA
* risk asset is sold for stable asset and vice versa when the spot price exceeds the MA.
*
* CHANGELOG:
* - Pass riskAssetOracleInstance in constructor
* - Pass list of collateral sets in constructor instead of individually
* - Read oracles using IOracle and IMetaOracleV2
*/
contract MACOStrategyManagerV2 {
using SafeMath for uint256;
/* ============ Constants ============ */
uint256 constant AUCTION_LIB_PRICE_DIVISOR = 1000;
uint256 constant ALLOCATION_PRICE_RATIO_LIMIT = 4;
uint256 constant TEN_MINUTES_IN_SECONDS = 600;
// Equal to $1 since token prices are passed with 18 decimals
uint256 constant STABLE_ASSET_PRICE = 10 ** 18;
uint256 constant SET_TOKEN_DECIMALS = 10 ** 18;
/* ============ State Variables ============ */
address public contractDeployer;
address public rebalancingSetTokenAddress;
address public coreAddress;
address public setTokenFactory;
address public auctionLibrary;
IMetaOracleV2 public movingAveragePriceFeedInstance;
IOracle public riskAssetOracleInstance;
address public stableAssetAddress;
address public riskAssetAddress;
address public stableCollateralAddress;
address public riskCollateralAddress;
uint256 public stableAssetDecimals;
uint256 public riskAssetDecimals;
uint256 public auctionTimeToPivot;
uint256 public movingAverageDays;
uint256 public lastCrossoverConfirmationTimestamp;
uint256 public crossoverConfirmationMinTime;
uint256 public crossoverConfirmationMaxTime;
/* ============ Events ============ */
event LogManagerProposal(
uint256 riskAssetPrice,
uint256 movingAveragePrice
);
/*
* MACOStrategyManager constructor.
*
* @param _coreAddress The address of the Core contract
* @param _movingAveragePriceFeed The address of MA price feed
* @param _riskAssetOracle The address of risk asset oracle
* @param _stableAssetAddress The address of the stable asset contract
* @param _riskAssetAddress The address of the risk asset contract
* @param _collateralAddresses The addresses of collateral Sets [stableCollateral,
* riskCollateral]
* @param _setTokenFactory The address of the SetTokenFactory
* @param _auctionLibrary The address of auction price curve to use in rebalance
* @param _movingAverageDays The amount of days to use in moving average calculation
* @param _auctionTimeToPivot The amount of time until pivot reached in rebalance
* @param _crossoverConfirmationBounds The minimum and maximum time in seconds confirm confirmation
* can be called after the last initial crossover confirmation
*/
constructor(
address _coreAddress,
IMetaOracleV2 _movingAveragePriceFeed,
IOracle _riskAssetOracle,
address _stableAssetAddress,
address _riskAssetAddress,
address[2] memory _collateralAddresses,
address _setTokenFactory,
address _auctionLibrary,
uint256 _movingAverageDays,
uint256 _auctionTimeToPivot,
uint256[2] memory _crossoverConfirmationBounds
)
public
{
contractDeployer = msg.sender;
coreAddress = _coreAddress;
movingAveragePriceFeedInstance = _movingAveragePriceFeed;
riskAssetOracleInstance = _riskAssetOracle;
setTokenFactory = _setTokenFactory;
auctionLibrary = _auctionLibrary;
stableAssetAddress = _stableAssetAddress;
riskAssetAddress = _riskAssetAddress;
stableCollateralAddress = _collateralAddresses[0];
riskCollateralAddress = _collateralAddresses[1];
auctionTimeToPivot = _auctionTimeToPivot;
movingAverageDays = _movingAverageDays;
lastCrossoverConfirmationTimestamp = 0;
crossoverConfirmationMinTime = _crossoverConfirmationBounds[0];
crossoverConfirmationMaxTime = _crossoverConfirmationBounds[1];
address[] memory initialStableCollateralComponents = ISetToken(_collateralAddresses[0]).getComponents();
address[] memory initialRiskCollateralComponents = ISetToken(_collateralAddresses[1]).getComponents();
require(
crossoverConfirmationMaxTime > crossoverConfirmationMinTime,
"MACOStrategyManager.constructor: Max confirmation time must be greater than min."
);
require(
initialStableCollateralComponents[0] == _stableAssetAddress,
"MACOStrategyManager.constructor: Stable collateral component must match stable asset."
);
require(
initialRiskCollateralComponents[0] == _riskAssetAddress,
"MACOStrategyManager.constructor: Risk collateral component must match risk asset."
);
// Get decimals of underlying assets from smart contracts
stableAssetDecimals = ERC20Detailed(_stableAssetAddress).decimals();
riskAssetDecimals = ERC20Detailed(_riskAssetAddress).decimals();
}
/* ============ External ============ */
/*
* This function sets the Rebalancing Set Token address that the manager is associated with.
* Since, the rebalancing set token must first specify the address of the manager before deployment,
* we cannot know what the rebalancing set token is in advance. This function is only meant to be called
* once during initialization by the contract deployer.
*
* @param _rebalancingSetTokenAddress The address of the rebalancing Set token
*/
function initialize(
address _rebalancingSetTokenAddress
)
external
{
// Check that contract deployer is calling function
require(
msg.sender == contractDeployer,
"MACOStrategyManager.initialize: Only the contract deployer can initialize"
);
// Make sure the rebalancingSetToken is tracked by Core
require(
ICore(coreAddress).validSets(_rebalancingSetTokenAddress),
"MACOStrategyManager.initialize: Invalid or disabled RebalancingSetToken address"
);
rebalancingSetTokenAddress = _rebalancingSetTokenAddress;
contractDeployer = address(0);
}
/*
* When allowed on RebalancingSetToken, anyone can call for a new rebalance proposal. This begins a six
* hour period where the signal can be confirmed before moving ahead with rebalance.
*
*/
function initialPropose()
external
{
// Make sure propose in manager hasn't already been initiated
require(
block.timestamp > lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMaxTime),
"MACOStrategyManager.initialPropose: 12 hours must pass before new proposal initiated"
);
// Create interface to interact with RebalancingSetToken and check enough time has passed for proposal
FlexibleTimingManagerLibrary.validateManagerPropose(IRebalancingSetToken(rebalancingSetTokenAddress));
// Get price data from oracles
(
uint256 riskAssetPrice,
uint256 movingAveragePrice
) = getPriceData();
// Make sure price trigger has been reached
checkPriceTriggerMet(riskAssetPrice, movingAveragePrice);
lastCrossoverConfirmationTimestamp = block.timestamp;
}
/*
* After initial propose is called, confirm the signal has been met and determine parameters for the rebalance
*
*/
function confirmPropose()
external
{
// Make sure enough time has passed to initiate proposal on Rebalancing Set Token
require(
block.timestamp >= lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMinTime) &&
block.timestamp <= lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMaxTime),
"MACOStrategyManager.confirmPropose: Confirming signal must be within bounds of the initial propose"
);
// Create interface to interact with RebalancingSetToken and check not in Proposal state
FlexibleTimingManagerLibrary.validateManagerPropose(IRebalancingSetToken(rebalancingSetTokenAddress));
// Get price data from oracles
(
uint256 riskAssetPrice,
uint256 movingAveragePrice
) = getPriceData();
// Make sure price trigger has been reached
checkPriceTriggerMet(riskAssetPrice, movingAveragePrice);
// If price trigger has been met, get next Set allocation. Create new set if price difference is too
// great to run good auction. Return nextSet address and dollar value of current and next set
(
address nextSetAddress,
uint256 currentSetDollarValue,
uint256 nextSetDollarValue
) = determineNewAllocation(
riskAssetPrice
);
// Calculate the price parameters for auction
(
uint256 auctionStartPrice,
uint256 auctionPivotPrice
) = FlexibleTimingManagerLibrary.calculateAuctionPriceParameters(
currentSetDollarValue,
nextSetDollarValue,
TEN_MINUTES_IN_SECONDS,
AUCTION_LIB_PRICE_DIVISOR,
auctionTimeToPivot
);
// Propose new allocation to Rebalancing Set Token
IRebalancingSetToken(rebalancingSetTokenAddress).propose(
nextSetAddress,
auctionLibrary,
auctionTimeToPivot,
auctionStartPrice,
auctionPivotPrice
);
emit LogManagerProposal(
riskAssetPrice,
movingAveragePrice
);
}
/* ============ Internal ============ */
/*
* Determine if risk collateral is currently collateralizing the rebalancing set, if so return true,
* else return false.
*
* @return boolean True if risk collateral in use, false otherwise
*/
function usingRiskCollateral()
internal
view
returns (bool)
{
// Get set currently collateralizing rebalancing set token
address[] memory currentCollateralComponents = ISetToken(rebalancingSetTokenAddress).getComponents();
// If collateralized by riskCollateral set return true, else to false
return (currentCollateralComponents[0] == riskCollateralAddress);
}
/*
* Get the risk asset and moving average prices from respective oracles. Price returned have 18 decimals so
* 10 ** 18 = $1.
*
* @return uint256 USD Price of risk asset
* @return uint256 Moving average USD Price of risk asset
*/
function getPriceData()
internal
view
returns(uint256, uint256)
{
// Get current risk asset price and moving average data
uint256 riskAssetPrice = riskAssetOracleInstance.read();
uint256 movingAveragePrice = movingAveragePriceFeedInstance.read(movingAverageDays);
return (riskAssetPrice, movingAveragePrice);
}
/*
* Check to make sure that the necessary price changes have occured to allow a rebalance.
*
* @param _riskAssetPrice Current risk asset price as found on oracle
* @param _movingAveragePrice Current MA price from Meta Oracle
*/
function checkPriceTriggerMet(
uint256 _riskAssetPrice,
uint256 _movingAveragePrice
)
internal
view
{
if (usingRiskCollateral()) {
// If currently holding risk asset (riskOn) check to see if price is below MA, otherwise revert.
require(
_movingAveragePrice > _riskAssetPrice,
"MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be below moving average price"
);
} else {
// If currently holding stable asset (not riskOn) check to see if price is above MA, otherwise revert.
require(
_movingAveragePrice < _riskAssetPrice,
"MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be above moving average price"
);
}
}
/*
* Determine the next allocation to rebalance into. If the dollar value of the two collateral sets is more
* than 5x different from each other then create a new collateral set. If currently riskOn then a new
* stable collateral set is created, if !riskOn then a new risk collateral set is created.
*
* @param _riskAssetPrice Current risk asset price as found on oracle
* @return address The address of the proposed nextSet
* @return uint256 The USD value of current Set
* @return uint256 The USD value of next Set
*/
function determineNewAllocation(
uint256 _riskAssetPrice
)
internal
returns (address, uint256, uint256)
{
// Check to see if new collateral must be created in order to keep collateral price ratio in line.
// If not just return the dollar value of current collateral sets
(
uint256 stableCollateralDollarValue,
uint256 riskCollateralDollarValue
) = checkForNewAllocation(_riskAssetPrice);
(
address nextSetAddress,
uint256 currentSetDollarValue,
uint256 nextSetDollarValue
) = usingRiskCollateral() ? (stableCollateralAddress, riskCollateralDollarValue, stableCollateralDollarValue) :
(riskCollateralAddress, stableCollateralDollarValue, riskCollateralDollarValue);
return (nextSetAddress, currentSetDollarValue, nextSetDollarValue);
}
/*
* Check to see if a new collateral set needs to be created. If the dollar value of the two collateral sets is more
* than 5x different from each other then create a new collateral set.
*
* @param _riskAssetPrice Current risk asset price as found on oracle
* @return uint256 The USD value of stable collateral
* @return uint256 The USD value of risk collateral
*/
function checkForNewAllocation(
uint256 _riskAssetPrice
)
internal
returns(uint256, uint256)
{
// Get details of both collateral sets
SetTokenLibrary.SetDetails memory stableCollateralDetails = SetTokenLibrary.getSetDetails(
stableCollateralAddress
);
SetTokenLibrary.SetDetails memory riskCollateralDetails = SetTokenLibrary.getSetDetails(
riskCollateralAddress
);
// Value both Sets
uint256 stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
STABLE_ASSET_PRICE,
stableCollateralDetails.naturalUnit,
stableCollateralDetails.units[0],
stableAssetDecimals
);
uint256 riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
_riskAssetPrice,
riskCollateralDetails.naturalUnit,
riskCollateralDetails.units[0],
riskAssetDecimals
);
// If value of one Set is 5 times greater than the other, create a new collateral Set
if (riskCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT) <= stableCollateralDollarValue ||
riskCollateralDollarValue >= stableCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT)) {
//Determine the new collateral parameters
return determineNewCollateralParameters(
_riskAssetPrice,
stableCollateralDollarValue,
riskCollateralDollarValue,
stableCollateralDetails,
riskCollateralDetails
);
} else {
return (stableCollateralDollarValue, riskCollateralDollarValue);
}
}
/*
* Create new collateral Set for the occasion where the dollar value of the two collateral
* sets is more than 5x different from each other. The new collateral set address is then
* assigned to the correct state variable (risk or stable collateral)
*
* @param _riskAssetPrice Current risk asset price as found on oracle
* @param _stableCollateralValue Value of current stable collateral set in USD
* @param _riskCollateralValue Value of current risk collateral set in USD
* @param _stableCollateralDetails Set details of current stable collateral set
* @param _riskCollateralDetails Set details of current risk collateral set
* @return uint256 The USD value of stable collateral
* @return uint256 The USD value of risk collateral
*/
function determineNewCollateralParameters(
uint256 _riskAssetPrice,
uint256 _stableCollateralValue,
uint256 _riskCollateralValue,
SetTokenLibrary.SetDetails memory _stableCollateralDetails,
SetTokenLibrary.SetDetails memory _riskCollateralDetails
)
internal
returns (uint256, uint256)
{
uint256 stableCollateralDollarValue;
uint256 riskCollateralDollarValue;
if (usingRiskCollateral()) {
// Create static components and units array
address[] memory nextSetComponents = new address[](1);
nextSetComponents[0] = stableAssetAddress;
(
uint256[] memory nextSetUnits,
uint256 nextNaturalUnit
) = getNewCollateralSetParameters(
_riskCollateralValue,
STABLE_ASSET_PRICE,
stableAssetDecimals,
_stableCollateralDetails.naturalUnit
);
// Create new stable collateral set with units and naturalUnit as calculated above
stableCollateralAddress = ICore(coreAddress).createSet(
setTokenFactory,
nextSetComponents,
nextSetUnits,
nextNaturalUnit,
bytes32("STBLCollateral"),
bytes32("STBLMACO"),
""
);
// Calculate dollar value of new stable collateral
stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
STABLE_ASSET_PRICE,
nextNaturalUnit,
nextSetUnits[0],
stableAssetDecimals
);
riskCollateralDollarValue = _riskCollateralValue;
} else {
// Create static components and units array
address[] memory nextSetComponents = new address[](1);
nextSetComponents[0] = riskAssetAddress;
(
uint256[] memory nextSetUnits,
uint256 nextNaturalUnit
) = getNewCollateralSetParameters(
_stableCollateralValue,
_riskAssetPrice,
riskAssetDecimals,
_riskCollateralDetails.naturalUnit
);
// Create new risk collateral set with units and naturalUnit as calculated above
riskCollateralAddress = ICore(coreAddress).createSet(
setTokenFactory,
nextSetComponents,
nextSetUnits,
nextNaturalUnit,
bytes32("RISKCollateral"),
bytes32("RISKMACO"),
""
);
// Calculate dollar value of new risk collateral
riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
_riskAssetPrice,
nextNaturalUnit,
nextSetUnits[0],
riskAssetDecimals
);
stableCollateralDollarValue = _stableCollateralValue;
}
return (stableCollateralDollarValue, riskCollateralDollarValue);
}
/*
* Calculate new collateral units and natural unit. If necessary iterate through until naturalUnit
* found that supports non-zero unit amount. Here Underlying refers to the token underlying the
* collateral Set (i.e. ETH is underlying of riskCollateral Set).
*
* @param _currentCollateralUSDValue USD Value of current collateral set
* @param _replacementUnderlyingPrice Price of underlying token to be rebalanced into
* @param _replacementUnderlyingDecimals Amount of decimals in replacement token
* @param _replacementCollateralNaturalUnit Natural Unit of replacement collateral Set
* @return uint256[] Units array for new collateral set
* @return uint256 NaturalUnit for new collateral set
*/
function getNewCollateralSetParameters(
uint256 _currentCollateralUSDValue,
uint256 _replacementUnderlyingPrice,
uint256 _replacementUnderlyingDecimals,
uint256 _replacementCollateralNaturalUnit
)
internal
pure
returns (uint256[] memory, uint256)
{
// Calculate nextSetUnits such that the USD value of new Set is equal to the USD value of the Set
// being rebalanced out of
uint256[] memory nextSetUnits = new uint256[](1);
uint256 potentialNextUnit = 0;
uint256 naturalUnitMultiplier = 1;
uint256 nextNaturalUnit;
// Calculate next units. If nextUnit is 0 then bump natural unit (and thus units) by factor of
// ten until unit is greater than 0
while (potentialNextUnit == 0) {
nextNaturalUnit = _replacementCollateralNaturalUnit.mul(naturalUnitMultiplier);
potentialNextUnit = calculateNextSetUnits(
_currentCollateralUSDValue,
_replacementUnderlyingPrice,
_replacementUnderlyingDecimals,
nextNaturalUnit
);
naturalUnitMultiplier = naturalUnitMultiplier.mul(10);
}
nextSetUnits[0] = potentialNextUnit;
return (nextSetUnits, nextNaturalUnit);
}
/*
* Calculate new collateral units by making the new collateral USD value equal to the USD value of the
* Set currently collateralizing the Rebalancing Set. Here Underlying refers to the token underlying the
* collateral Set (i.e. ETH is underlying of riskCollateral Set).
*
* @param _currentCollateralUSDValue USD Value of current collateral set
* @param _replacementUnderlyingPrice Price of asset to be rebalanced into
* @param _replacementUnderlyingDecimals Amount of decimals in replacement collateral
* @param _replacementCollateralNaturalUnit Natural Unit of collateral set to be replacement
* @return uint256 New unit for new collateral set
*/
function calculateNextSetUnits(
uint256 _currentCollateralUSDValue,
uint256 _replacementUnderlyingPrice,
uint256 _replacementUnderlyingDecimals,
uint256 _replacementCollateralNaturalUnit
)
internal
pure
returns (uint256)
{
return _currentCollateralUSDValue
.mul(10 ** _replacementUnderlyingDecimals)
.mul(_replacementCollateralNaturalUnit)
.div(SET_TOKEN_DECIMALS.mul(_replacementUnderlyingPrice));
}
}
|
* @title MACOStrategyManager @author Set Protocol Rebalancing Manager contract for implementing the Moving Average (MA) Crossover Strategy between a risk asset's MA and the spot price of the risk asset. The time frame for the MA is defined on instantiation. When the spot price dips below the MA risk asset is sold for stable asset and vice versa when the spot price exceeds the MA. CHANGELOG: - Pass riskAssetOracleInstance in constructor - Pass list of collateral sets in constructor instead of individually - Read oracles using IOracle and IMetaOracleV2/ Equal to $1 since token prices are passed with 18 decimals
|
contract MACOStrategyManagerV2 {
using SafeMath for uint256;
uint256 constant AUCTION_LIB_PRICE_DIVISOR = 1000;
uint256 constant ALLOCATION_PRICE_RATIO_LIMIT = 4;
uint256 constant TEN_MINUTES_IN_SECONDS = 600;
uint256 constant STABLE_ASSET_PRICE = 10 ** 18;
uint256 constant SET_TOKEN_DECIMALS = 10 ** 18;
address public contractDeployer;
address public rebalancingSetTokenAddress;
address public coreAddress;
address public setTokenFactory;
address public auctionLibrary;
IMetaOracleV2 public movingAveragePriceFeedInstance;
IOracle public riskAssetOracleInstance;
address public stableAssetAddress;
address public riskAssetAddress;
address public stableCollateralAddress;
address public riskCollateralAddress;
uint256 public stableAssetDecimals;
uint256 public riskAssetDecimals;
uint256 public auctionTimeToPivot;
uint256 public movingAverageDays;
uint256 public lastCrossoverConfirmationTimestamp;
uint256 public crossoverConfirmationMinTime;
uint256 public crossoverConfirmationMaxTime;
event LogManagerProposal(
uint256 riskAssetPrice,
uint256 movingAveragePrice
);
constructor(
address _coreAddress,
IMetaOracleV2 _movingAveragePriceFeed,
IOracle _riskAssetOracle,
address _stableAssetAddress,
address _riskAssetAddress,
address[2] memory _collateralAddresses,
address _setTokenFactory,
address _auctionLibrary,
uint256 _movingAverageDays,
uint256 _auctionTimeToPivot,
uint256[2] memory _crossoverConfirmationBounds
)
public
Copyright 2019 Set Labs Inc.
{
contractDeployer = msg.sender;
coreAddress = _coreAddress;
movingAveragePriceFeedInstance = _movingAveragePriceFeed;
riskAssetOracleInstance = _riskAssetOracle;
setTokenFactory = _setTokenFactory;
auctionLibrary = _auctionLibrary;
stableAssetAddress = _stableAssetAddress;
riskAssetAddress = _riskAssetAddress;
stableCollateralAddress = _collateralAddresses[0];
riskCollateralAddress = _collateralAddresses[1];
auctionTimeToPivot = _auctionTimeToPivot;
movingAverageDays = _movingAverageDays;
lastCrossoverConfirmationTimestamp = 0;
crossoverConfirmationMinTime = _crossoverConfirmationBounds[0];
crossoverConfirmationMaxTime = _crossoverConfirmationBounds[1];
address[] memory initialStableCollateralComponents = ISetToken(_collateralAddresses[0]).getComponents();
address[] memory initialRiskCollateralComponents = ISetToken(_collateralAddresses[1]).getComponents();
require(
crossoverConfirmationMaxTime > crossoverConfirmationMinTime,
"MACOStrategyManager.constructor: Max confirmation time must be greater than min."
);
require(
initialStableCollateralComponents[0] == _stableAssetAddress,
"MACOStrategyManager.constructor: Stable collateral component must match stable asset."
);
require(
initialRiskCollateralComponents[0] == _riskAssetAddress,
"MACOStrategyManager.constructor: Risk collateral component must match risk asset."
);
stableAssetDecimals = ERC20Detailed(_stableAssetAddress).decimals();
riskAssetDecimals = ERC20Detailed(_riskAssetAddress).decimals();
}
function initialize(
address _rebalancingSetTokenAddress
)
external
{
require(
msg.sender == contractDeployer,
"MACOStrategyManager.initialize: Only the contract deployer can initialize"
);
require(
ICore(coreAddress).validSets(_rebalancingSetTokenAddress),
"MACOStrategyManager.initialize: Invalid or disabled RebalancingSetToken address"
);
rebalancingSetTokenAddress = _rebalancingSetTokenAddress;
contractDeployer = address(0);
}
function initialPropose()
external
{
require(
block.timestamp > lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMaxTime),
"MACOStrategyManager.initialPropose: 12 hours must pass before new proposal initiated"
);
FlexibleTimingManagerLibrary.validateManagerPropose(IRebalancingSetToken(rebalancingSetTokenAddress));
(
uint256 riskAssetPrice,
uint256 movingAveragePrice
) = getPriceData();
checkPriceTriggerMet(riskAssetPrice, movingAveragePrice);
lastCrossoverConfirmationTimestamp = block.timestamp;
}
function confirmPropose()
external
{
require(
block.timestamp >= lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMinTime) &&
block.timestamp <= lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMaxTime),
"MACOStrategyManager.confirmPropose: Confirming signal must be within bounds of the initial propose"
);
FlexibleTimingManagerLibrary.validateManagerPropose(IRebalancingSetToken(rebalancingSetTokenAddress));
(
uint256 riskAssetPrice,
uint256 movingAveragePrice
) = getPriceData();
checkPriceTriggerMet(riskAssetPrice, movingAveragePrice);
(
address nextSetAddress,
uint256 currentSetDollarValue,
uint256 nextSetDollarValue
) = determineNewAllocation(
riskAssetPrice
);
(
uint256 auctionStartPrice,
uint256 auctionPivotPrice
) = FlexibleTimingManagerLibrary.calculateAuctionPriceParameters(
currentSetDollarValue,
nextSetDollarValue,
TEN_MINUTES_IN_SECONDS,
AUCTION_LIB_PRICE_DIVISOR,
auctionTimeToPivot
);
IRebalancingSetToken(rebalancingSetTokenAddress).propose(
nextSetAddress,
auctionLibrary,
auctionTimeToPivot,
auctionStartPrice,
auctionPivotPrice
);
emit LogManagerProposal(
riskAssetPrice,
movingAveragePrice
);
}
function usingRiskCollateral()
internal
view
returns (bool)
{
address[] memory currentCollateralComponents = ISetToken(rebalancingSetTokenAddress).getComponents();
return (currentCollateralComponents[0] == riskCollateralAddress);
}
function getPriceData()
internal
view
returns(uint256, uint256)
{
uint256 riskAssetPrice = riskAssetOracleInstance.read();
uint256 movingAveragePrice = movingAveragePriceFeedInstance.read(movingAverageDays);
return (riskAssetPrice, movingAveragePrice);
}
function checkPriceTriggerMet(
uint256 _riskAssetPrice,
uint256 _movingAveragePrice
)
internal
view
{
if (usingRiskCollateral()) {
require(
_movingAveragePrice > _riskAssetPrice,
"MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be below moving average price"
);
require(
_movingAveragePrice < _riskAssetPrice,
"MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be above moving average price"
);
}
}
function checkPriceTriggerMet(
uint256 _riskAssetPrice,
uint256 _movingAveragePrice
)
internal
view
{
if (usingRiskCollateral()) {
require(
_movingAveragePrice > _riskAssetPrice,
"MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be below moving average price"
);
require(
_movingAveragePrice < _riskAssetPrice,
"MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be above moving average price"
);
}
}
} else {
function determineNewAllocation(
uint256 _riskAssetPrice
)
internal
returns (address, uint256, uint256)
{
(
uint256 stableCollateralDollarValue,
uint256 riskCollateralDollarValue
) = checkForNewAllocation(_riskAssetPrice);
(
address nextSetAddress,
uint256 currentSetDollarValue,
uint256 nextSetDollarValue
) = usingRiskCollateral() ? (stableCollateralAddress, riskCollateralDollarValue, stableCollateralDollarValue) :
(riskCollateralAddress, stableCollateralDollarValue, riskCollateralDollarValue);
return (nextSetAddress, currentSetDollarValue, nextSetDollarValue);
}
function checkForNewAllocation(
uint256 _riskAssetPrice
)
internal
returns(uint256, uint256)
{
SetTokenLibrary.SetDetails memory stableCollateralDetails = SetTokenLibrary.getSetDetails(
stableCollateralAddress
);
SetTokenLibrary.SetDetails memory riskCollateralDetails = SetTokenLibrary.getSetDetails(
riskCollateralAddress
);
uint256 stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
STABLE_ASSET_PRICE,
stableCollateralDetails.naturalUnit,
stableCollateralDetails.units[0],
stableAssetDecimals
);
uint256 riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
_riskAssetPrice,
riskCollateralDetails.naturalUnit,
riskCollateralDetails.units[0],
riskAssetDecimals
);
if (riskCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT) <= stableCollateralDollarValue ||
riskCollateralDollarValue >= stableCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT)) {
return determineNewCollateralParameters(
_riskAssetPrice,
stableCollateralDollarValue,
riskCollateralDollarValue,
stableCollateralDetails,
riskCollateralDetails
);
return (stableCollateralDollarValue, riskCollateralDollarValue);
}
}
function checkForNewAllocation(
uint256 _riskAssetPrice
)
internal
returns(uint256, uint256)
{
SetTokenLibrary.SetDetails memory stableCollateralDetails = SetTokenLibrary.getSetDetails(
stableCollateralAddress
);
SetTokenLibrary.SetDetails memory riskCollateralDetails = SetTokenLibrary.getSetDetails(
riskCollateralAddress
);
uint256 stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
STABLE_ASSET_PRICE,
stableCollateralDetails.naturalUnit,
stableCollateralDetails.units[0],
stableAssetDecimals
);
uint256 riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
_riskAssetPrice,
riskCollateralDetails.naturalUnit,
riskCollateralDetails.units[0],
riskAssetDecimals
);
if (riskCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT) <= stableCollateralDollarValue ||
riskCollateralDollarValue >= stableCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT)) {
return determineNewCollateralParameters(
_riskAssetPrice,
stableCollateralDollarValue,
riskCollateralDollarValue,
stableCollateralDetails,
riskCollateralDetails
);
return (stableCollateralDollarValue, riskCollateralDollarValue);
}
}
} else {
function determineNewCollateralParameters(
uint256 _riskAssetPrice,
uint256 _stableCollateralValue,
uint256 _riskCollateralValue,
SetTokenLibrary.SetDetails memory _stableCollateralDetails,
SetTokenLibrary.SetDetails memory _riskCollateralDetails
)
internal
returns (uint256, uint256)
{
uint256 stableCollateralDollarValue;
uint256 riskCollateralDollarValue;
if (usingRiskCollateral()) {
address[] memory nextSetComponents = new address[](1);
nextSetComponents[0] = stableAssetAddress;
(
uint256[] memory nextSetUnits,
uint256 nextNaturalUnit
) = getNewCollateralSetParameters(
_riskCollateralValue,
STABLE_ASSET_PRICE,
stableAssetDecimals,
_stableCollateralDetails.naturalUnit
);
stableCollateralAddress = ICore(coreAddress).createSet(
setTokenFactory,
nextSetComponents,
nextSetUnits,
nextNaturalUnit,
bytes32("STBLCollateral"),
bytes32("STBLMACO"),
""
);
stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
STABLE_ASSET_PRICE,
nextNaturalUnit,
nextSetUnits[0],
stableAssetDecimals
);
riskCollateralDollarValue = _riskCollateralValue;
address[] memory nextSetComponents = new address[](1);
nextSetComponents[0] = riskAssetAddress;
(
uint256[] memory nextSetUnits,
uint256 nextNaturalUnit
) = getNewCollateralSetParameters(
_stableCollateralValue,
_riskAssetPrice,
riskAssetDecimals,
_riskCollateralDetails.naturalUnit
);
riskCollateralAddress = ICore(coreAddress).createSet(
setTokenFactory,
nextSetComponents,
nextSetUnits,
nextNaturalUnit,
bytes32("RISKCollateral"),
bytes32("RISKMACO"),
""
);
riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
_riskAssetPrice,
nextNaturalUnit,
nextSetUnits[0],
riskAssetDecimals
);
stableCollateralDollarValue = _stableCollateralValue;
}
return (stableCollateralDollarValue, riskCollateralDollarValue);
}
function determineNewCollateralParameters(
uint256 _riskAssetPrice,
uint256 _stableCollateralValue,
uint256 _riskCollateralValue,
SetTokenLibrary.SetDetails memory _stableCollateralDetails,
SetTokenLibrary.SetDetails memory _riskCollateralDetails
)
internal
returns (uint256, uint256)
{
uint256 stableCollateralDollarValue;
uint256 riskCollateralDollarValue;
if (usingRiskCollateral()) {
address[] memory nextSetComponents = new address[](1);
nextSetComponents[0] = stableAssetAddress;
(
uint256[] memory nextSetUnits,
uint256 nextNaturalUnit
) = getNewCollateralSetParameters(
_riskCollateralValue,
STABLE_ASSET_PRICE,
stableAssetDecimals,
_stableCollateralDetails.naturalUnit
);
stableCollateralAddress = ICore(coreAddress).createSet(
setTokenFactory,
nextSetComponents,
nextSetUnits,
nextNaturalUnit,
bytes32("STBLCollateral"),
bytes32("STBLMACO"),
""
);
stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
STABLE_ASSET_PRICE,
nextNaturalUnit,
nextSetUnits[0],
stableAssetDecimals
);
riskCollateralDollarValue = _riskCollateralValue;
address[] memory nextSetComponents = new address[](1);
nextSetComponents[0] = riskAssetAddress;
(
uint256[] memory nextSetUnits,
uint256 nextNaturalUnit
) = getNewCollateralSetParameters(
_stableCollateralValue,
_riskAssetPrice,
riskAssetDecimals,
_riskCollateralDetails.naturalUnit
);
riskCollateralAddress = ICore(coreAddress).createSet(
setTokenFactory,
nextSetComponents,
nextSetUnits,
nextNaturalUnit,
bytes32("RISKCollateral"),
bytes32("RISKMACO"),
""
);
riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD(
_riskAssetPrice,
nextNaturalUnit,
nextSetUnits[0],
riskAssetDecimals
);
stableCollateralDollarValue = _stableCollateralValue;
}
return (stableCollateralDollarValue, riskCollateralDollarValue);
}
} else {
function getNewCollateralSetParameters(
uint256 _currentCollateralUSDValue,
uint256 _replacementUnderlyingPrice,
uint256 _replacementUnderlyingDecimals,
uint256 _replacementCollateralNaturalUnit
)
internal
pure
returns (uint256[] memory, uint256)
{
uint256[] memory nextSetUnits = new uint256[](1);
uint256 potentialNextUnit = 0;
uint256 naturalUnitMultiplier = 1;
uint256 nextNaturalUnit;
while (potentialNextUnit == 0) {
nextNaturalUnit = _replacementCollateralNaturalUnit.mul(naturalUnitMultiplier);
potentialNextUnit = calculateNextSetUnits(
_currentCollateralUSDValue,
_replacementUnderlyingPrice,
_replacementUnderlyingDecimals,
nextNaturalUnit
);
naturalUnitMultiplier = naturalUnitMultiplier.mul(10);
}
nextSetUnits[0] = potentialNextUnit;
return (nextSetUnits, nextNaturalUnit);
}
function getNewCollateralSetParameters(
uint256 _currentCollateralUSDValue,
uint256 _replacementUnderlyingPrice,
uint256 _replacementUnderlyingDecimals,
uint256 _replacementCollateralNaturalUnit
)
internal
pure
returns (uint256[] memory, uint256)
{
uint256[] memory nextSetUnits = new uint256[](1);
uint256 potentialNextUnit = 0;
uint256 naturalUnitMultiplier = 1;
uint256 nextNaturalUnit;
while (potentialNextUnit == 0) {
nextNaturalUnit = _replacementCollateralNaturalUnit.mul(naturalUnitMultiplier);
potentialNextUnit = calculateNextSetUnits(
_currentCollateralUSDValue,
_replacementUnderlyingPrice,
_replacementUnderlyingDecimals,
nextNaturalUnit
);
naturalUnitMultiplier = naturalUnitMultiplier.mul(10);
}
nextSetUnits[0] = potentialNextUnit;
return (nextSetUnits, nextNaturalUnit);
}
function calculateNextSetUnits(
uint256 _currentCollateralUSDValue,
uint256 _replacementUnderlyingPrice,
uint256 _replacementUnderlyingDecimals,
uint256 _replacementCollateralNaturalUnit
)
internal
pure
returns (uint256)
{
return _currentCollateralUSDValue
.mul(10 ** _replacementUnderlyingDecimals)
.mul(_replacementCollateralNaturalUnit)
.div(SET_TOKEN_DECIMALS.mul(_replacementUnderlyingPrice));
}
}
| 1,001,013 |
[
1,
10875,
51,
4525,
1318,
225,
1000,
4547,
868,
28867,
8558,
6835,
364,
19981,
326,
490,
13767,
27275,
261,
5535,
13,
19742,
1643,
19736,
3086,
279,
18404,
3310,
1807,
19316,
471,
326,
16463,
6205,
434,
326,
18404,
3310,
18,
1021,
813,
2623,
364,
326,
19316,
353,
2553,
603,
28380,
18,
5203,
326,
16463,
6205,
302,
7146,
5712,
326,
19316,
18404,
3310,
353,
272,
1673,
364,
14114,
3310,
471,
31842,
14690,
69,
1347,
326,
16463,
6205,
14399,
326,
19316,
18,
26267,
4842,
30,
225,
300,
10311,
18404,
6672,
23601,
1442,
316,
3885,
225,
300,
10311,
666,
434,
4508,
2045,
287,
1678,
316,
3885,
3560,
434,
28558,
225,
300,
2720,
578,
69,
9558,
1450,
1665,
16873,
471,
467,
2781,
23601,
58,
22,
19,
9057,
358,
271,
21,
3241,
1147,
19827,
854,
2275,
598,
6549,
15105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
14246,
51,
4525,
1318,
58,
22,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
5381,
432,
27035,
67,
14484,
67,
7698,
1441,
67,
2565,
26780,
916,
273,
4336,
31,
203,
565,
2254,
5034,
5381,
7981,
15277,
67,
7698,
1441,
67,
54,
789,
4294,
67,
8283,
273,
1059,
31,
203,
203,
565,
2254,
5034,
5381,
399,
1157,
67,
6236,
24080,
67,
706,
67,
11609,
273,
14707,
31,
203,
203,
565,
2254,
5034,
5381,
2347,
2782,
67,
3033,
4043,
67,
7698,
1441,
273,
1728,
2826,
6549,
31,
203,
565,
2254,
5034,
5381,
7855,
67,
8412,
67,
23816,
55,
273,
1728,
2826,
6549,
31,
203,
203,
565,
1758,
1071,
6835,
10015,
264,
31,
203,
565,
1758,
1071,
283,
28867,
694,
1345,
1887,
31,
203,
565,
1758,
1071,
2922,
1887,
31,
203,
565,
1758,
1071,
22629,
1733,
31,
203,
565,
1758,
1071,
279,
4062,
9313,
31,
203,
203,
565,
467,
2781,
23601,
58,
22,
1071,
12499,
17115,
5147,
8141,
1442,
31,
203,
565,
1665,
16873,
1071,
18404,
6672,
23601,
1442,
31,
203,
203,
565,
1758,
1071,
14114,
6672,
1887,
31,
203,
565,
1758,
1071,
18404,
6672,
1887,
31,
203,
565,
1758,
1071,
14114,
13535,
2045,
287,
1887,
31,
203,
565,
1758,
1071,
18404,
13535,
2045,
287,
1887,
31,
203,
203,
565,
2254,
5034,
1071,
14114,
6672,
31809,
31,
203,
565,
2254,
5034,
1071,
18404,
6672,
31809,
31,
203,
203,
565,
2254,
5034,
1071,
279,
4062,
950,
774,
18239,
31,
203,
565,
2254,
5034,
1071,
12499,
17115,
9384,
31,
203,
565,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-19
*/
pragma solidity ^0.5.17;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0);
c = a / b;
}
}
contract SPICE is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "SPICE.swap";
symbol = "SPICE";
decimals = 18;
_totalSupply = 1000000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
}
|
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
|
constructor() public {
name = "SPICE.swap";
symbol = "SPICE";
decimals = 18;
_totalSupply = 1000000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 15,119,458 |
[
1,
442,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1435,
1071,
288,
203,
3639,
508,
273,
315,
22694,
1441,
18,
22270,
14432,
203,
3639,
3273,
273,
315,
22694,
1441,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
2787,
11706,
31,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.13;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
revert();
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/*
* Fix for the ERC20 short address attack
*/
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
/**
* @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 onlyPayloadSize(2 * 32) returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract RBInformationStore is Ownable {
address public profitContainerAddress;
address public companyWalletAddress;
uint public etherRatioForOwner;
address public multiSigAddress;
address public accountAddressForSponsee;
bool public isPayableEnabledForAll = true;
modifier onlyMultiSig() {
require(multiSigAddress == msg.sender);
_;
}
function RBInformationStore
(
address _profitContainerAddress,
address _companyWalletAddress,
uint _etherRatioForOwner,
address _multiSigAddress,
address _accountAddressForSponsee
) {
profitContainerAddress = _profitContainerAddress;
companyWalletAddress = _companyWalletAddress;
etherRatioForOwner = _etherRatioForOwner;
multiSigAddress = _multiSigAddress;
accountAddressForSponsee = _accountAddressForSponsee;
}
function changeProfitContainerAddress(address _address) onlyMultiSig {
profitContainerAddress = _address;
}
function changeCompanyWalletAddress(address _address) onlyMultiSig {
companyWalletAddress = _address;
}
function changeEtherRatioForOwner(uint _value) onlyMultiSig {
etherRatioForOwner = _value;
}
function changeMultiSigAddress(address _address) onlyMultiSig {
multiSigAddress = _address;
}
function changeOwner(address _address) onlyMultiSig {
owner = _address;
}
function changeAccountAddressForSponsee(address _address) onlyMultiSig {
accountAddressForSponsee = _address;
}
function changeIsPayableEnabledForAll() onlyMultiSig {
isPayableEnabledForAll = !isPayableEnabledForAll;
}
}
contract Rate {
uint public ETH_USD_rate;
RBInformationStore public rbInformationStore;
modifier onlyOwner() {
require(msg.sender == rbInformationStore.owner());
_;
}
function Rate(uint _rate, address _address) {
ETH_USD_rate = _rate;
rbInformationStore = RBInformationStore(_address);
}
function setRate(uint _rate) onlyOwner {
ETH_USD_rate = _rate;
}
}
/**
@title SponseeTokenModel
*/
contract SponseeTokenModel is StandardToken {
string public name;
string public symbol;
uint8 public decimals = 0;
uint public totalSupply = 0;
uint public cap = 100000000; // maximum cap = 1 000 000 $ = 100 000 000 tokens
uint public minimumSupport = 500; // minimum support is 5$(500 cents)
uint public etherRatioForInvestor = 10; // etherRatio (10%) to send ether to investor
address public sponseeAddress;
bool public isPayableEnabled = true;
RBInformationStore public rbInformationStore;
Rate public rate;
event LogReceivedEther(address indexed from, address indexed to, uint etherValue, string tokenName);
event LogBuy(address indexed from, address indexed to, uint indexed value, uint paymentId);
event LogRollbackTransfer(address indexed from, address indexed to, uint value);
event LogExchange(address indexed from, address indexed token, uint value);
event LogIncreaseCap(uint value);
event LogDecreaseCap(uint value);
event LogSetRBInformationStoreAddress(address indexed to);
event LogSetName(string name);
event LogSetSymbol(string symbol);
event LogMint(address indexed to, uint value);
event LogChangeSponseeAddress(address indexed to);
event LogChangeIsPayableEnabled(bool flag);
modifier onlyAccountAddressForSponsee() {
require(rbInformationStore.accountAddressForSponsee() == msg.sender);
_;
}
modifier onlyMultiSig() {
require(rbInformationStore.multiSigAddress() == msg.sender);
_;
}
// constructor
function SponseeTokenModel(
string _name,
string _symbol,
address _rbInformationStoreAddress,
address _rateAddress,
address _sponsee
) {
name = _name;
symbol = _symbol;
rbInformationStore = RBInformationStore(_rbInformationStoreAddress);
rate = Rate(_rateAddress);
sponseeAddress = _sponsee;
}
/**
@notice Receive ether from any EOA accounts. Amount of ether received in this function is distributed to 3 parts.
One is a profitContainerAddress which is address of containerWallet to dividend to investor of Boost token.
Another is an ownerAddress which is address of owner of REALBOOST site.
The other is an sponseeAddress which is address of owner of this contract.
Then, return token of this contract to msg.sender related to the amount of ether that msg.sender sent and rate (US cent) of ehter stored in Rate contract.
*/
function() payable {
// check condition
require(isPayableEnabled && rbInformationStore.isPayableEnabledForAll());
// check validation
if (msg.value <= 0) { revert(); }
// calculate support amount in US
uint supportedAmount = msg.value.mul(rate.ETH_USD_rate()).div(10**18);
// if support is less than minimum => return money to supporter
if (supportedAmount < minimumSupport) { revert(); }
// calculate the ratio of Ether for distribution
uint etherRatioForOwner = rbInformationStore.etherRatioForOwner();
uint etherRatioForSponsee = uint(100).sub(etherRatioForOwner).sub(etherRatioForInvestor);
/* divide Ether */
// calculate
uint etherForOwner = msg.value.mul(etherRatioForOwner).div(100);
uint etherForInvestor = msg.value.mul(etherRatioForInvestor).div(100);
uint etherForSponsee = msg.value.mul(etherRatioForSponsee).div(100);
// get address
address profitContainerAddress = rbInformationStore.profitContainerAddress();
address companyWalletAddress = rbInformationStore.companyWalletAddress();
// send Ether
if (!profitContainerAddress.send(etherForInvestor)) { revert(); }
if (!companyWalletAddress.send(etherForOwner)) { revert(); }
if (!sponseeAddress.send(etherForSponsee)) { revert(); }
// token amount is transfered to sender
// 1 token = 1 cent, 1 usd = 100 cents
uint tokenAmount = msg.value.mul(rate.ETH_USD_rate()).div(10**18);
// add tokens
balances[msg.sender] = balances[msg.sender].add(tokenAmount);
// increase total supply
totalSupply = totalSupply.add(tokenAmount);
// check cap
if (totalSupply > cap) { revert(); }
// send Event
LogExchange(msg.sender, this, tokenAmount);
LogReceivedEther(msg.sender, this, msg.value, name);
Transfer(address(0x0), msg.sender, tokenAmount);
}
/**
@notice Change rbInformationStoreAddress.
@param _address The address of new rbInformationStore
*/
function setRBInformationStoreAddress(address _address) onlyMultiSig {
rbInformationStore = RBInformationStore(_address);
// send Event
LogSetRBInformationStoreAddress(_address);
}
/**
@notice Change name.
@param _name The new name of token
*/
function setName(string _name) onlyAccountAddressForSponsee {
name = _name;
// send Event
LogSetName(_name);
}
/**
@notice Change symbol.
@param _symbol The new symbol of token
*/
function setSymbol(string _symbol) onlyAccountAddressForSponsee {
symbol = _symbol;
// send Event
LogSetSymbol(_symbol);
}
/**
@notice Mint new token amount.
@param _address The address that new token amount is added
@param _value The new amount of token
*/
function mint(address _address, uint _value) onlyAccountAddressForSponsee {
// add tokens
balances[_address] = balances[_address].add(_value);
// increase total supply
totalSupply = totalSupply.add(_value);
// check cap
if (totalSupply > cap) { revert(); }
// send Event
LogMint(_address, _value);
Transfer(address(0x0), _address, _value);
}
/**
@notice Increase cap.
@param _value The amount of token that should be increased
*/
function increaseCap(uint _value) onlyAccountAddressForSponsee {
// change cap here
cap = cap.add(_value);
// send Event
LogIncreaseCap(_value);
}
/**
@notice Decrease cap.
@param _value The amount of token that should be decreased
*/
function decreaseCap(uint _value) onlyAccountAddressForSponsee {
// check whether cap is lower than totalSupply or not
if (totalSupply > cap.sub(_value)) { revert(); }
// change cap here
cap = cap.sub(_value);
// send Event
LogDecreaseCap(_value);
}
/**
@notice Rollback transfer.
@param _from The EOA address for rollback transfer
@param _to The EOA address for rollback transfer
@param _value The number of token for rollback transfer
*/
function rollbackTransfer(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) onlyMultiSig {
balances[_to] = balances[_to].sub(_value);
balances[_from] = balances[_from].add(_value);
// send Event
LogRollbackTransfer(_from, _to, _value);
Transfer(_from, _to, _value);
}
/**
@notice Transfer from msg.sender for downloading of content.
@param _to The EOA address for buy content
@param _value The number of token for buy content
@param _paymentId The id of content which msg.sender want to buy
*/
function buy(address _to, uint _value, uint _paymentId) {
transfer(_to, _value);
// send Event
LogBuy(msg.sender, _to, _value, _paymentId);
}
/**
@notice This method will change old sponsee address with a new one.
@param _newAddress new address is set
*/
function changeSponseeAddress(address _newAddress) onlyAccountAddressForSponsee {
sponseeAddress = _newAddress;
// send Event
LogChangeSponseeAddress(_newAddress);
}
/**
@notice This method will change isPayableEnabled flag.
*/
function changeIsPayableEnabled() onlyMultiSig {
isPayableEnabled = !isPayableEnabled;
// send Event
LogChangeIsPayableEnabled(isPayableEnabled);
}
}
|
minimum support is 5$(500 cents)
|
uint public minimumSupport = 500;
| 905,745 |
[
1,
15903,
2865,
353,
1381,
8,
12,
12483,
276,
4877,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
1071,
5224,
6289,
273,
6604,
31,
7734,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xb8D3fc790f38b332572f8604fA6866E29e522946/sources/contracts/provers/BirthCertificateProver.sol
|
* @notice handles minting the token after a fact is stored @param fact the fact which was stored/
|
function _afterStore(Fact memory fact, bool alreadyStored) internal override {
if (!alreadyStored) {
token.mint(fact.account, 0);
}
}
| 9,787,462 |
[
1,
24111,
312,
474,
310,
326,
1147,
1839,
279,
5410,
353,
4041,
225,
5410,
326,
5410,
1492,
1703,
4041,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
5205,
2257,
12,
9766,
3778,
5410,
16,
1426,
1818,
18005,
13,
2713,
3849,
288,
203,
3639,
309,
16051,
17583,
18005,
13,
288,
203,
5411,
1147,
18,
81,
474,
12,
3493,
18,
4631,
16,
374,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/***
* https://templeofeth.io
*
* Tiki Madness.
*
* 6 Tiki Masks are flipping
* Price increases by 32% every flip.
*
* 10% of rise buyer gets TMPL tokens in the TempleOfETH.
* 5% of rise goes to tiki holder fund.
* 5% of rise goes to temple management.
* 2% of rise goes to the God Tiki owner (The Tiki with the lowest value.)
* The rest (110%) goes to previous owner.
* Over 1 hour price will fall to 12.5% of the Tiki Holder fund..
* Holders after 1 hours with no flip can collect the holder fund.
*
* Temple Warning: Do not play with more than you can afford to lose.
*/
contract TempleInterface {
function purchaseFor(address _referredBy, address _customerAddress) public payable returns (uint256);
}
contract TikiMadness {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Access modifier for owner functions
modifier onlyOwner() {
require(msg.sender == contractOwner);
_;
}
/// @dev Prevent contract calls.
modifier notContract() {
require(tx.origin == msg.sender);
_;
}
/// @dev notPaused
modifier notPaused() {
require(now > startTime);
_;
}
/// @dev easyOnGas
modifier easyOnGas() {
require(tx.gasprice < 99999999999);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenSold(
uint256 indexed tokenId,
uint256 price,
address prevOwner,
address newOwner,
string name
);
/*==============================
= CONSTANTS =
==============================*/
uint256 private increaseRatePercent = 132;
uint256 private godTikiPercent = 2; // 2% of all sales
uint256 private devFeePercent = 5;
uint256 private bagHolderFundPercent = 5;
uint256 private exchangeTokenPercent = 10;
uint256 private previousOwnerPercent = 110;
uint256 private priceFallDuration = 1 hours;
/*==============================
= STORAGE =
==============================*/
/// @dev A mapping from tiki IDs to the address that owns them.
mapping (uint256 => address) public tikiIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
mapping (address => uint256) private ownershipTokenCount;
// @dev The address of the owner
address public contractOwner;
/// @dev Start Time
uint256 public startTime = 1543692600; // GMT: Saturday, December 1, 2018 19:30:00 PM
// @dev Current dev fee
uint256 public currentDevFee = 0;
// @dev The address of the temple contract
address public templeOfEthaddress = 0x0e21902d93573c18fd0acbadac4a5464e9732f54; // MAINNET
/// @dev Interface to temple
TempleInterface public templeContract;
/*==============================
= DATATYPES =
==============================*/
struct TikiMask {
string name;
uint256 basePrice; // current base price = 12.5% of holder fund.
uint256 highPrice;
uint256 fallDuration;
uint256 saleTime; // when was sold last
uint256 bagHolderFund;
}
TikiMask [6] public tikiMasks;
constructor () public {
contractOwner = msg.sender;
templeContract = TempleInterface(templeOfEthaddress);
TikiMask memory _Huracan = TikiMask({
name: "Huracan",
basePrice: 0.015 ether,
highPrice: 0.015 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[0] = _Huracan;
TikiMask memory _Itzamna = TikiMask({
name: "Itzamna",
basePrice: 0.018 ether,
highPrice: 0.018 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[1] = _Itzamna;
TikiMask memory _Mitnal = TikiMask({
name: "Mitnal",
basePrice: 0.020 ether,
highPrice: 0.020 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[2] = _Mitnal;
TikiMask memory _Tepeu = TikiMask({
name: "Tepeu",
basePrice: 0.025 ether,
highPrice: 0.025 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[3] = _Tepeu;
TikiMask memory _Usukan = TikiMask({
name: "Usukan",
basePrice: 0.030 ether,
highPrice: 0.030 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[4] = _Usukan;
TikiMask memory _Voltan = TikiMask({
name: "Voltan",
basePrice: 0.035 ether,
highPrice: 0.035 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[5] = _Voltan;
_transfer(0x0, contractOwner, 0);
_transfer(0x0, contractOwner, 1);
_transfer(0x0, contractOwner, 2);
_transfer(0x0, contractOwner, 3);
_transfer(0x0, contractOwner, 4);
_transfer(0x0, contractOwner, 5);
}
/// For querying balance of a particular account
/// @param _owner The address for balance query
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
/// @notice Returns all the relevant information about a specific tiki.
/// @param _tokenId The tokenId of the tiki of interest.
function getTiki(uint256 _tokenId) public view returns (
string tikiName,
uint256 currentPrice,
uint256 basePrice,
address currentOwner,
uint256 bagHolderFund,
bool isBagFundAvailable
) {
TikiMask storage tiki = tikiMasks[_tokenId];
tikiName = tiki.name;
currentPrice = priceOf(_tokenId);
basePrice = tiki.basePrice;
currentOwner = tikiIndexToOwner[_tokenId];
bagHolderFund = tiki.bagHolderFund;
isBagFundAvailable = now > (tiki.saleTime + priceFallDuration);
}
/// For querying owner of token
/// @param _tokenId The tokenID for owner inquiry
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = tikiIndexToOwner[_tokenId];
require(owner != address(0));
}
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId , address _referredBy) public payable notContract notPaused easyOnGas {
address oldOwner = tikiIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 currentPrice = priceOf(_tokenId);
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= currentPrice);
uint256 previousOwnerGets = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),previousOwnerPercent);
uint256 exchangeTokensAmount = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),exchangeTokenPercent);
uint256 devFeeAmount = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),devFeePercent);
uint256 bagHolderFundAmount = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),bagHolderFundPercent);
uint256 godTikiGets = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),godTikiPercent);
if (msg.value>currentPrice){
bagHolderFundAmount = bagHolderFundAmount + (msg.value-currentPrice); // overbidding should be discouraged
}
currentDevFee = currentDevFee + devFeeAmount;
// buy the tokens for this player and include the referrer too (templenodes work)
templeContract.purchaseFor.value(exchangeTokensAmount)(_referredBy, msg.sender);
// the god tiki receives their amount.
ownerOf(godTiki()).transfer(godTikiGets);
// do the sale
_transfer(oldOwner, newOwner, _tokenId);
// set new price and saleTime
tikiMasks[_tokenId].highPrice = SafeMath.mul(SafeMath.div(currentPrice,100),increaseRatePercent);
tikiMasks[_tokenId].saleTime = now;
tikiMasks[_tokenId].bagHolderFund = tikiMasks[_tokenId].bagHolderFund + bagHolderFundAmount;
tikiMasks[_tokenId].basePrice = max(tikiMasks[_tokenId].basePrice,SafeMath.div(tikiMasks[_tokenId].bagHolderFund,8)); // 12.5% of the holder fund
// Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
if (oldOwner.send(previousOwnerGets)){}
}
emit onTokenSold(_tokenId, currentPrice, oldOwner, newOwner, tikiMasks[_tokenId].name);
}
/// @dev this is the tiki with the current lowest value - it receives 2% of ALL sales.
function godTiki() public view returns (uint256 tokenId) {
uint256 lowestPrice = priceOf(0);
uint256 lowestId = 0;
for(uint x=1;x<6;x++){
if(priceOf(x)<lowestPrice){
lowestId=x;
}
}
return lowestId;
}
/// @dev calculate the current price of this token
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
TikiMask storage tiki = tikiMasks[_tokenId];
uint256 secondsPassed = now - tiki.saleTime;
if (secondsPassed >= tiki.fallDuration || tiki.highPrice==tiki.basePrice) {
return tiki.basePrice;
}
uint256 totalPriceChange = tiki.highPrice - tiki.basePrice;
uint256 currentPriceChange = totalPriceChange * secondsPassed /tiki.fallDuration;
uint256 currentPrice = tiki.highPrice - currentPriceChange;
return currentPrice;
}
/// @dev allow holder to collect fund if time is expired
function collectBagHolderFund(uint256 _tokenId) public notPaused {
require(msg.sender == tikiIndexToOwner[_tokenId]);
uint256 bagHolderFund;
bool isBagFundAvailable = false;
(
,
,
,
,
bagHolderFund,
isBagFundAvailable
) = getTiki(_tokenId);
require(isBagFundAvailable && bagHolderFund > 0);
uint256 amount = bagHolderFund;
tikiMasks[_tokenId].bagHolderFund = 0;
tikiMasks[_tokenId].basePrice = 0.015 ether;
msg.sender.transfer(amount);
}
function paused() public view returns (bool){
return (now < startTime);
}
/*** PRIVATE FUNCTIONS ***/
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
/// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == tikiIndexToOwner[_tokenId];
}
/// @dev Assigns ownership of a specific token to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// no transfer to contract
uint length;
assembly { length := extcodesize(_to) }
require (length == 0);
ownershipTokenCount[_to]++;
//transfer ownership
tikiIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
}
}
/// @dev Not a charity
function collectDevFees() public onlyOwner {
if (currentDevFee < address(this).balance){
uint256 amount = currentDevFee;
currentDevFee = 0;
contractOwner.transfer(amount);
}
}
/// @dev stop and start
function max(uint a, uint b) private pure returns (uint) {
return a > b ? a : b;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
the god tiki receives their amount.
|
ownerOf(godTiki()).transfer(godTikiGets);
| 2,518,114 |
[
1,
5787,
314,
369,
268,
6169,
17024,
3675,
3844,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3410,
951,
12,
75,
369,
56,
6169,
1435,
2934,
13866,
12,
75,
369,
56,
6169,
3002,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/8453/0xF0363DBD4Efb76fC72Aa4df7D8b956269c9052A6/sources/contracts/interfaces/IAllowance.sol
|
* allowanceRemoved This event is fired when an allowance is deleted for a recipient key @param operator the message sender @param allowanceId the allowance ID that was removed/
|
event allowanceRemoved(address operator, bytes32 allowanceId);
| 11,538,630 |
[
1,
5965,
1359,
10026,
1220,
871,
353,
15950,
1347,
392,
1699,
1359,
353,
4282,
364,
279,
8027,
498,
225,
3726,
4202,
326,
883,
5793,
225,
1699,
1359,
548,
565,
326,
1699,
1359,
1599,
716,
1703,
3723,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
871,
1699,
1359,
10026,
12,
2867,
3726,
16,
1731,
1578,
1699,
1359,
548,
1769,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xb38827497dAf7f28261910e33e22219de087C8f5/sources/contracts/BlurExchange.sol
|
* @dev Verify ECDSA signature @param signer Expected signer @param digest Signature preimage @param v v @param r r @param s s/
|
function _verify(
address signer,
bytes32 digest,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (bool) {
require(v == 27 || v == 28, "Invalid v parameter");
address recoveredSigner = ecrecover(digest, v, r, s);
if (recoveredSigner == address(0)) {
return false;
return signer == recoveredSigner;
}
}
| 2,788,928 |
[
1,
8097,
7773,
19748,
3372,
225,
10363,
13219,
10363,
225,
5403,
9249,
675,
2730,
225,
331,
331,
225,
436,
436,
225,
272,
272,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
8705,
12,
203,
3639,
1758,
10363,
16,
203,
3639,
1731,
1578,
5403,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
90,
422,
12732,
747,
331,
422,
9131,
16,
315,
1941,
331,
1569,
8863,
203,
3639,
1758,
24616,
15647,
273,
425,
1793,
3165,
12,
10171,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
309,
261,
266,
16810,
15647,
422,
1758,
12,
20,
3719,
288,
203,
1850,
327,
629,
31,
203,
1850,
327,
10363,
422,
24616,
15647,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-30
*/
pragma solidity 0.6.12;
// SPDX-License-Identifier: MIT
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
}
interface StandardToken {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
interface IUniswapV2Router02 {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
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 swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
}
interface IYearnWETH{
function balanceOf(address account) external view returns (uint256);
function withdraw(uint256 amount, address recipient) external returns(uint256);
function pricePerShare() external view returns(uint256);
function deposit(uint256 _amount) external returns(uint256);
function deposit(uint256 _amount, address recipient) external returns(uint256);
}
interface IWETH is StandardToken{
function withdraw(uint256 amount) external returns(uint256);
function deposit() external payable;
}
interface IStakeAndYield {
function getRewardToken() external view returns(address);
function totalSupply(uint256 stakeType) external view returns(uint256);
function notifyRewardAmount(uint256 reward, uint256 stakeType) external;
}
interface IAutomaticMarketMaker {
function buy(uint256 _tokenAmount) external payable;
function sell(uint256 tokenAmount, uint256 _etherAmount) external;
function calculatePurchaseReturn(uint256 etherAmount) external returns (uint256);
function calculateSaleReturn(uint256 tokenAmount) external returns (uint256);
function withdrawPayments(address payable payee) external;
}
contract Controller is Ownable {
using SafeMath for uint256;
uint256 MAX_INT = type(uint256).max;
IWETH public weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public DEUS = 0x3b62F3820e0B035cc4aD602dECe6d796BC325325;
IUniswapV2Router02 public uniswapRouter = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
IYearnWETH public yweth = IYearnWETH(0xa9fE4601811213c340e850ea305481afF02f5b28);
IAutomaticMarketMaker public AMM = IAutomaticMarketMaker(0xD77700fC3C78d1Cb3aCb1a9eAC891ff59bC7946D);
// strategy => vault
mapping (address => address) public strategies;
// vault => strategy
mapping (address => address) public vaults;
// vault => exitToken
mapping (address => address) public exitTokens;
// vault => multiplier
mapping (address => uint256) public multipliers;
address public operator;
uint256 public minBuyFromAMM = 1 ether;
modifier onlyOwnerOrOperator(){
require(
msg.sender == owner() || msg.sender == operator,
"!owner"
);
_;
}
constructor() public{
StandardToken(weth).approve(address(uniswapRouter), MAX_INT);
StandardToken(weth).approve(address(yweth), MAX_INT);
StandardToken(DEUS).approve(address(uniswapRouter), MAX_INT);
}
modifier onlyStragey(){
require(strategies[msg.sender] != address(0), "!strategy");
_;
}
modifier onlyVault(){
require(vaults[msg.sender] != address(0), "!vault");
_;
}
modifier onlyExitableVault(){
require(vaults[msg.sender] != address(0) &&
exitTokens[msg.sender] != address(0)
, "!exitable vault");
_;
}
receive() external payable {
}
function depositWETH() external payable{
weth.deposit{value: msg.value}();
}
function addStrategy(address vault, address strategy,
address exitToken, uint256 multiplier
) external onlyOwner{
require(vault != address(0) && strategy!=address(0), "0x0");
strategies[strategy] = vault;
vaults[vault] = strategy;
exitTokens[vault] = exitToken;
multipliers[vault] = multiplier;
StandardToken(weth).approve(strategy, MAX_INT);
}
function delStrategy(address vault, address strategy) external onlyOwner{
require(vault != address(0) && strategy!=address(0), "0x0");
strategies[strategy] = address(0);
vaults[vault] = address(0);
StandardToken(weth).approve(strategy, 0);
}
function setOperator(address _addr) public onlyOwner{
operator = _addr;
}
function setMultiplier(
address vault,
uint256 multiplier
) external onlyOwnerOrOperator{
require(vaults[vault] != address(0), "!vault");
multipliers[vault] = multiplier;
}
function withdrawETH(uint256 amount) public onlyStragey{
msg.sender.transfer(amount);
}
function sendExitToken(
address _user,
uint256 _amount
) public onlyExitableVault{
uint256 amount = _amount.mul(multipliers[msg.sender]).div(1 ether);
require(amount > 0, "0 amount");
StandardToken(exitTokens[msg.sender]).transfer(
_user, amount
);
}
function depositForStrategy(uint256 amount, address addr) public onlyStragey{
yweth.deposit(amount, addr);
}
function buyForStrategy(
uint256 amount,
address rewardToken,
address recipient
) public onlyStragey{
address[] memory path;
uint256[] memory amounts;
uint256 tokenAmount = amount;
if(amount < minBuyFromAMM){
path[0] = address(weth);
path[1] = DEUS;
path[2] = rewardToken;
}else{
path[0] = DEUS;
path[1] = rewardToken;
weth.withdraw(amount);
tokenAmount = AMM.calculatePurchaseReturn(amount);
AMM.buy{value: amount}(tokenAmount);
}
amounts = uniswapRouter.swapExactTokensForTokens(
tokenAmount, 1, path, recipient, block.timestamp
);
IStakeAndYield(recipient).notifyRewardAmount(
amounts[amounts.length-1],
2 // yield
);
}
function setMinBuyFromAMM(uint256 _val) public onlyOwner{
minBuyFromAMM = _val;
}
function emergencyWithdrawETH(uint256 amount, address addr) public onlyOwner{
require(addr != address(0));
payable(addr).transfer(amount);
}
function emergencyWithdrawERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
StandardToken(_tokenAddr).transfer(_to, _amount);
}
function getStrategy(address vault) public view returns(address){
return vaults[vault];
}
}
|
strategy => vault vault => strategy vault => exitToken vault => multiplier
|
contract Controller is Ownable {
using SafeMath for uint256;
uint256 MAX_INT = type(uint256).max;
IWETH public weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public DEUS = 0x3b62F3820e0B035cc4aD602dECe6d796BC325325;
IUniswapV2Router02 public uniswapRouter = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
IYearnWETH public yweth = IYearnWETH(0xa9fE4601811213c340e850ea305481afF02f5b28);
IAutomaticMarketMaker public AMM = IAutomaticMarketMaker(0xD77700fC3C78d1Cb3aCb1a9eAC891ff59bC7946D);
mapping (address => address) public strategies;
mapping (address => address) public vaults;
mapping (address => address) public exitTokens;
mapping (address => uint256) public multipliers;
address public operator;
uint256 public minBuyFromAMM = 1 ether;
modifier onlyOwnerOrOperator(){
require(
msg.sender == owner() || msg.sender == operator,
"!owner"
);
_;
}
constructor() public{
StandardToken(weth).approve(address(uniswapRouter), MAX_INT);
StandardToken(weth).approve(address(yweth), MAX_INT);
StandardToken(DEUS).approve(address(uniswapRouter), MAX_INT);
}
modifier onlyStragey(){
require(strategies[msg.sender] != address(0), "!strategy");
_;
}
modifier onlyVault(){
require(vaults[msg.sender] != address(0), "!vault");
_;
}
modifier onlyExitableVault(){
require(vaults[msg.sender] != address(0) &&
exitTokens[msg.sender] != address(0)
, "!exitable vault");
_;
}
receive() external payable {
}
function depositWETH() external payable{
}
weth.deposit{value: msg.value}();
function addStrategy(address vault, address strategy,
address exitToken, uint256 multiplier
) external onlyOwner{
require(vault != address(0) && strategy!=address(0), "0x0");
strategies[strategy] = vault;
vaults[vault] = strategy;
exitTokens[vault] = exitToken;
multipliers[vault] = multiplier;
StandardToken(weth).approve(strategy, MAX_INT);
}
function delStrategy(address vault, address strategy) external onlyOwner{
require(vault != address(0) && strategy!=address(0), "0x0");
strategies[strategy] = address(0);
vaults[vault] = address(0);
StandardToken(weth).approve(strategy, 0);
}
function setOperator(address _addr) public onlyOwner{
operator = _addr;
}
function setMultiplier(
address vault,
uint256 multiplier
) external onlyOwnerOrOperator{
require(vaults[vault] != address(0), "!vault");
multipliers[vault] = multiplier;
}
function withdrawETH(uint256 amount) public onlyStragey{
msg.sender.transfer(amount);
}
function sendExitToken(
address _user,
uint256 _amount
) public onlyExitableVault{
uint256 amount = _amount.mul(multipliers[msg.sender]).div(1 ether);
require(amount > 0, "0 amount");
StandardToken(exitTokens[msg.sender]).transfer(
_user, amount
);
}
function depositForStrategy(uint256 amount, address addr) public onlyStragey{
yweth.deposit(amount, addr);
}
function buyForStrategy(
uint256 amount,
address rewardToken,
address recipient
) public onlyStragey{
address[] memory path;
uint256[] memory amounts;
uint256 tokenAmount = amount;
if(amount < minBuyFromAMM){
path[0] = address(weth);
path[1] = DEUS;
path[2] = rewardToken;
path[0] = DEUS;
path[1] = rewardToken;
weth.withdraw(amount);
tokenAmount = AMM.calculatePurchaseReturn(amount);
}
amounts = uniswapRouter.swapExactTokensForTokens(
tokenAmount, 1, path, recipient, block.timestamp
);
IStakeAndYield(recipient).notifyRewardAmount(
amounts[amounts.length-1],
);
}
function buyForStrategy(
uint256 amount,
address rewardToken,
address recipient
) public onlyStragey{
address[] memory path;
uint256[] memory amounts;
uint256 tokenAmount = amount;
if(amount < minBuyFromAMM){
path[0] = address(weth);
path[1] = DEUS;
path[2] = rewardToken;
path[0] = DEUS;
path[1] = rewardToken;
weth.withdraw(amount);
tokenAmount = AMM.calculatePurchaseReturn(amount);
}
amounts = uniswapRouter.swapExactTokensForTokens(
tokenAmount, 1, path, recipient, block.timestamp
);
IStakeAndYield(recipient).notifyRewardAmount(
amounts[amounts.length-1],
);
}
}else{
AMM.buy{value: amount}(tokenAmount);
function setMinBuyFromAMM(uint256 _val) public onlyOwner{
minBuyFromAMM = _val;
}
function emergencyWithdrawETH(uint256 amount, address addr) public onlyOwner{
require(addr != address(0));
payable(addr).transfer(amount);
}
function emergencyWithdrawERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
StandardToken(_tokenAddr).transfer(_to, _amount);
}
function getStrategy(address vault) public view returns(address){
return vaults[vault];
}
}
| 2,050,172 |
[
1,
14914,
516,
9229,
9229,
516,
6252,
9229,
516,
2427,
1345,
9229,
516,
15027,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
6629,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
2254,
5034,
4552,
67,
3217,
273,
618,
12,
11890,
5034,
2934,
1896,
31,
203,
565,
467,
59,
1584,
44,
1071,
341,
546,
273,
467,
59,
1584,
44,
12,
20,
14626,
3103,
7598,
37,
5520,
70,
3787,
23,
8090,
28,
40,
20,
37,
20,
73,
25,
39,
24,
42,
5324,
73,
1880,
29,
6840,
23,
39,
27,
4313,
39,
71,
22,
1769,
203,
565,
1758,
1071,
2030,
3378,
273,
374,
92,
23,
70,
8898,
42,
7414,
3462,
73,
20,
38,
4630,
25,
952,
24,
69,
40,
26,
3103,
72,
7228,
73,
26,
72,
7235,
26,
16283,
1578,
25,
1578,
25,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
640,
291,
91,
438,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
377,
202,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
565,
11272,
203,
203,
565,
467,
61,
73,
1303,
59,
1584,
44,
1071,
677,
91,
546,
273,
467,
61,
73,
1303,
59,
1584,
44,
12,
20,
6995,
29,
74,
41,
8749,
1611,
11861,
2138,
3437,
71,
5026,
20,
73,
28,
3361,
24852,
5082,
6564,
11861,
1727,
42,
3103,
74,
25,
70,
6030,
1769,
203,
203,
565,
467,
7150,
4941,
3882,
278,
12373,
1071,
432,
8206,
273,
467,
7150,
4941,
3882,
278,
12373,
2
] |
pragma solidity ^0.4.24;
import "./Ownable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract CryptoKats is Ownable {
/// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously
/// includes any time a cat is created through the giveBirth method, but it is also called
/// when a new gen0 cat is created.
event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/**
* CryptoKat data structure
*/
struct Kat {
uint32 color;
uint16 generation;
uint256 motherId;
uint256 fatherId;
}
Kat[] kats;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
constructor() public {
// TODO: fill in constructor body
}
/**
* @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) {
// TODO: ensure the owner isn't address 0x0
}
/**
* @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) {
// TODO: return the owner of the provided token
}
function getKat(uint256 katId) public view returns (uint32 color, uint16 generation, uint256 motherId, uint256 fatherId) {
// TODO: return the color, generation, motherId, and fatherId
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transfer(
address to,
uint256 tokenId
)
public
{
// TODO: transfer the token from the sender to the to address
}
function birth(uint32 color) public {
require(msg.sender == address(this));
kats.push(Kat(color, 0, 0, 0));
emit Birth(msg.sender, kats.length - 1, 0, 0, color);
_mint(msg.sender, kats.length - 1);
}
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(from == _tokenOwner[tokenId]);
require(to != address(0));
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to mint a new token
* 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 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]++;
}
/**
* @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]--;
_tokenOwner[tokenId] = address(0);
}
}
|
* @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]--;
_tokenOwner[tokenId] = address(0);
}
| 1,792,460 |
[
1,
3061,
445,
358,
1206,
279,
1147,
1599,
628,
326,
666,
434,
279,
864,
1758,
225,
628,
1758,
5123,
326,
2416,
3410,
434,
326,
864,
1147,
1599,
225,
1147,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
3723,
628,
326,
2430,
666,
434,
326,
864,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
389,
4479,
1345,
1265,
12,
2867,
628,
16,
2254,
5034,
1147,
548,
13,
2713,
288,
203,
565,
2583,
12,
8443,
951,
12,
2316,
548,
13,
422,
628,
1769,
203,
565,
389,
995,
329,
5157,
1380,
63,
2080,
65,
413,
31,
203,
565,
389,
2316,
5541,
63,
2316,
548,
65,
273,
1758,
12,
20,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
contract MineFactory {
address[] public deployedMineContracts;
function createMineContract() public {
address newMineContract = new Mine();
deployedMineContracts.push(newMineContract);
}
function getDeployedMineContracts()
public
view
returns(address[])
{
return deployedMineContracts;
}
}
contract Mine {
address public miner = address(0);
// address[100] public dataOwners;
mapping(address => bool) public dataOwners;
uint dataOwnersCounter = 0;
mapping(uint => address) public dOwnAddresses; // used for looping through addresses
bool minerAvailable;
bool dataMined = false;
constructor () public {
}
modifier dataOwnerOnly(address owner) {
require(dataOwners[owner] == true, "Only dataOwners are allowed to invoke this function");
_;
}
modifier minerOnly() {
require(msg.sender == miner, "Only Miners are allowed to invoke this function");
_;
}
modifier dataOwnersExists() {
require(!dataOwners[msg.sender], "Already registered as a dataOwner");
_;
}
function addMiner(address minerAddress)
public
dataOwnersExists
returns (address)
{
require(!minerAvailable && msg.sender != address(0), "Miner already exist's in this contract create a new one.");
miner = minerAddress;
minerAvailable = true;
return miner;
}
function allowMine()
public
dataOwnersExists
returns (bool)
{
require(msg.sender != miner, "Miners cannot be dataOwners");
dataOwners[msg.sender] = true;
dOwnAddresses[dataOwnersCounter] = msg.sender;
dataOwnersCounter++;
return true;
}
function startMine()
public
payable
minerOnly
returns (bool)
{
// Require at least .01 ether to mine users data.
require(msg.value > .01 ether, "You require at least 0.01 ether to mine.");
// Require data owners before mining begins
require(dataOwnersCounter >= 2, "You require at least 2 data owners in the contract");
dataMined = true;
return true;
}
function payDataOwners()
public
dataOwnerOnly(msg.sender)
returns (bool)
{
require(dataMined, "Data has already been mined.");
uint totalAmount = address(this).balance;
for (uint i = 0; i < dataOwnersCounter; i ++) {
dOwnAddresses[i].transfer(totalAmount/(dataOwnersCounter));
dataOwners[dOwnAddresses[i]] = false;
dOwnAddresses[i] = address(0);
}
// reset minee pool to make sure they are no longer in the array
dataOwnersCounter = 0;
// Set dataNotMined to false so that currency cannot be sent twice.
dataMined = false;
miner = address(0);
minerAvailable = false;
return true;
}
function getBal() public view returns (uint) {
return address(this).balance;
}
function reset() public returns (bool) {
for (uint i = 0; i < dataOwnersCounter; i++) {
dataOwners[dOwnAddresses[i]] = false;
dOwnAddresses[i] = address(0);
}
// Return all the currency to miner. Not the best way but will fix
miner.transfer(address(this).balance);
dataOwnersCounter = 0;
dataMined = false;
miner = address(0);
minerAvailable = false;
return true;
}
function () public payable {}
}
|
used for looping through addresses
|
mapping(uint => address) public dOwnAddresses;
| 7,233,818 |
[
1,
3668,
364,
25004,
3059,
6138,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2874,
12,
11890,
516,
1758,
13,
1071,
302,
5460,
7148,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: CSU Blockchain final project
pragma solidity >=0.5.0 <0.7.4;
import "./licenseFactory.sol";
// sources
// https://ethereum.stackexchange.com/questions/1415/solidity-create-contract-from-contract/1419
// TODO put in request method, struct.
contract dmvController {
// contract variables
LicenseFactory liscenseContractAddress; // stores the liscense of the contract we create
address owner;
// creates the address, thus saving it in this contract and the next
constructor() public {
liscenseContractAddress = new LicenseFactory();
owner = msg.sender; // save as owner.
}
function getUserLicenseAddress() public view returns(address) {
//require(msg.sender == owner, "Only the DMV can call this contract.");
return address(liscenseContractAddress); // return should be okay? could emit event
}
}
|
contract variables creates the address, thus saving it in this contract and the next
|
contract dmvController {
address owner;
pragma solidity >=0.5.0 <0.7.4;
constructor() public {
liscenseContractAddress = new LicenseFactory();
}
function getUserLicenseAddress() public view returns(address) {
}
}
| 12,722,515 |
[
1,
16351,
3152,
3414,
326,
1758,
16,
12493,
12392,
518,
316,
333,
6835,
471,
326,
1024,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
9113,
90,
2933,
288,
203,
203,
225,
1758,
3410,
31,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
25,
18,
20,
411,
20,
18,
27,
18,
24,
31,
203,
203,
203,
225,
3885,
1435,
1071,
288,
203,
565,
328,
291,
71,
3558,
8924,
1887,
273,
394,
16832,
1733,
5621,
203,
225,
289,
203,
203,
225,
445,
4735,
13211,
1887,
1435,
1071,
1476,
1135,
12,
2867,
13,
288,
203,
225,
289,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.7.3;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
contract TokenOpenZeppelin1 is ERC20 {
constructor() ERC20('Token Name', 'TOKEN_SYMBOL') public {}
}
//with allocation in constructor
contract TokenOpenZeppelin2 is ERC20 {
constructor() ERC20('Token Name', 'TOKEN_SYMBOL') {
_mint(msg.sender, 100000);
}
}
//with allocation in mint() function
contract TokenOpenZeppelin3 is ERC20 {
address public admin;
constructor() ERC20('Token Name', 'TOKEN_SYMBOL') public {
admin = msg.sender;
}
function mint(address to, uint amount) external {
require(msg.sender == admin, 'only admin');
_mint(to, amount);
}
}
//with faucet (good for testing)
contract TokenOpenZeppelin4 is ERC20 {
constructor() ERC20('Token Name', 'TOKEN_SYMBOL') public {}
function faucet(address to, uint amount) external {
_mint(to, amount);
}
}
|
with faucet (good for testing)
|
contract TokenOpenZeppelin4 is ERC20 {
constructor() ERC20('Token Name', 'TOKEN_SYMBOL') public {}
function faucet(address to, uint amount) external {
_mint(to, amount);
}
}
| 6,456,627 |
[
1,
1918,
11087,
5286,
278,
261,
19747,
364,
7769,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
3155,
3678,
62,
881,
84,
292,
267,
24,
353,
4232,
39,
3462,
288,
7010,
203,
225,
3885,
1435,
4232,
39,
3462,
2668,
1345,
1770,
2187,
296,
8412,
67,
22093,
6134,
1071,
2618,
203,
225,
445,
11087,
5286,
278,
12,
2867,
358,
16,
2254,
3844,
13,
3903,
288,
203,
565,
389,
81,
474,
12,
869,
16,
3844,
1769,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../thirdparty/SafeERC20.sol";
import "../../lib/ERC20.sol";
import "../../lib/MathUint.sol";
import "../../lib/AddressUtil.sol";
import "../../iface/PriceOracle.sol";
import "./WhitelistLib.sol";
import "./QuotaLib.sol";
import "./ApprovalLib.sol";
/// @title ERC20Lib
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ERC20Lib
{
using AddressUtil for address;
using MathUint for uint;
using WhitelistLib for Wallet;
using QuotaLib for Wallet;
using ApprovalLib for Wallet;
using SafeERC20 for ERC20;
event Transfered (address token, address to, uint amount, bytes logdata);
event Approved (address token, address spender, uint amount);
event ContractCalled (address to, uint value, bytes data);
bytes32 public constant TRANSFER_TOKEN_TYPEHASH = keccak256(
"transferToken(address wallet,uint256 validUntil,address token,address to,uint256 amount,bytes logdata)"
);
bytes32 public constant APPROVE_TOKEN_TYPEHASH = keccak256(
"approveToken(address wallet,uint256 validUntil,address token,address to,uint256 amount)"
);
bytes32 public constant CALL_CONTRACT_TYPEHASH = keccak256(
"callContract(address wallet,uint256 validUntil,address to,uint256 value,bytes data)"
);
bytes32 public constant APPROVE_THEN_CALL_CONTRACT_TYPEHASH = keccak256(
"approveThenCallContract(address wallet,uint256 validUntil,address token,address to,uint256 amount,uint256 value,bytes data)"
);
function transferToken(
Wallet storage wallet,
PriceOracle priceOracle,
address token,
address to,
uint amount,
bytes calldata logdata,
bool forceUseQuota
)
external
{
if (forceUseQuota || !wallet.isAddressWhitelisted(to)) {
wallet.checkAndAddToSpent(priceOracle, token, amount);
}
_transferWithEvent(token, to, amount, logdata);
}
function transferTokenWA(
Wallet storage wallet,
bytes32 domainSeparator,
Approval calldata approval,
address token,
address to,
uint amount,
bytes calldata logdata
)
external
returns (bytes32 approvedHash)
{
approvedHash = wallet.verifyApproval(
domainSeparator,
SigRequirement.MAJORITY_OWNER_REQUIRED,
approval,
abi.encode(
TRANSFER_TOKEN_TYPEHASH,
approval.wallet,
approval.validUntil,
token,
to,
amount,
keccak256(logdata)
)
);
_transferWithEvent(token, to, amount, logdata);
}
function callContract(
Wallet storage wallet,
PriceOracle priceOracle,
address to,
uint value,
bytes calldata data,
bool forceUseQuota
)
external
returns (bytes memory returnData)
{
if (forceUseQuota || !wallet.isAddressWhitelisted(to)) {
wallet.checkAndAddToSpent(priceOracle, address(0), value);
}
return _callContractInternal(to, value, data, priceOracle);
}
function callContractWA(
Wallet storage wallet,
bytes32 domainSeparator,
Approval calldata approval,
address to,
uint value,
bytes calldata data
)
external
returns (bytes32 approvedHash, bytes memory returnData)
{
approvedHash = wallet.verifyApproval(
domainSeparator,
SigRequirement.MAJORITY_OWNER_REQUIRED,
approval,
abi.encode(
CALL_CONTRACT_TYPEHASH,
approval.wallet,
approval.validUntil,
to,
value,
keccak256(data)
)
);
returnData = _callContractInternal(to, value, data, PriceOracle(0));
}
function approveToken(
Wallet storage wallet,
PriceOracle priceOracle,
address token,
address to,
uint amount,
bool forceUseQuota
)
external
{
uint additionalAllowance = _approveInternal(token, to, amount);
if (forceUseQuota || !wallet.isAddressWhitelisted(to)) {
wallet.checkAndAddToSpent(priceOracle, token, additionalAllowance);
}
}
function approveTokenWA(
Wallet storage wallet,
bytes32 domainSeparator,
Approval calldata approval,
address token,
address to,
uint amount
)
external
returns (bytes32 approvedHash)
{
approvedHash = wallet.verifyApproval(
domainSeparator,
SigRequirement.MAJORITY_OWNER_REQUIRED,
approval,
abi.encode(
APPROVE_TOKEN_TYPEHASH,
approval.wallet,
approval.validUntil,
token,
to,
amount
)
);
_approveInternal(token, to, amount);
}
function approveThenCallContract(
Wallet storage wallet,
PriceOracle priceOracle,
address token,
address to,
uint amount,
uint value,
bytes calldata data,
bool forceUseQuota
)
external
returns (bytes memory returnData)
{
uint additionalAllowance = _approveInternal(token, to, amount);
if (forceUseQuota || !wallet.isAddressWhitelisted(to)) {
wallet.checkAndAddToSpent(priceOracle, token, additionalAllowance);
wallet.checkAndAddToSpent(priceOracle, address(0), value);
}
return _callContractInternal(to, value, data, priceOracle);
}
function approveThenCallContractWA(
Wallet storage wallet,
bytes32 domainSeparator,
Approval calldata approval,
address token,
address to,
uint amount,
uint value,
bytes calldata data
)
external
returns (bytes32 approvedHash, bytes memory returnData)
{
approvedHash = wallet.verifyApproval(
domainSeparator,
SigRequirement.MAJORITY_OWNER_REQUIRED,
approval,
abi.encode(
APPROVE_THEN_CALL_CONTRACT_TYPEHASH,
approval.wallet,
approval.validUntil,
token,
to,
amount,
value,
keccak256(data)
)
);
_approveInternal(token, to, amount);
returnData = _callContractInternal(to, value, data, PriceOracle(0));
}
function transfer(
address token,
address to,
uint amount
)
public
{
if (token == address(0)) {
to.sendETHAndVerify(amount, gasleft());
} else {
ERC20(token).safeTransfer(to, amount);
}
}
// --- Internal functions ---
function _transferWithEvent(
address token,
address to,
uint amount,
bytes calldata logdata
)
private
{
transfer(token, to, amount);
emit Transfered(token, to, amount, logdata);
}
function _approveInternal(
address token,
address spender,
uint amount
)
private
returns (uint additionalAllowance)
{
// Current allowance
uint allowance = ERC20(token).allowance(address(this), spender);
if (amount != allowance) {
// First reset the approved amount if needed
if (allowance > 0) {
ERC20(token).safeApprove(spender, 0);
}
// Now approve the requested amount
ERC20(token).safeApprove(spender, amount);
}
// If we increased the allowance, calculate by how much
if (amount > allowance) {
additionalAllowance = amount.sub(allowance);
}
emit Approved(token, spender, amount);
}
function _callContractInternal(
address to,
uint value,
bytes calldata txData,
PriceOracle priceOracle
)
private
returns (bytes memory returnData)
{
require(to != address(this), "SELF_CALL_DISALLOWED");
if (priceOracle != PriceOracle(0)) {
// Disallow general calls to token contracts (for tokens that have price data
// so the quota is actually used).
require(priceOracle.tokenValue(to, 1e18) == 0, "CALL_DISALLOWED");
}
bool success;
(success, returnData) = to.call{value: value}(txData);
require(success, "CALL_FAILED");
emit ContractCalled(to, value, txData);
}
}
// SPDX-License-Identifier: MIT
// Taken from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/utils/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
import "./Address.sol";
import "../lib/ERC20.sol";
import "../lib/MathUint.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 MathUint for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 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(ERC20 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(ERC20 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(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(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(ERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @title ERC20 Token Interface
/// @dev see https://github.com/ethereum/EIPs/issues/20
/// @author Daniel Wang - <[email protected]>
abstract contract ERC20
{
function totalSupply()
public
view
virtual
returns (uint);
function balanceOf(
address who
)
public
view
virtual
returns (uint);
function allowance(
address owner,
address spender
)
public
view
virtual
returns (uint);
function transfer(
address to,
uint value
)
public
virtual
returns (bool);
function transferFrom(
address from,
address to,
uint value
)
public
virtual
returns (bool);
function approve(
address spender,
uint value
)
public
virtual
returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint
{
function mul(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a * b;
require(a == 0 || c / a == b, "MUL_OVERFLOW");
}
function sub(
uint a,
uint b
)
internal
pure
returns (uint)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
function add(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @title Utility Functions for addresses
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library AddressUtil
{
using AddressUtil for *;
function isContract(
address addr
)
internal
view
returns (bool)
{
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(addr) }
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function toPayable(
address addr
)
internal
pure
returns (address payable)
{
return payable(addr);
}
// Works like address.send but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETH(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
if (amount == 0) {
return true;
}
address payable recipient = to.toPayable();
/* solium-disable-next-line */
(success,) = recipient.call{value: amount, gas: gasLimit}("");
}
// Works like address.transfer but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETHAndVerify(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
success = to.sendETH(amount, gasLimit);
require(success, "TRANSFER_FAILURE");
}
// Works like call but is slightly more efficient when data
// needs to be copied from memory to do the call.
function fastCall(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bool success, bytes memory returnData)
{
if (to != address(0)) {
assembly {
// Do the call
success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
// Copy the return data
let size := returndatasize()
returnData := mload(0x40)
mstore(returnData, size)
returndatacopy(add(returnData, 32), 0, size)
// Update free memory pointer
mstore(0x40, add(returnData, add(32, size)))
}
}
}
// Like fastCall, but throws when the call is unsuccessful.
function fastCallAndVerify(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bytes memory returnData)
{
bool success;
(success, returnData) = fastCall(to, gasLimit, value, data);
if (!success) {
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @title PriceOracle
interface PriceOracle
{
// @dev Return's the token's value in ETH
function tokenValue(address token, uint amount)
external
view
returns (uint value);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./ApprovalLib.sol";
import "./WalletData.sol";
import "../../lib/MathUint.sol";
/// @title WhitelistLib
/// @dev This store maintains a wallet's whitelisted addresses.
library WhitelistLib
{
using MathUint for uint;
using WhitelistLib for Wallet;
using ApprovalLib for Wallet;
uint public constant WHITELIST_PENDING_PERIOD = 1 days;
bytes32 public constant ADD_TO_WHITELIST_TYPEHASH = keccak256(
"addToWhitelist(address wallet,uint256 validUntil,address addr)"
);
event Whitelisted(
address addr,
bool whitelisted,
uint effectiveTime
);
function addToWhitelist(
Wallet storage wallet,
address addr
)
external
{
wallet._addToWhitelist(
addr,
block.timestamp.add(WHITELIST_PENDING_PERIOD)
);
}
function addToWhitelistWA(
Wallet storage wallet,
bytes32 domainSeparator,
Approval calldata approval,
address addr
)
external
returns (bytes32 approvedHash)
{
approvedHash = wallet.verifyApproval(
domainSeparator,
SigRequirement.MAJORITY_OWNER_REQUIRED,
approval,
abi.encode(
ADD_TO_WHITELIST_TYPEHASH,
approval.wallet,
approval.validUntil,
addr
)
);
wallet._addToWhitelist(
addr,
block.timestamp
);
}
function removeFromWhitelist(
Wallet storage wallet,
address addr
)
external
{
wallet._removeFromWhitelist(addr);
}
function isAddressWhitelisted(
Wallet storage wallet,
address addr
)
internal
view
returns (bool)
{
uint effectiveTime = wallet.whitelisted[addr];
return effectiveTime > 0 && effectiveTime <= block.timestamp;
}
// --- Internal functions ---
function _addToWhitelist(
Wallet storage wallet,
address addr,
uint effectiveTime
)
internal
{
require(wallet.whitelisted[addr] == 0, "ADDRESS_ALREADY_WHITELISTED");
uint effective = effectiveTime >= block.timestamp ? effectiveTime : block.timestamp;
wallet.whitelisted[addr] = effective;
emit Whitelisted(addr, true, effective);
}
function _removeFromWhitelist(
Wallet storage wallet,
address addr
)
internal
{
delete wallet.whitelisted[addr];
emit Whitelisted(addr, false, 0);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./ApprovalLib.sol";
import "./WalletData.sol";
import "../../iface/PriceOracle.sol";
import "../../lib/MathUint.sol";
import "../../thirdparty/SafeCast.sol";
/// @title QuotaLib
/// @dev This store maintains daily spending quota for each wallet.
/// A rolling daily limit is used.
library QuotaLib
{
using MathUint for uint;
using SafeCast for uint;
using ApprovalLib for Wallet;
uint128 public constant MAX_QUOTA = uint128(-1);
uint public constant QUOTA_PENDING_PERIOD = 1 days;
bytes32 public constant CHANGE_DAILY_QUOTE_TYPEHASH = keccak256(
"changeDailyQuota(address wallet,uint256 validUntil,uint256 newQuota)"
);
event QuotaScheduled(
address wallet,
uint pendingQuota,
uint64 pendingUntil
);
function changeDailyQuota(
Wallet storage wallet,
uint newQuota
)
public
{
setQuota(wallet, newQuota, block.timestamp.add(QUOTA_PENDING_PERIOD));
}
function changeDailyQuotaWA(
Wallet storage wallet,
bytes32 domainSeparator,
Approval calldata approval,
uint newQuota
)
public
returns (bytes32 approvedHash)
{
approvedHash = wallet.verifyApproval(
domainSeparator,
SigRequirement.MAJORITY_OWNER_REQUIRED,
approval,
abi.encode(
CHANGE_DAILY_QUOTE_TYPEHASH,
approval.wallet,
approval.validUntil,
newQuota
)
);
setQuota(wallet, newQuota, 0);
}
function checkAndAddToSpent(
Wallet storage wallet,
PriceOracle priceOracle,
address token,
uint amount
)
internal
{
Quota memory q = wallet.quota;
uint available = _availableQuota(q);
if (available != MAX_QUOTA) {
uint value = (token == address(0)) ?
amount :
((address(priceOracle) == address(0)) ?
0 :
priceOracle.tokenValue(token, amount));
if (value > 0) {
require(available >= value, "QUOTA_EXCEEDED");
_addToSpent(wallet, q, value);
}
}
}
// 0 for newQuota indicates unlimited quota, or daily quota is disabled.
function setQuota(
Wallet storage wallet,
uint newQuota,
uint effectiveTime
)
internal
{
require(newQuota <= MAX_QUOTA, "INVALID_VALUE");
if (newQuota == MAX_QUOTA) {
newQuota = 0;
}
uint __currentQuota = currentQuota(wallet);
// Always allow the quota to be changed immediately when the quota doesn't increase
if ((__currentQuota >= newQuota && newQuota != 0) || __currentQuota == 0) {
effectiveTime = 0;
}
Quota storage quota = wallet.quota;
quota.currentQuota = __currentQuota.toUint128();
quota.pendingQuota = newQuota.toUint128();
quota.pendingUntil = effectiveTime.toUint64();
emit QuotaScheduled(
address(this),
newQuota,
quota.pendingUntil
);
}
// Returns 0 to indiciate unlimited quota
function currentQuota(Wallet storage wallet)
internal
view
returns (uint)
{
return _currentQuota(wallet.quota);
}
// Returns 0 to indiciate unlimited quota
function pendingQuota(Wallet storage wallet)
internal
view
returns (
uint __pendingQuota,
uint __pendingUntil
)
{
return _pendingQuota(wallet.quota);
}
function spentQuota(Wallet storage wallet)
internal
view
returns (uint)
{
return _spentQuota(wallet.quota);
}
function availableQuota(Wallet storage wallet)
internal
view
returns (uint)
{
return _availableQuota(wallet.quota);
}
function hasEnoughQuota(
Wallet storage wallet,
uint requiredAmount
)
internal
view
returns (bool)
{
return _hasEnoughQuota(wallet.quota, requiredAmount);
}
// --- Internal functions ---
function _currentQuota(Quota memory q)
private
view
returns (uint)
{
return q.pendingUntil <= block.timestamp ? q.pendingQuota : q.currentQuota;
}
function _pendingQuota(Quota memory q)
private
view
returns (
uint __pendingQuota,
uint __pendingUntil
)
{
if (q.pendingUntil > 0 && q.pendingUntil > block.timestamp) {
__pendingQuota = q.pendingQuota;
__pendingUntil = q.pendingUntil;
}
}
function _spentQuota(Quota memory q)
private
view
returns (uint)
{
uint timeSinceLastSpent = block.timestamp.sub(q.spentTimestamp);
if (timeSinceLastSpent < 1 days) {
return uint(q.spentAmount).sub(timeSinceLastSpent.mul(q.spentAmount) / 1 days);
} else {
return 0;
}
}
function _availableQuota(Quota memory q)
private
view
returns (uint)
{
uint quota = _currentQuota(q);
if (quota == 0) {
return MAX_QUOTA;
}
uint spent = _spentQuota(q);
return quota > spent ? quota - spent : 0;
}
function _hasEnoughQuota(
Quota memory q,
uint requiredAmount
)
private
view
returns (bool)
{
return _availableQuota(q) >= requiredAmount;
}
function _addToSpent(
Wallet storage wallet,
Quota memory q,
uint amount
)
private
{
Quota storage s = wallet.quota;
s.spentAmount = _spentQuota(q).add(amount).toUint128();
s.spentTimestamp = uint64(block.timestamp);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/EIP712.sol";
import "../../lib/SignatureUtil.sol";
import "./GuardianLib.sol";
import "./WalletData.sol";
/// @title ApprovalLib
/// @dev Utility library for better handling of signed wallet requests.
/// This library must be deployed and linked to other modules.
///
/// @author Daniel Wang - <[email protected]>
library ApprovalLib {
using SignatureUtil for bytes32;
function verifyApproval(
Wallet storage wallet,
bytes32 domainSeparator,
SigRequirement sigRequirement,
Approval memory approval,
bytes memory encodedRequest
)
internal
returns (bytes32 approvedHash)
{
require(address(this) == approval.wallet, "INVALID_WALLET");
require(block.timestamp <= approval.validUntil, "EXPIRED_SIGNED_REQUEST");
approvedHash = EIP712.hashPacked(domainSeparator, keccak256(encodedRequest));
// Save hash to prevent replay attacks
require(!wallet.hashes[approvedHash], "HASH_EXIST");
wallet.hashes[approvedHash] = true;
require(
approvedHash.verifySignatures(approval.signers, approval.signatures),
"INVALID_SIGNATURES"
);
require(
GuardianLib.requireMajority(
wallet,
approval.signers,
sigRequirement
),
"PERMISSION_DENIED"
);
}
}
// SPDX-License-Identifier: MIT
// Token from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/90ed1af972299070f51bf4665a85da56ac4d355e/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
//require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
enum SigRequirement
{
MAJORITY_OWNER_NOT_ALLOWED,
MAJORITY_OWNER_ALLOWED,
MAJORITY_OWNER_REQUIRED,
OWNER_OR_ANY_GUARDIAN,
ANY_GUARDIAN
}
struct Approval
{
address[] signers;
bytes[] signatures;
uint validUntil;
address wallet;
}
// Optimized to fit into 64 bytes (2 slots)
struct Quota
{
uint128 currentQuota;
uint128 pendingQuota;
uint128 spentAmount;
uint64 spentTimestamp;
uint64 pendingUntil;
}
enum GuardianStatus
{
REMOVE, // Being removed or removed after validUntil timestamp
ADD // Being added or added after validSince timestamp.
}
// Optimized to fit into 32 bytes (1 slot)
struct Guardian
{
address addr;
uint8 status;
uint64 timestamp; // validSince if status = ADD; validUntil if adding = REMOVE;
}
struct Wallet
{
address owner;
uint64 creationTimestamp;
// relayer => nonce
uint nonce;
// hash => consumed
mapping (bytes32 => bool) hashes;
bool locked;
Guardian[] guardians;
mapping (address => uint) guardianIdx;
address inheritor;
uint32 inheritWaitingPeriod;
uint64 lastActive; // the latest timestamp the owner is considered to be active
Quota quota;
// whitelisted address => effective timestamp
mapping (address => uint) whitelisted;
}
// SPDX-License-Identifier: Apache-2.0
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
library EIP712
{
struct Domain {
string name;
string version;
address verifyingContract;
}
bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
string constant internal EIP191_HEADER = "\x19\x01";
function hash(Domain memory domain)
internal
pure
returns (bytes32)
{
uint _chainid;
assembly { _chainid := chainid() }
return keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(domain.name)),
keccak256(bytes(domain.version)),
_chainid,
domain.verifyingContract
)
);
}
function hashPacked(
bytes32 domainSeparator,
bytes32 dataHash
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
EIP191_HEADER,
domainSeparator,
dataHash
)
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../thirdparty/BytesUtil.sol";
import "./AddressUtil.sol";
import "./ERC1271.sol";
import "./MathUint.sol";
/// @title SignatureUtil
/// @author Daniel Wang - <[email protected]>
/// @dev This method supports multihash standard. Each signature's last byte indicates
/// the signature's type.
library SignatureUtil
{
using BytesUtil for bytes;
using MathUint for uint;
using AddressUtil for address;
enum SignatureType {
ILLEGAL,
INVALID,
EIP_712,
ETH_SIGN,
WALLET // deprecated
}
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function verifySignatures(
bytes32 signHash,
address[] memory signers,
bytes[] memory signatures
)
internal
view
returns (bool)
{
require(signers.length == signatures.length, "BAD_SIGNATURE_DATA");
address lastSigner;
for (uint i = 0; i < signers.length; i++) {
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (!verifySignature(signHash, signers[i], signatures[i])) {
return false;
}
}
return true;
}
function verifySignature(
bytes32 signHash,
address signer,
bytes memory signature
)
internal
view
returns (bool)
{
if (signer == address(0)) {
return false;
}
return signer.isContract()?
verifyERC1271Signature(signHash, signer, signature):
verifyEOASignature(signHash, signer, signature);
}
function recoverECDSASigner(
bytes32 signHash,
bytes memory signature
)
internal
pure
returns (address)
{
if (signature.length != 65) {
return address(0);
}
bytes32 r;
bytes32 s;
uint8 v;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := and(mload(add(signature, 0x41)), 0xff)
}
// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v == 27 || v == 28) {
return ecrecover(signHash, v, r, s);
} else {
return address(0);
}
}
function verifyEOASignature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
pure
returns (bool success)
{
if (signer == address(0)) {
return false;
}
uint signatureTypeOffset = signature.length.sub(1);
SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset));
// Strip off the last byte of the signature by updating the length
assembly {
mstore(signature, signatureTypeOffset)
}
if (signatureType == SignatureType.EIP_712) {
success = (signer == recoverECDSASigner(signHash, signature));
} else if (signatureType == SignatureType.ETH_SIGN) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash)
);
success = (signer == recoverECDSASigner(hash, signature));
} else {
success = false;
}
// Restore the signature length
assembly {
mstore(signature, add(signatureTypeOffset, 1))
}
return success;
}
function verifyERC1271Signature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
view
returns (bool)
{
bytes memory callData = abi.encodeWithSelector(
ERC1271.isValidSignature.selector,
signHash,
signature
);
(bool success, bytes memory result) = signer.staticcall(callData);
return (
success &&
result.length == 32 &&
result.toBytes4(0) == ERC1271_MAGICVALUE
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./WalletData.sol";
import "./ApprovalLib.sol";
import "../../lib/SignatureUtil.sol";
import "../../thirdparty/SafeCast.sol";
/// @title GuardianModule
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library GuardianLib
{
using AddressUtil for address;
using SafeCast for uint;
using SignatureUtil for bytes32;
using ApprovalLib for Wallet;
uint public constant MAX_GUARDIANS = 10;
uint public constant GUARDIAN_PENDING_PERIOD = 3 days;
bytes32 public constant ADD_GUARDIAN_TYPEHASH = keccak256(
"addGuardian(address wallet,uint256 validUntil,address guardian)"
);
bytes32 public constant REMOVE_GUARDIAN_TYPEHASH = keccak256(
"removeGuardian(address wallet,uint256 validUntil,address guardian)"
);
bytes32 public constant RESET_GUARDIANS_TYPEHASH = keccak256(
"resetGuardians(address wallet,uint256 validUntil,address[] guardians)"
);
event GuardianAdded (address guardian, uint effectiveTime);
event GuardianRemoved (address guardian, uint effectiveTime);
function addGuardiansImmediately(
Wallet storage wallet,
address[] memory _guardians
)
external
{
address guardian = address(0);
for (uint i = 0; i < _guardians.length; i++) {
require(_guardians[i] > guardian, "INVALID_ORDERING");
guardian = _guardians[i];
_addGuardian(wallet, guardian, 0, true);
}
}
function addGuardian(
Wallet storage wallet,
address guardian
)
external
{
_addGuardian(wallet, guardian, GUARDIAN_PENDING_PERIOD, false);
}
function addGuardianWA(
Wallet storage wallet,
bytes32 domainSeparator,
Approval calldata approval,
address guardian
)
external
returns (bytes32 approvedHash)
{
approvedHash = wallet.verifyApproval(
domainSeparator,
SigRequirement.MAJORITY_OWNER_REQUIRED,
approval,
abi.encode(
ADD_GUARDIAN_TYPEHASH,
approval.wallet,
approval.validUntil,
guardian
)
);
_addGuardian(wallet, guardian, 0, true);
}
function removeGuardian(
Wallet storage wallet,
address guardian
)
external
{
_removeGuardian(wallet, guardian, GUARDIAN_PENDING_PERIOD, false);
}
function removeGuardianWA(
Wallet storage wallet,
bytes32 domainSeparator,
Approval calldata approval,
address guardian
)
external
returns (bytes32 approvedHash)
{
approvedHash = wallet.verifyApproval(
domainSeparator,
SigRequirement.MAJORITY_OWNER_REQUIRED,
approval,
abi.encode(
REMOVE_GUARDIAN_TYPEHASH,
approval.wallet,
approval.validUntil,
guardian
)
);
_removeGuardian(wallet, guardian, 0, true);
}
function resetGuardians(
Wallet storage wallet,
address[] calldata newGuardians
)
external
{
Guardian[] memory allGuardians = guardians(wallet, true);
for (uint i = 0; i < allGuardians.length; i++) {
_removeGuardian(wallet, allGuardians[i].addr, GUARDIAN_PENDING_PERIOD, false);
}
for (uint j = 0; j < newGuardians.length; j++) {
_addGuardian(wallet, newGuardians[j], GUARDIAN_PENDING_PERIOD, false);
}
}
function resetGuardiansWA(
Wallet storage wallet,
bytes32 domainSeparator,
Approval calldata approval,
address[] calldata newGuardians
)
external
returns (bytes32 approvedHash)
{
approvedHash = wallet.verifyApproval(
domainSeparator,
SigRequirement.MAJORITY_OWNER_REQUIRED,
approval,
abi.encode(
RESET_GUARDIANS_TYPEHASH,
approval.wallet,
approval.validUntil,
keccak256(abi.encodePacked(newGuardians))
)
);
removeAllGuardians(wallet);
for (uint i = 0; i < newGuardians.length; i++) {
_addGuardian(wallet, newGuardians[i], 0, true);
}
}
function requireMajority(
Wallet storage wallet,
address[] memory signers,
SigRequirement requirement
)
internal
view
returns (bool)
{
// We always need at least one signer
if (signers.length == 0) {
return false;
}
// Calculate total group sizes
Guardian[] memory allGuardians = guardians(wallet, false);
require(allGuardians.length > 0, "NO_GUARDIANS");
address lastSigner;
bool walletOwnerSigned = false;
address owner = wallet.owner;
for (uint i = 0; i < signers.length; i++) {
// Check for duplicates
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (signers[i] == owner) {
walletOwnerSigned = true;
} else {
bool _isGuardian = false;
for (uint j = 0; j < allGuardians.length; j++) {
if (allGuardians[j].addr == signers[i]) {
_isGuardian = true;
break;
}
}
require(_isGuardian, "SIGNER_NOT_GUARDIAN");
}
}
if (requirement == SigRequirement.OWNER_OR_ANY_GUARDIAN) {
return signers.length == 1;
} else if (requirement == SigRequirement.ANY_GUARDIAN) {
require(!walletOwnerSigned, "WALLET_OWNER_SIGNATURE_NOT_ALLOWED");
return signers.length == 1;
}
// Check owner requirements
if (requirement == SigRequirement.MAJORITY_OWNER_REQUIRED) {
require(walletOwnerSigned, "WALLET_OWNER_SIGNATURE_REQUIRED");
} else if (requirement == SigRequirement.MAJORITY_OWNER_NOT_ALLOWED) {
require(!walletOwnerSigned, "WALLET_OWNER_SIGNATURE_NOT_ALLOWED");
}
uint numExtendedSigners = allGuardians.length;
if (walletOwnerSigned) {
numExtendedSigners += 1;
require(signers.length > 1, "NO_GUARDIAN_SIGNED_BESIDES_OWNER");
}
return signers.length >= (numExtendedSigners >> 1) + 1;
}
function isGuardian(
Wallet storage wallet,
address addr,
bool includePendingAddition
)
public
view
returns (bool)
{
Guardian memory g = _getGuardian(wallet, addr);
return _isActiveOrPendingAddition(g, includePendingAddition);
}
function guardians(
Wallet storage wallet,
bool includePendingAddition
)
public
view
returns (Guardian[] memory _guardians)
{
_guardians = new Guardian[](wallet.guardians.length);
uint index = 0;
for (uint i = 0; i < wallet.guardians.length; i++) {
Guardian memory g = wallet.guardians[i];
if (_isActiveOrPendingAddition(g, includePendingAddition)) {
_guardians[index] = g;
index++;
}
}
assembly { mstore(_guardians, index) }
}
function numGuardians(
Wallet storage wallet,
bool includePendingAddition
)
public
view
returns (uint count)
{
for (uint i = 0; i < wallet.guardians.length; i++) {
Guardian memory g = wallet.guardians[i];
if (_isActiveOrPendingAddition(g, includePendingAddition)) {
count++;
}
}
}
function removeAllGuardians(
Wallet storage wallet
)
internal
{
uint size = wallet.guardians.length;
if (size == 0) return;
for (uint i = 0; i < wallet.guardians.length; i++) {
delete wallet.guardianIdx[wallet.guardians[i].addr];
}
delete wallet.guardians;
}
function cancelPendingGuardians(Wallet storage wallet)
internal
{
bool cancelled = false;
for (uint i = 0; i < wallet.guardians.length; i++) {
Guardian memory g = wallet.guardians[i];
if (_isPendingAddition(g)) {
wallet.guardians[i].status = uint8(GuardianStatus.REMOVE);
wallet.guardians[i].timestamp = 0;
cancelled = true;
}
if (_isPendingRemoval(g)) {
wallet.guardians[i].status = uint8(GuardianStatus.ADD);
wallet.guardians[i].timestamp = 0;
cancelled = true;
}
}
_cleanRemovedGuardians(wallet, true);
}
function storeGuardian(
Wallet storage wallet,
address addr,
uint validSince,
bool alwaysOverride
)
internal
returns (uint)
{
require(validSince >= block.timestamp, "INVALID_VALID_SINCE");
require(addr != address(0), "ZERO_ADDRESS");
require(addr != address(this), "INVALID_ADDRESS");
uint pos = wallet.guardianIdx[addr];
if (pos == 0) {
// Add the new guardian
Guardian memory _g = Guardian(
addr,
uint8(GuardianStatus.ADD),
validSince.toUint64()
);
wallet.guardians.push(_g);
wallet.guardianIdx[addr] = wallet.guardians.length;
_cleanRemovedGuardians(wallet, false);
return validSince;
}
Guardian memory g = wallet.guardians[pos - 1];
if (_isRemoved(g)) {
wallet.guardians[pos - 1].status = uint8(GuardianStatus.ADD);
wallet.guardians[pos - 1].timestamp = validSince.toUint64();
return validSince;
}
if (_isPendingRemoval(g)) {
wallet.guardians[pos - 1].status = uint8(GuardianStatus.ADD);
wallet.guardians[pos - 1].timestamp = 0;
return 0;
}
if (_isPendingAddition(g)) {
if (!alwaysOverride) return g.timestamp;
wallet.guardians[pos - 1].timestamp = validSince.toUint64();
return validSince;
}
require(_isAdded(g), "UNEXPECTED_RESULT");
return 0;
}
function deleteGuardian(
Wallet storage wallet,
address addr,
uint validUntil,
bool alwaysOverride
)
internal
returns (uint)
{
require(validUntil >= block.timestamp, "INVALID_VALID_UNTIL");
require(addr != address(0), "ZERO_ADDRESS");
uint pos = wallet.guardianIdx[addr];
require(pos > 0, "GUARDIAN_NOT_EXISTS");
Guardian memory g = wallet.guardians[pos - 1];
if (_isAdded(g)) {
wallet.guardians[pos - 1].status = uint8(GuardianStatus.REMOVE);
wallet.guardians[pos - 1].timestamp = validUntil.toUint64();
return validUntil;
}
if (_isPendingAddition(g)) {
wallet.guardians[pos - 1].status = uint8(GuardianStatus.REMOVE);
wallet.guardians[pos - 1].timestamp = 0;
return 0;
}
if (_isPendingRemoval(g)) {
if (!alwaysOverride) return g.timestamp;
wallet.guardians[pos - 1].timestamp = validUntil.toUint64();
return validUntil;
}
require(_isRemoved(g), "UNEXPECTED_RESULT");
return 0;
}
// --- Internal functions ---
function _addGuardian(
Wallet storage wallet,
address guardian,
uint pendingPeriod,
bool alwaysOverride
)
internal
{
uint _numGuardians = numGuardians(wallet, true);
require(_numGuardians < MAX_GUARDIANS, "TOO_MANY_GUARDIANS");
require(guardian != wallet.owner, "GUARDIAN_CAN_NOT_BE_OWNER");
uint validSince = block.timestamp;
if (_numGuardians >= 2) {
validSince = block.timestamp + pendingPeriod;
}
validSince = storeGuardian(wallet, guardian, validSince, alwaysOverride);
emit GuardianAdded(guardian, validSince);
}
function _removeGuardian(
Wallet storage wallet,
address guardian,
uint pendingPeriod,
bool alwaysOverride
)
private
{
uint validUntil = block.timestamp + pendingPeriod;
validUntil = deleteGuardian(wallet, guardian, validUntil, alwaysOverride);
emit GuardianRemoved(guardian, validUntil);
}
function _getGuardian(
Wallet storage wallet,
address addr
)
private
view
returns (Guardian memory guardian)
{
uint pos = wallet.guardianIdx[addr];
if (pos > 0) {
guardian = wallet.guardians[pos - 1];
}
}
function _isAdded(Guardian memory guardian)
private
view
returns (bool)
{
return guardian.status == uint8(GuardianStatus.ADD) &&
guardian.timestamp <= block.timestamp;
}
function _isPendingAddition(Guardian memory guardian)
private
view
returns (bool)
{
return guardian.status == uint8(GuardianStatus.ADD) &&
guardian.timestamp > block.timestamp;
}
function _isRemoved(Guardian memory guardian)
private
view
returns (bool)
{
return guardian.status == uint8(GuardianStatus.REMOVE) &&
guardian.timestamp <= block.timestamp;
}
function _isPendingRemoval(Guardian memory guardian)
private
view
returns (bool)
{
return guardian.status == uint8(GuardianStatus.REMOVE) &&
guardian.timestamp > block.timestamp;
}
function _isActive(Guardian memory guardian)
private
view
returns (bool)
{
return _isAdded(guardian) || _isPendingRemoval(guardian);
}
function _isActiveOrPendingAddition(
Guardian memory guardian,
bool includePendingAddition
)
private
view
returns (bool)
{
return _isActive(guardian) || includePendingAddition && _isPendingAddition(guardian);
}
function _cleanRemovedGuardians(
Wallet storage wallet,
bool force
)
private
{
uint count = wallet.guardians.length;
if (!force && count < 10) return;
for (int i = int(count) - 1; i >= 0; i--) {
Guardian memory g = wallet.guardians[uint(i)];
if (_isRemoved(g)) {
Guardian memory lastGuardian = wallet.guardians[wallet.guardians.length - 1];
if (g.addr != lastGuardian.addr) {
wallet.guardians[uint(i)] = lastGuardian;
wallet.guardianIdx[lastGuardian.addr] = uint(i) + 1;
}
wallet.guardians.pop();
delete wallet.guardianIdx[g.addr];
}
}
}
}
// SPDX-License-Identifier: UNLICENSED
// Taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
pragma solidity ^0.7.0;
library BytesUtil {
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) {
require(_bytes.length >= (_start + 3));
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
require(_bytes.length >= (_start + 4));
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function fastSHA256(
bytes memory data
)
internal
view
returns (bytes32)
{
bytes32[] memory result = new bytes32[](1);
bool success;
assembly {
let ptr := add(data, 32)
success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32)
}
require(success, "SHA256_FAILED");
return result[0];
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
abstract contract ERC1271 {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
|
Current allowance First reset the approved amount if needed If we increased the allowance, calculate by how much
|
function _approveInternal(
address token,
address spender,
uint amount
)
private
returns (uint additionalAllowance)
{
uint allowance = ERC20(token).allowance(address(this), spender);
if (amount != allowance) {
if (allowance > 0) {
ERC20(token).safeApprove(spender, 0);
}
}
if (amount > allowance) {
additionalAllowance = amount.sub(allowance);
}
emit Approved(token, spender, amount);
}
| 11,845,002 |
[
1,
3935,
1699,
1359,
5783,
2715,
326,
20412,
3844,
309,
3577,
971,
732,
31383,
326,
1699,
1359,
16,
4604,
635,
3661,
9816,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
12908,
537,
3061,
12,
203,
3639,
1758,
1147,
16,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
565,
3844,
203,
3639,
262,
203,
3639,
3238,
203,
3639,
1135,
261,
11890,
3312,
7009,
1359,
13,
203,
565,
288,
203,
3639,
2254,
1699,
1359,
273,
4232,
39,
3462,
12,
2316,
2934,
5965,
1359,
12,
2867,
12,
2211,
3631,
17571,
264,
1769,
203,
203,
3639,
309,
261,
8949,
480,
1699,
1359,
13,
288,
203,
5411,
309,
261,
5965,
1359,
405,
374,
13,
288,
203,
7734,
4232,
39,
3462,
12,
2316,
2934,
4626,
12053,
537,
12,
87,
1302,
264,
16,
374,
1769,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
309,
261,
8949,
405,
1699,
1359,
13,
288,
203,
5411,
3312,
7009,
1359,
273,
3844,
18,
1717,
12,
5965,
1359,
1769,
203,
3639,
289,
203,
3639,
3626,
1716,
685,
2155,
12,
2316,
16,
17571,
264,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x82d921dbC70E1FE231284615aCFb0650fe01c8C2/sources/contracts/Equb.sol
|
bytes32 txHash = keccak256( abi.encodePacked(block.timestamp, block.number, address(this)) );
|
function createProposal(
address _poolAddress,
address _proposer,
string memory _title,
string memory _description,
address _startupAddress,
string memory _startupWebsite,
string memory _proposerTwitter,
string memory _proposerTelegram,
string memory _proposerFacebook
) public {
proposalsByPool[_poolAddress].push(
Proposal(
_poolAddress,
_proposer,
_title,
_description,
_startupAddress,
_startupWebsite,
_proposerTwitter,
_proposerTelegram,
_proposerFacebook,
votingDuration,
true,
0,
0
)
);
proposalsCount[_poolAddress]++;
}
| 1,865,236 |
[
1,
3890,
1578,
2229,
2310,
273,
417,
24410,
581,
5034,
12,
377,
24126,
18,
3015,
4420,
329,
12,
2629,
18,
5508,
16,
1203,
18,
2696,
16,
1758,
12,
2211,
3719,
11272,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
752,
14592,
12,
203,
3639,
1758,
389,
6011,
1887,
16,
203,
3639,
1758,
389,
685,
5607,
16,
203,
3639,
533,
3778,
389,
2649,
16,
203,
3639,
533,
3778,
389,
3384,
16,
203,
3639,
1758,
389,
23939,
1887,
16,
203,
3639,
533,
3778,
389,
23939,
19186,
16,
203,
3639,
533,
3778,
389,
685,
5607,
23539,
6132,
16,
203,
3639,
533,
3778,
389,
685,
5607,
56,
19938,
16,
203,
3639,
533,
3778,
389,
685,
5607,
11824,
3618,
203,
565,
262,
1071,
288,
203,
3639,
450,
22536,
858,
2864,
63,
67,
6011,
1887,
8009,
6206,
12,
203,
5411,
19945,
12,
203,
7734,
389,
6011,
1887,
16,
203,
7734,
389,
685,
5607,
16,
203,
7734,
389,
2649,
16,
203,
7734,
389,
3384,
16,
203,
7734,
389,
23939,
1887,
16,
203,
7734,
389,
23939,
19186,
16,
203,
7734,
389,
685,
5607,
23539,
6132,
16,
203,
7734,
389,
685,
5607,
56,
19938,
16,
203,
7734,
389,
685,
5607,
11824,
3618,
16,
203,
7734,
331,
17128,
5326,
16,
203,
7734,
638,
16,
203,
7734,
374,
16,
203,
7734,
374,
203,
5411,
262,
203,
3639,
11272,
203,
3639,
450,
22536,
1380,
63,
67,
6011,
1887,
3737,
15,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./libs/DecMath.sol";
import "./moneymarkets/IMoneyMarket.sol";
import "./models/fee/IFeeModel.sol";
import "./models/interest/IInterestModel.sol";
import "./NFT.sol";
import "./rewards/MPHMinter.sol";
import "./models/interest-oracle/IInterestOracle.sol";
// DeLorean Interest -- It's coming back from the future!
// EL PSY CONGROO
// Author: Zefram Lou
// Contact: [email protected]
contract DInterest is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
// Constants
uint256 internal constant PRECISION = 10**18;
uint256 internal constant ONE = 10**18;
uint256 internal constant EXTRA_PRECISION = 10**27; // used for sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
// User deposit data
// Each deposit has an ID used in the depositNFT, which is equal to its index in `deposits` plus 1
struct Deposit {
uint256 amount; // Amount of stablecoin deposited
uint256 maturationTimestamp; // Unix timestamp after which the deposit may be withdrawn, in seconds
uint256 interestOwed; // Deficit incurred to the pool at time of deposit
uint256 initialMoneyMarketIncomeIndex; // Money market's income index at time of deposit
bool active; // True if not yet withdrawn, false if withdrawn
bool finalSurplusIsNegative;
uint256 finalSurplusAmount; // Surplus remaining after withdrawal
uint256 mintMPHAmount; // Amount of MPH minted to user
uint256 depositTimestamp; // Unix timestamp at time of deposit, in seconds
}
Deposit[] internal deposits;
uint256 public latestFundedDepositID; // the ID of the most recently created deposit that was funded
uint256 public unfundedUserDepositAmount; // the deposited stablecoin amount (plus interest owed) whose deficit hasn't been funded
// Funding data
// Each funding has an ID used in the fundingNFT, which is equal to its index in `fundingList` plus 1
struct Funding {
// deposits with fromDepositID < ID <= toDepositID are funded
uint256 fromDepositID;
uint256 toDepositID;
uint256 recordedFundedDepositAmount; // the current stablecoin amount earning interest for the funder
uint256 recordedMoneyMarketIncomeIndex; // the income index at the last update (creation or withdrawal)
uint256 creationTimestamp; // Unix timestamp at time of deposit, in seconds
}
Funding[] internal fundingList;
// the sum of (recordedFundedDepositAmount / recordedMoneyMarketIncomeIndex) of all fundings
uint256
public sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex;
// Params
uint256 public MinDepositPeriod; // Minimum deposit period, in seconds
uint256 public MaxDepositPeriod; // Maximum deposit period, in seconds
uint256 public MinDepositAmount; // Minimum deposit amount for each deposit, in stablecoins
uint256 public MaxDepositAmount; // Maximum deposit amount for each deposit, in stablecoins
// Instance variables
uint256 public totalDeposit;
uint256 public totalInterestOwed;
// External smart contracts
IMoneyMarket public moneyMarket;
ERC20 public stablecoin;
IFeeModel public feeModel;
IInterestModel public interestModel;
IInterestOracle public interestOracle;
NFT public depositNFT;
NFT public fundingNFT;
MPHMinter public mphMinter;
// Events
event EDeposit(
address indexed sender,
uint256 indexed depositID,
uint256 amount,
uint256 maturationTimestamp,
uint256 interestAmount,
uint256 mintMPHAmount
);
event EWithdraw(
address indexed sender,
uint256 indexed depositID,
uint256 indexed fundingID,
bool early,
uint256 takeBackMPHAmount
);
event EFund(
address indexed sender,
uint256 indexed fundingID,
uint256 deficitAmount
);
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
event ESetParamUint(
address indexed sender,
string indexed paramName,
uint256 newValue
);
struct DepositLimit {
uint256 MinDepositPeriod;
uint256 MaxDepositPeriod;
uint256 MinDepositAmount;
uint256 MaxDepositAmount;
}
constructor(
DepositLimit memory _depositLimit,
address _moneyMarket, // Address of IMoneyMarket that's used for generating interest (owner must be set to this DInterest contract)
address _stablecoin, // Address of the stablecoin used to store funds
address _feeModel, // Address of the FeeModel contract that determines how fees are charged
address _interestModel, // Address of the InterestModel contract that determines how much interest to offer
address _interestOracle, // Address of the InterestOracle contract that provides the average interest rate
address _depositNFT, // Address of the NFT representing ownership of deposits (owner must be set to this DInterest contract)
address _fundingNFT, // Address of the NFT representing ownership of fundings (owner must be set to this DInterest contract)
address _mphMinter // Address of the contract for handling minting MPH to users
) public {
// Verify input addresses
require(
_moneyMarket.isContract() &&
_stablecoin.isContract() &&
_feeModel.isContract() &&
_interestModel.isContract() &&
_interestOracle.isContract() &&
_depositNFT.isContract() &&
_fundingNFT.isContract() &&
_mphMinter.isContract(),
"DInterest: An input address is not a contract"
);
moneyMarket = IMoneyMarket(_moneyMarket);
stablecoin = ERC20(_stablecoin);
feeModel = IFeeModel(_feeModel);
interestModel = IInterestModel(_interestModel);
interestOracle = IInterestOracle(_interestOracle);
depositNFT = NFT(_depositNFT);
fundingNFT = NFT(_fundingNFT);
mphMinter = MPHMinter(_mphMinter);
// Ensure moneyMarket uses the same stablecoin
require(
moneyMarket.stablecoin() == _stablecoin,
"DInterest: moneyMarket.stablecoin() != _stablecoin"
);
// Ensure interestOracle uses the same moneyMarket
require(
interestOracle.moneyMarket() == _moneyMarket,
"DInterest: interestOracle.moneyMarket() != _moneyMarket"
);
// Verify input uint256 parameters
require(
_depositLimit.MaxDepositPeriod > 0 &&
_depositLimit.MaxDepositAmount > 0,
"DInterest: An input uint256 is 0"
);
require(
_depositLimit.MinDepositPeriod <= _depositLimit.MaxDepositPeriod,
"DInterest: Invalid DepositPeriod range"
);
require(
_depositLimit.MinDepositAmount <= _depositLimit.MaxDepositAmount,
"DInterest: Invalid DepositAmount range"
);
MinDepositPeriod = _depositLimit.MinDepositPeriod;
MaxDepositPeriod = _depositLimit.MaxDepositPeriod;
MinDepositAmount = _depositLimit.MinDepositAmount;
MaxDepositAmount = _depositLimit.MaxDepositAmount;
totalDeposit = 0;
}
/**
Public actions
*/
function deposit(uint256 amount, uint256 maturationTimestamp)
external
nonReentrant
{
_deposit(amount, maturationTimestamp);
}
function withdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, false);
}
function earlyWithdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, true);
}
function multiDeposit(
uint256[] calldata amountList,
uint256[] calldata maturationTimestampList
) external nonReentrant {
require(
amountList.length == maturationTimestampList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < amountList.length; i = i.add(1)) {
_deposit(amountList[i], maturationTimestampList[i]);
}
}
function multiWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], false);
}
}
function multiEarlyWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], true);
}
}
/**
Deficit funding
*/
function fundAll() external nonReentrant {
// Calculate current deficit
(bool isNegative, uint256 deficit) = surplus();
require(isNegative, "DInterest: No deficit available");
require(
!depositIsFunded(deposits.length),
"DInterest: All deposits funded"
);
// Create funding struct
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: deposits.length,
recordedFundedDepositAmount: unfundedUserDepositAmount,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
// Update relevant values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
unfundedUserDepositAmount.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = deposits.length;
unfundedUserDepositAmount = 0;
_fund(deficit);
}
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
// Deposits with ID [latestFundedDepositID+1, toDepositID] will be funded
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
// Deposit still active, use current surplus
(isNegative, surplus) = surplusOfDeposit(id);
} else {
// Deposit has been withdrawn, use recorded final surplus
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
// Add on deficit to total
totalDeficit = totalDeficit.add(surplus);
} else {
// Has surplus
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
// Deposits selected have a surplus as a whole, revert
revert("DInterest: Selected deposits in surplus");
} else {
// Deduct surplus from totalDeficit
totalDeficit = totalDeficit.sub(totalSurplus);
}
// Create funding struct
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
// Update relevant values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
function payInterestToFunder(uint256 fundingID)
external
returns (uint256 interestAmount)
{
address funder = fundingNFT.ownerOf(fundingID);
require(funder == msg.sender, "DInterest: not funder");
Funding storage f = _getFunding(fundingID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
interestAmount = f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
// Update funding values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
// Send interest to funder
if (interestAmount > 0) {
interestAmount = moneyMarket.withdraw(interestAmount);
if (interestAmount > 0) {
stablecoin.safeTransfer(funder, interestAmount);
}
}
}
/**
Public getters
*/
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds
) public returns (uint256 interestAmount) {
(, uint256 moneyMarketInterestRatePerSecond) =
interestOracle.updateAndQuery();
(bool surplusIsNegative, uint256 surplusAmount) = surplus();
return
interestModel.calculateInterestAmount(
depositAmount,
depositPeriodInSeconds,
moneyMarketInterestRatePerSecond,
surplusIsNegative,
surplusAmount
);
}
/**
@notice Computes the floating interest amount owed to deficit funders, which will be paid out
when a funded deposit is withdrawn.
Formula: \sum_i recordedFundedDepositAmount_i * (incomeIndex / recordedMoneyMarketIncomeIndex_i - 1)
= incomeIndex * (\sum_i recordedFundedDepositAmount_i / recordedMoneyMarketIncomeIndex_i)
- (totalDeposit + totalInterestOwed - unfundedUserDepositAmount)
where i refers to a funding
*/
function totalInterestOwedToFunders()
public
returns (uint256 interestOwed)
{
uint256 currentValue =
moneyMarket
.incomeIndex()
.mul(
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
)
.div(EXTRA_PRECISION);
uint256 initialValue =
totalDeposit.add(totalInterestOwed).sub(unfundedUserDepositAmount);
if (currentValue < initialValue) {
return 0;
}
return currentValue.sub(initialValue);
}
function surplus() public returns (bool isNegative, uint256 surplusAmount) {
uint256 totalValue = moneyMarket.totalValue();
uint256 totalOwed =
totalDeposit.add(totalInterestOwed).add(
totalInterestOwedToFunders()
);
if (totalValue >= totalOwed) {
// Locked value more than owed deposits, positive surplus
isNegative = false;
surplusAmount = totalValue.sub(totalOwed);
} else {
// Locked value less than owed deposits, negative surplus
isNegative = true;
surplusAmount = totalOwed.sub(totalValue);
}
}
function surplusOfDeposit(uint256 depositID)
public
returns (bool isNegative, uint256 surplusAmount)
{
Deposit storage depositEntry = _getDeposit(depositID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
uint256 currentDepositValue =
depositEntry.amount.mul(currentMoneyMarketIncomeIndex).div(
depositEntry.initialMoneyMarketIncomeIndex
);
uint256 owed = depositEntry.amount.add(depositEntry.interestOwed);
if (currentDepositValue >= owed) {
// Locked value more than owed deposits, positive surplus
isNegative = false;
surplusAmount = currentDepositValue.sub(owed);
} else {
// Locked value less than owed deposits, negative surplus
isNegative = true;
surplusAmount = owed.sub(currentDepositValue);
}
}
function depositIsFunded(uint256 id) public view returns (bool) {
return (id <= latestFundedDepositID);
}
function depositsLength() external view returns (uint256) {
return deposits.length;
}
function fundingListLength() external view returns (uint256) {
return fundingList.length;
}
function getDeposit(uint256 depositID)
external
view
returns (Deposit memory)
{
return deposits[depositID.sub(1)];
}
function getFunding(uint256 fundingID)
external
view
returns (Funding memory)
{
return fundingList[fundingID.sub(1)];
}
function moneyMarketIncomeIndex() external returns (uint256) {
return moneyMarket.incomeIndex();
}
/**
Param setters
*/
function setFeeModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
feeModel = IFeeModel(newValue);
emit ESetParamAddress(msg.sender, "feeModel", newValue);
}
function setInterestModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestModel = IInterestModel(newValue);
emit ESetParamAddress(msg.sender, "interestModel", newValue);
}
function setInterestOracle(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestOracle = IInterestOracle(newValue);
require(
interestOracle.moneyMarket() == address(moneyMarket),
"DInterest: moneyMarket mismatch"
);
emit ESetParamAddress(msg.sender, "interestOracle", newValue);
}
function setRewards(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
moneyMarket.setRewards(newValue);
emit ESetParamAddress(msg.sender, "moneyMarket.rewards", newValue);
}
function setMPHMinter(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
mphMinter = MPHMinter(newValue);
emit ESetParamAddress(msg.sender, "mphMinter", newValue);
}
function setMinDepositPeriod(uint256 newValue) external onlyOwner {
require(newValue <= MaxDepositPeriod, "DInterest: invalid value");
MinDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MinDepositPeriod", newValue);
}
function setMaxDepositPeriod(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositPeriod && newValue > 0,
"DInterest: invalid value"
);
MaxDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MaxDepositPeriod", newValue);
}
function setMinDepositAmount(uint256 newValue) external onlyOwner {
require(
newValue <= MaxDepositAmount && newValue > 0,
"DInterest: invalid value"
);
MinDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MinDepositAmount", newValue);
}
function setMaxDepositAmount(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositAmount && newValue > 0,
"DInterest: invalid value"
);
MaxDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MaxDepositAmount", newValue);
}
function setDepositNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
depositNFT.setTokenURI(tokenId, newURI);
}
function setDepositNFTBaseURI(string calldata newURI) external onlyOwner {
depositNFT.setBaseURI(newURI);
}
function setDepositNFTContractURI(string calldata newURI)
external
onlyOwner
{
depositNFT.setContractURI(newURI);
}
function setFundingNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
fundingNFT.setTokenURI(tokenId, newURI);
}
function setFundingNFTBaseURI(string calldata newURI) external onlyOwner {
fundingNFT.setBaseURI(newURI);
}
function setFundingNFTContractURI(string calldata newURI)
external
onlyOwner
{
fundingNFT.setContractURI(newURI);
}
/**
Internal getters
*/
function _getDeposit(uint256 depositID)
internal
view
returns (Deposit storage)
{
return deposits[depositID.sub(1)];
}
function _getFunding(uint256 fundingID)
internal
view
returns (Funding storage)
{
return fundingList[fundingID.sub(1)];
}
/**
Internals
*/
function _deposit(uint256 amount, uint256 maturationTimestamp) internal {
// Ensure deposit amount is not more than maximum
require(
amount >= MinDepositAmount && amount <= MaxDepositAmount,
"DInterest: Deposit amount out of range"
);
// Ensure deposit period is at least MinDepositPeriod
uint256 depositPeriod = maturationTimestamp.sub(now);
require(
depositPeriod >= MinDepositPeriod &&
depositPeriod <= MaxDepositPeriod,
"DInterest: Deposit period out of range"
);
// Update totalDeposit
totalDeposit = totalDeposit.add(amount);
// Calculate interest
uint256 interestAmount = calculateInterestAmount(amount, depositPeriod);
require(interestAmount > 0, "DInterest: interestAmount == 0");
// Update funding related data
uint256 id = deposits.length.add(1);
unfundedUserDepositAmount = unfundedUserDepositAmount.add(amount).add(
interestAmount
);
// Update totalInterestOwed
totalInterestOwed = totalInterestOwed.add(interestAmount);
// Mint MPH for msg.sender
uint256 mintMPHAmount =
mphMinter.mintDepositorReward(
msg.sender,
amount,
depositPeriod,
interestAmount
);
// Record deposit data for `msg.sender`
deposits.push(
Deposit({
amount: amount,
maturationTimestamp: maturationTimestamp,
interestOwed: interestAmount,
initialMoneyMarketIncomeIndex: moneyMarket.incomeIndex(),
active: true,
finalSurplusIsNegative: false,
finalSurplusAmount: 0,
mintMPHAmount: mintMPHAmount,
depositTimestamp: now
})
);
// Transfer `amount` stablecoin to DInterest
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Lend `amount` stablecoin to money market
stablecoin.safeIncreaseAllowance(address(moneyMarket), amount);
moneyMarket.deposit(amount);
// Mint depositNFT
depositNFT.mint(msg.sender, id);
// Emit event
emit EDeposit(
msg.sender,
id,
amount,
maturationTimestamp,
interestAmount,
mintMPHAmount
);
}
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
// Verify deposit is active and set to inactive
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
// Verify `now < depositEntry.maturationTimestamp`
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
// Verify `now > depositEntry.depositTimestamp`
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
} else {
// Verify `now >= depositEntry.maturationTimestamp`
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
// Verify msg.sender owns the depositNFT
require(
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
// Restrict scope to prevent stack too deep error
{
// Take back MPH
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
// Emit event
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
// Update totalDeposit
totalDeposit = totalDeposit.sub(depositEntry.amount);
// Update totalInterestOwed
totalInterestOwed = totalInterestOwed.sub(depositEntry.interestOwed);
// Fetch the income index & surplus before withdrawal, to prevent our withdrawal from
// increasing the income index when the money market vault total supply is extremely small
// (vault as in yEarn & Harvest vaults)
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
// Restrict scope to prevent stack too deep error
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
// Withdraw the principal of the deposit from money market
withdrawAmount = depositEntry.amount;
} else {
// Withdraw the principal & the interest from money market
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
// Send `withdrawAmount - feeAmount` stablecoin to `msg.sender`
stablecoin.safeTransfer(msg.sender, withdrawAmount.sub(feeAmount));
// Send `feeAmount` stablecoin to feeModel beneficiary
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
// If deposit was funded, payout interest to funder
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
} else {
// Remove deposit from future deficit fundings
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
// Record remaining surplus
if (!early) {
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
}
function _payInterestToFunder(
uint256 fundingID,
uint256 depositID,
uint256 depositAmount,
uint256 depositMaturationTimestamp,
uint256 depositInterestOwed,
bool depositSurplusIsNegative,
uint256 depositSurplus,
uint256 currentMoneyMarketIncomeIndex,
bool early
) internal {
Funding storage f = _getFunding(fundingID);
require(
depositID > f.fromDepositID && depositID <= f.toDepositID,
"DInterest: Deposit not funded by fundingID"
);
uint256 interestAmount =
f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
// Update funding values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedFundedDepositAmount = f.recordedFundedDepositAmount.sub(
depositAmount.add(depositInterestOwed)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
// Send interest to funder
address funder = fundingNFT.ownerOf(fundingID);
uint256 transferToFunderAmount =
(early && depositSurplusIsNegative)
? interestAmount.add(depositSurplus)
: interestAmount;
if (transferToFunderAmount > 0) {
transferToFunderAmount = moneyMarket.withdraw(
transferToFunderAmount
);
if (transferToFunderAmount > 0) {
stablecoin.safeTransfer(funder, transferToFunderAmount);
}
}
// Mint funder rewards
mphMinter.mintFunderReward(
funder,
depositAmount,
f.creationTimestamp,
depositMaturationTimestamp,
interestAmount,
early
);
}
function _fund(uint256 totalDeficit) internal {
// Transfer `totalDeficit` stablecoins from msg.sender
stablecoin.safeTransferFrom(msg.sender, address(this), totalDeficit);
// Deposit `totalDeficit` stablecoins into moneyMarket
stablecoin.safeIncreaseAllowance(address(moneyMarket), totalDeficit);
moneyMarket.deposit(totalDeficit);
// Mint fundingNFT
fundingNFT.mint(msg.sender, fundingList.length);
// Emit event
uint256 fundingID = fundingList.length;
emit EFund(msg.sender, fundingID, totalDeficit);
}
}
|
Deposits with ID [latestFundedDepositID+1, toDepositID] will be funded Deposit still active, use current surplus Deposit has been withdrawn, use recorded final surplus Add on deficit to total Has surplus Deposits selected have a surplus as a whole, revert Deduct surplus from totalDeficit
|
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
(isNegative, surplus) = surplusOfDeposit(id);
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
totalDeficit = totalDeficit.add(surplus);
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
revert("DInterest: Selected deposits in surplus");
totalDeficit = totalDeficit.sub(totalSurplus);
}
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
| 892,233 |
[
1,
758,
917,
1282,
598,
1599,
306,
13550,
42,
12254,
758,
1724,
734,
15,
21,
16,
358,
758,
1724,
734,
65,
903,
506,
9831,
785,
4019,
538,
305,
4859,
2695,
16,
999,
783,
5056,
10103,
4019,
538,
305,
711,
2118,
598,
9446,
82,
16,
999,
16421,
727,
5056,
10103,
1436,
603,
1652,
335,
305,
358,
2078,
4393,
5056,
10103,
4019,
538,
1282,
3170,
1240,
279,
5056,
10103,
487,
279,
7339,
16,
15226,
463,
329,
853,
5056,
10103,
628,
2078,
3262,
335,
305,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
284,
1074,
8438,
12,
11890,
5034,
358,
758,
1724,
734,
13,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
203,
5411,
358,
758,
1724,
734,
405,
4891,
42,
12254,
758,
1724,
734,
16,
203,
5411,
315,
40,
29281,
30,
4019,
538,
1282,
1818,
9831,
785,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
358,
758,
1724,
734,
1648,
443,
917,
1282,
18,
2469,
16,
203,
5411,
315,
40,
29281,
30,
1962,
358,
758,
1724,
734,
6,
203,
3639,
11272,
203,
203,
3639,
261,
6430,
29886,
16,
2254,
5034,
5056,
10103,
13,
273,
5056,
10103,
5621,
203,
3639,
2583,
12,
291,
14959,
16,
315,
40,
29281,
30,
2631,
1652,
335,
305,
2319,
8863,
203,
203,
3639,
2254,
5034,
2078,
3262,
335,
305,
273,
374,
31,
203,
3639,
2254,
5034,
2078,
7719,
10103,
273,
374,
31,
203,
3639,
2254,
5034,
2078,
758,
1724,
1876,
29281,
774,
42,
1074,
273,
374,
31,
203,
3639,
364,
261,
203,
5411,
2254,
5034,
612,
273,
4891,
42,
12254,
758,
1724,
734,
18,
1289,
12,
21,
1769,
203,
5411,
612,
1648,
358,
758,
1724,
734,
31,
203,
5411,
612,
273,
612,
18,
1289,
12,
21,
13,
203,
3639,
262,
288,
203,
5411,
4019,
538,
305,
2502,
443,
1724,
1622,
273,
389,
588,
758,
1724,
12,
350,
1769,
203,
5411,
309,
261,
323,
1724,
1622,
18,
3535,
13,
288,
203,
7734,
261,
291,
14959,
16,
5056,
10103,
13,
273,
5056,
10103,
951,
758,
1724,
12,
350,
1769,
203,
7734,
261,
291,
14959,
16,
5056,
10103,
13,
2
] |
./partial_match/3/0xE195a5eB1d9281389Db98c2cB99621b65C2321D7/sources/XERRUIMToken.sol
|
* @dev Decrease the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol @param _spender The address which will spend the funds. @param _subtractedValue The amount of tokens to decrease the allowance by./
|
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| 5,152,106 |
[
1,
23326,
448,
326,
3844,
434,
2430,
716,
392,
3410,
2935,
358,
279,
17571,
264,
18,
6617,
537,
1410,
506,
2566,
1347,
2935,
63,
67,
87,
1302,
264,
65,
422,
374,
18,
2974,
15267,
2935,
460,
353,
7844,
358,
999,
333,
445,
358,
4543,
576,
4097,
261,
464,
2529,
3180,
326,
1122,
2492,
353,
1131,
329,
13,
6338,
9041,
355,
483,
18485,
3155,
18,
18281,
225,
389,
87,
1302,
264,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
225,
389,
1717,
1575,
329,
620,
1021,
3844,
434,
2430,
358,
20467,
326,
1699,
1359,
635,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
20467,
23461,
12,
2867,
389,
87,
1302,
264,
16,
2254,
389,
1717,
1575,
329,
620,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2254,
11144,
273,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
15533,
203,
565,
309,
261,
67,
1717,
1575,
329,
620,
405,
11144,
13,
288,
203,
1377,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
374,
31,
203,
1377,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
11144,
18,
1717,
24899,
1717,
1575,
329,
620,
1769,
203,
565,
289,
203,
565,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
19226,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title Basic.
* @dev Deposit & Withdraw ERC721 from DSA.
*/
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {DSMath} from "../../common/math.sol";
import {Basic} from "../../common/basic.sol";
import {Events} from "./events.sol";
abstract contract BasicResolver is Events, DSMath, Basic {
/**
* @dev Deposit Assets To Smart Account.
* @notice Deposit a ERC721 token to DSA
* @param token Address of token.
* @param tokenId ID of token.
* @param getId ID to retrieve tokenId.
* @param setId ID stores the tokenId.
*/
function depositERC721(
address token,
uint256 tokenId,
uint256 getId,
uint256 setId
)
public
payable
returns (string memory _eventName, bytes memory _eventParam)
{
uint256 _tokenId = getUint(getId, tokenId);
IERC721 tokenContract = IERC721(token);
tokenContract.safeTransferFrom(msg.sender, address(this), _tokenId);
setUint(setId, _tokenId);
_eventName = "LogDepositERC721(address,address,uint256,uint256,uint256)";
_eventParam = abi.encode(token, msg.sender, _tokenId, getId, setId);
}
/**
* @dev Withdraw Assets To Smart Account.
* @notice Withdraw a ERC721 token from DSA
* @param token Address of the token.
* @param tokenId ID of token.
* @param to The address to receive the token upon withdrawal
* @param getId ID to retrieve tokenId.
* @param setId ID stores the tokenId.
*/
function withdrawERC721(
address token,
uint256 tokenId,
address payable to,
uint256 getId,
uint256 setId
)
public
payable
returns (string memory _eventName, bytes memory _eventParam)
{
uint256 _tokenId = getUint(getId, tokenId);
IERC721 tokenContract = IERC721(token);
tokenContract.safeTransferFrom(address(this), to, _tokenId);
setUint(setId, _tokenId);
_eventName = "LogWithdrawERC721(address,uint256,address,uint256,uint256)";
_eventParam = abi.encode(token, _tokenId, to, getId, setId);
}
}
contract ConnectV2BasicERC721Polygon is BasicResolver {
string public constant name = "BASIC-ERC721-v1.0";
}
|
* @dev Withdraw Assets To Smart Account. @notice Withdraw a ERC721 token from DSA @param token Address of the token. @param tokenId ID of token. @param to The address to receive the token upon withdrawal @param getId ID to retrieve tokenId. @param setId ID stores the tokenId./
|
function withdrawERC721(
address token,
uint256 tokenId,
address payable to,
uint256 getId,
uint256 setId
)
public
payable
returns (string memory _eventName, bytes memory _eventParam)
{
uint256 _tokenId = getUint(getId, tokenId);
IERC721 tokenContract = IERC721(token);
tokenContract.safeTransferFrom(address(this), to, _tokenId);
setUint(setId, _tokenId);
_eventName = "LogWithdrawERC721(address,uint256,address,uint256,uint256)";
_eventParam = abi.encode(token, _tokenId, to, getId, setId);
}
| 12,880,457 |
[
1,
1190,
9446,
26284,
2974,
19656,
6590,
18,
225,
3423,
9446,
279,
4232,
39,
27,
5340,
1147,
628,
463,
5233,
225,
1147,
5267,
434,
326,
1147,
18,
225,
1147,
548,
1599,
434,
1147,
18,
225,
358,
1021,
1758,
358,
6798,
326,
1147,
12318,
598,
9446,
287,
225,
2634,
1599,
358,
4614,
1147,
548,
18,
225,
10446,
1599,
9064,
326,
1147,
548,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
598,
9446,
654,
39,
27,
5340,
12,
203,
3639,
1758,
1147,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1758,
8843,
429,
358,
16,
203,
3639,
2254,
5034,
2634,
16,
203,
3639,
2254,
5034,
10446,
203,
565,
262,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
3639,
1135,
261,
1080,
3778,
389,
2575,
461,
16,
1731,
3778,
389,
2575,
786,
13,
203,
565,
288,
203,
3639,
2254,
5034,
389,
2316,
548,
273,
336,
5487,
12,
26321,
16,
1147,
548,
1769,
203,
3639,
467,
654,
39,
27,
5340,
1147,
8924,
273,
467,
654,
39,
27,
5340,
12,
2316,
1769,
203,
3639,
1147,
8924,
18,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
358,
16,
389,
2316,
548,
1769,
203,
203,
3639,
444,
5487,
12,
542,
548,
16,
389,
2316,
548,
1769,
203,
203,
3639,
389,
2575,
461,
273,
315,
1343,
1190,
9446,
654,
39,
27,
5340,
12,
2867,
16,
11890,
5034,
16,
2867,
16,
11890,
5034,
16,
11890,
5034,
2225,
31,
203,
3639,
389,
2575,
786,
273,
24126,
18,
3015,
12,
2316,
16,
389,
2316,
548,
16,
358,
16,
2634,
16,
10446,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
// File: contracts/tokenIssueContract.sol
// Written by Metabridge - https://www.metabridgeagency.com
// We are a community of passionate <humans /> building a distributed world
pragma solidity ^0.8.0;
/// @author MetaBridge Agency LLC
/// @title The bank for the Sheeba play to earn rewards.
contract SheebaGameTokenBank {
IERC20 public erc20Token;
address public owner;
string public name = "Sheeba Game Token Bank";
mapping(address => bool) public admins;
mapping(address => uint256) public earners;
mapping(address => bool) public blockedAddresses;
constructor(address _erc20Token) {
erc20Token = IERC20(_erc20Token);
owner = msg.sender;
// Set the owner as a dev
admins[msg.sender] = true;
}
/// Return the users token balance.
/// @param userAddress the address to check.
/// @return the users token balance.
function getTokenBalance(address userAddress) public view returns(uint256) {
return erc20Token.balanceOf(userAddress);
}
/// Return the contracts balance of tokens.
/// @return the contracts balance of tokens.
function getContractBalance() public view returns(uint256) {
return getTokenBalance(address(this));
}
/// Return the users reward balance.
/// @param userAddress the address to check.
/// @return the users reward balance.
function getRewardsBalance(address userAddress) public view returns(uint256) {
return earners[userAddress];
}
/// Store 'totalSheeb'.
/// @param userAddressToAdd the address to add.
/// @param totalSheeb the amount of sheeb to add to the user. Not in full form decimal ex. 10 Tokens = 10
function addTokens(address userAddressToAdd, uint256 totalSheeb) public {
// Check if admin
require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN");
// Start
earners[userAddressToAdd] = earners[userAddressToAdd] += totalSheeb * 10 ** 18;
}
/// Store 'totalSheeb' per user.
/// @param userAddresses the addresses to add.
/// @param points the points to add. Not in full form decimal ex. 10 Tokens = 10
function addTokensMultiple(address[] memory userAddresses, uint256[] memory points) public {
// Check if admin
require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN");
require(userAddresses.length == points.length, "Unequal arrays");
// Start
for (uint i=0; i<userAddresses.length; i++) {
earners[userAddresses[i]] = earners[userAddresses[i]] += points[i] * 10 ** 18;
}
}
/// Store 'userAddressToAdd' as either bot or not.
/// @param userAddressToAdd the address to add or remove.
/// @param isBot the indication of whether or not this address is a bot.
function userIsBot(address userAddressToAdd, bool isBot) public {
// Check if admin
require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN");
// Start
blockedAddresses[userAddressToAdd] = isBot;
}
/// Store 'newAdmin' as admin.
/// @param newAdmin the address to add.
function addAdmin(address newAdmin) public {
require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN");
// Any admin can remove the another
require(newAdmin != msg.sender, "Cannot add yourself as admin.");
admins[newAdmin] = true;
}
/// Store 'adminToRemove' as admin.
/// @param adminToRemove the address to remove.
function removeAdmin(address adminToRemove) public {
require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN");
// Any admin can remove the another
require(adminToRemove != msg.sender, "Cannot remove yourself as admin.");
admins[adminToRemove] = false;
}
/// Remove the tokens from the contract in case of upgrade or contract issue.
function retrieveRewardTokens() public {
require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN");
uint256 contractBalance = getTokenBalance(address(this));
erc20Token.transfer(msg.sender, contractBalance);
}
/// Send the tokens to the users wallet.
function recieveReward() public {
uint256 amountToSend = earners[msg.sender];
// Get balance of contract
uint256 contractBalance = getTokenBalance(address(this));
require(amountToSend > 0, "You have not earned any tokens.");
require(contractBalance >= amountToSend, "Not enough tokens in the contract. Please contact the DEV team.");
earners[msg.sender] = 0;
erc20Token.transfer(msg.sender, amountToSend);
}
}
|
Return the users token balance. @param userAddress the address to check. @return the users token balance.
|
function getTokenBalance(address userAddress) public view returns(uint256) {
return erc20Token.balanceOf(userAddress);
}
| 122,631 |
[
1,
990,
326,
3677,
1147,
11013,
18,
225,
729,
1887,
326,
1758,
358,
866,
18,
327,
326,
3677,
1147,
11013,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
9162,
13937,
12,
2867,
729,
1887,
13,
1071,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
327,
6445,
71,
3462,
1345,
18,
12296,
951,
12,
1355,
1887,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
// Importing data Contract
import "./FlightSuretyData.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
// Total of airlines before concensus starts.
uint8 private constant MIN_AIRLINES = 4;
// Needs 10 ether to be able to register an irline.
uint256 private constant MIN_FUNDS = 10000000000000000000;
// Maximun insurance allowed to be paid by a user.
uint256 private constant MAX_INSURANCE = 1000000000000000000;
address private contractOwner; // Account used to deploy contract
FlightSuretyData flightSuretyData;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(string => Flight) private flights;
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
// Modify to call data contract's status
require(true, "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");
_;
}
// Checking if airline is approved in order to get money in.
modifier activeAirline() {
require(flightSuretyData.getAirlineStatus(msg.sender) == true, "Your must be an active airline.");
_;
}
// Value has to be bigger than 0.
modifier validFunds() {
require(msg.value > 0, "Value is not valid");
_;
}
// Make sure flight exists
modifier requireFlight(string flight) {
require(flights[flight].isRegistered == true, "This flight not exists");
_;
}
// Maximun value of insurance reached.
modifier requireMaximumInsurance() {
require(msg.value <= MAX_INSURANCE, "You insurance limit reached");
_;
}
// Airline Approved
modifier requireAirlineApproved() {
( , uint256 fundUser, bool statusUser) = flightSuretyData.getAirlines(msg.sender);
require(statusUser == true, "Airline has to be approved.");
_;
}
// Airline Approved
modifier requireUserFunding() {
( , uint256 fundUser, bool statusUser) = flightSuretyData.getAirlines(msg.sender);
require(fundUser >= MIN_FUNDS, "Airline has not provided enough funding");
_;
}
// Airline Approved
modifier requireAirlineNotCreated(address checkAddress) {
( address airline, uint256 fundUser, bool statusUser) = flightSuretyData.getAirlines(checkAddress);
require(airline != checkAddress, "Airline should not exist");
_;
}
// Flight Approved
modifier requireFlightDoesntExist(string flight) {
require(flights[flight].isRegistered == false, "Flight should not exist");
_;
}
// Check Insurance dont exisr
modifier requireInsuranceDoesntExist(string flight) {
( address passenger, , , ) = flightSuretyData.getInsurance(flight, msg.sender);
require(passenger != msg.sender, "User already bought insurance. All sales final");
_;
}
// Events
event RegisteringAirline(address airline);
event AirlineVote(address airline, address sender);
event AddedFunds(address airline, uint256 funds);
event FlightRegistered(address airline, string flight);
event FlightBooked(address passenger, string flight);
event InsuranceBought(address passenger, string flight);
event MoneyWithdrawn(address passenger, uint256 funds);
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
* Got to update the data contract in here.
*/
constructor(address dataContract) public
{
contractOwner = msg.sender;
flightSuretyData = FlightSuretyData(dataContract);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
pure
returns(bool)
{
return true; // Modify to call data contract's status
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline( address flightAddress, bool userVote ) external requireAirlineNotCreated(flightAddress) requireAirlineApproved requireUserFunding
{
bool status = false;
uint256 consensus = 0;
uint256 neededVotes = 0;
uint256 vote = 0;
if(userVote){
vote = 1;
}
if (flightSuretyData.getAirlineCounter() >= 4) {
consensus = flightSuretyData.addConcensus(flightAddress, msg.sender, vote);
neededVotes = flightSuretyData.getAirlineCounter().div(2);
}
if (consensus >= neededVotes) {
status = true;
flightSuretyData.registerAirline(flightAddress, 0, status);
emit RegisteringAirline(flightAddress);
}
else{
emit AirlineVote(flightAddress, msg.sender);
}
}
function getAirlineInfo (address searchAirline) external view returns (address airline, uint256 funds, bool status){
(airline, funds, status) = flightSuretyData.getAirlines(searchAirline);
}
function airlineTotal() external view returns(uint256) {
return flightSuretyData.getAirlineCounter();
}
// Add funds to airline
function addFunds() external payable validFunds activeAirline
{
flightSuretyData.setAirlineFunds.value(msg.value)(msg.sender, msg.value);
emit AddedFunds(msg.sender, msg.value);
}
// Buy insurance
function buyInsurance(string flight) external payable validFunds requireMaximumInsurance requireFlight(flight) requireInsuranceDoesntExist(flight) {
flightSuretyData.buyInsurace.value(msg.value)(flight, msg.sender);
emit InsuranceBought(msg.sender, flight);
}
// Get Insurance
function getInsurance(string flight) external view returns(address r_passenger, string r_flight, uint256 value, bool claimed) {
(r_passenger, r_flight, value, claimed) = flightSuretyData.getInsurance(flight, msg.sender);
}
function contractBalance() external view returns(uint) {
return flightSuretyData.contractBalance();
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(string flight) external requireFlightDoesntExist(flight) requireUserFunding
{
flights[flight] = Flight({
isRegistered: true,
statusCode: STATUS_CODE_UNKNOWN,
updatedTimestamp: now,
airline: msg.sender
});
emit FlightRegistered(msg.sender, flight);
}
function getFlightInformation(string flight) external view returns (address airline, uint256 updatedTimestamp, bool isRegistered, uint8 statusCode){
Flight memory flightInfo = flights[flight];
return (flightInfo.airline, flightInfo.updatedTimestamp, flightInfo.isRegistered, flightInfo.statusCode);
}
function initiateWithdrawl() external payable {
require(flightSuretyData.getPassengerFunds(msg.sender) > 0);
flightSuretyData.pay(msg.sender, flightSuretyData.getPassengerFunds(msg.sender));
emit MoneyWithdrawn(msg.sender, flightSuretyData.getPassengerFunds(msg.sender));
}
/**
* Same as processFlightStatus its just external for testing with test classes. Would not be open in real life.
*/
function processFlightStatusTesting(address airline, string flight, uint256 timestamp, uint8 statusCode) external
{
// Update flight
flights[flight].updatedTimestamp = timestamp;
flights[flight].statusCode = statusCode;
if(statusCode > STATUS_CODE_ON_TIME){
flightSuretyData.creditInsurees(flight);
}
}
/**
* @dev Called after oracle has updated flight status
* Triggered when oracle returns with result and decides things. check status code?
* look for passengers insurance on flight and do the retuns
*/
function processFlightStatus(address airline, string flight, uint256 timestamp, uint8 statusCode) internal
{
// Update flight
flights[flight].updatedTimestamp = timestamp;
flights[flight].statusCode = statusCode;
if(statusCode > STATUS_CODE_ON_TIME){
flightSuretyData.creditInsurees(flight);
}
}
// Generate a request for oracles to fetch flight information
// generated from the UI
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp
)
external
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airline, flight, timestamp);
}
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 wei;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Register an oracle with the contract
function registerOracle
(
)
external
payable
{
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function getMyIndexes() view external returns(uint8[3])
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
external
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
function getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns(uint8[3])
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
|
Checking if airline is approved in order to get money in.
|
modifier activeAirline() {
require(flightSuretyData.getAirlineStatus(msg.sender) == true, "Your must be an active airline.");
_;
}
| 6,480,340 |
[
1,
14294,
309,
23350,
1369,
353,
20412,
316,
1353,
358,
336,
15601,
316,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
2695,
29752,
1369,
1435,
288,
203,
3639,
2583,
12,
19131,
55,
594,
4098,
751,
18,
588,
29752,
1369,
1482,
12,
3576,
18,
15330,
13,
422,
638,
16,
315,
15446,
1297,
506,
392,
2695,
23350,
1369,
1199,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-20
*/
// Sources flattened with hardhat v2.4.3 https://hardhat.org
// File openzeppelin-solidity/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File openzeppelin-solidity/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File openzeppelin-solidity/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File openzeppelin-solidity/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File openzeppelin-solidity/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File openzeppelin-solidity/contracts/governance/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*
* _Available since v3.3._
*/
contract TimelockController is AccessControl {
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
mapping(bytes32 => uint256) private _timestamps;
uint256 private _minDelay;
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with a given `minDelay`.
*/
constructor(uint256 minDelay, address[] memory proposers, address[] memory executors) {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
// deployer + self administration
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
// register proposers
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_setupRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRoleOrOpenRole(bytes32 role) {
if (!hasRole(role, address(0))) {
_checkRole(role, _msgSender());
}
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable {}
/**
* @dev Returns whether an id correspond to a registered operation. This
* includes both Pending, Ready and Done operations.
*/
function isOperation(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > 0;
}
/**
* @dev Returns whether an operation is pending or not.
*/
function isOperationPending(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > _DONE_TIMESTAMP;
}
/**
* @dev Returns whether an operation is ready or not.
*/
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id);
// solhint-disable-next-line not-rely-on-time
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
/**
* @dev Returns the timestamp at with an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {
return _timestamps[id];
}
/**
* @dev Returns the minimum delay for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256 duration) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, datas, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits a {CallScheduled} event.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay);
}
}
/**
* @dev Schedule an operation that is to becomes valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
// solhint-disable-next-line not-rely-on-time
_timestamps[id] = block.timestamp + delay;
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) {
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute an (ready) operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function execute(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
/**
* @dev Execute an (ready) operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_beforeCall(predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
_call(id, i, targets[i], values[i], datas[i]);
}
_afterCall(id);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 predecessor) private view {
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
require(isOperationReady(id), "TimelockController: operation is not ready");
_timestamps[id] = _DONE_TIMESTAMP;
}
/**
* @dev Execute an operation's call.
*
* Emits a {CallExecuted} event.
*/
function _call(bytes32 id, uint256 index, address target, uint256 value, bytes calldata data) private {
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data);
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) external virtual {
require(msg.sender == address(this), "TimelockController: caller must be timelock");
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
}
// File contracts/interfaces/ISwapRouter.sol
pragma solidity 0.8.6;
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
// solhint-disable-next-line func-name-mixedcase
function WETH9() external pure returns (address);
}
// File openzeppelin-solidity/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File openzeppelin-solidity/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File openzeppelin-solidity/contracts/token/ERC20/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File openzeppelin-solidity/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File openzeppelin-solidity/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File openzeppelin-solidity/contracts/utils/math/[email protected]
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File contracts/HATToken.sol
pragma solidity 0.8.6;
contract HATToken is IERC20 {
struct PendingMinter {
uint256 seedAmount;
uint256 setMinterPendingAt;
}
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice EIP-20 token name for this token
// solhint-disable-next-line const-name-snakecase
string public constant name = "hats.finance";
/// @notice EIP-20 token symbol for this token
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "HAT";
/// @notice EIP-20 token decimals for this token
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public override totalSupply;
address public governance;
address public governancePending;
uint256 public setGovernancePendingAt;
uint256 public immutable timeLockDelay;
uint256 public constant CAP = 10000000e18;
/// @notice Address which may mint new tokens
/// minter -> minting seedAmount
mapping (address => uint256) public minters;
/// @notice Address which may mint new tokens
/// minter -> minting seedAmount
mapping (address => PendingMinter) public pendingMinters;
// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice An event thats emitted when a new minter address is pending
event MinterPending(address indexed minter, uint256 seedAmount, uint256 at);
/// @notice An event thats emitted when the minter address is changed
event MinterChanged(address indexed minter, uint256 seedAmount);
/// @notice An event thats emitted when a new governance address is pending
event GovernancePending(address indexed oldGovernance, address indexed newGovernance, uint256 at);
/// @notice An event thats emitted when a new governance address is set
event GovernanceChanged(address indexed oldGovernance, address indexed newGovernance);
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Construct a new HAT token
*/
// solhint-disable-next-line func-visibility
constructor(address _governance, uint256 _timeLockDelay) {
governance = _governance;
timeLockDelay = _timeLockDelay;
}
function setPendingGovernance(address _governance) external {
require(msg.sender == governance, "HAT:!governance");
require(_governance != address(0), "HAT:!_governance");
governancePending = _governance;
// solhint-disable-next-line not-rely-on-time
setGovernancePendingAt = block.timestamp;
emit GovernancePending(governance, _governance, setGovernancePendingAt);
}
function confirmGovernance() external {
require(msg.sender == governance, "HAT:!governance");
require(setGovernancePendingAt > 0, "HAT:!governancePending");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp - setGovernancePendingAt > timeLockDelay,
"HAT: cannot confirm governance at this time");
emit GovernanceChanged(governance, governancePending);
governance = governancePending;
setGovernancePendingAt = 0;
}
function setPendingMinter(address _minter, uint256 _cap) external {
require(msg.sender == governance, "HAT::!governance");
pendingMinters[_minter].seedAmount = _cap;
// solhint-disable-next-line not-rely-on-time
pendingMinters[_minter].setMinterPendingAt = block.timestamp;
emit MinterPending(_minter, _cap, pendingMinters[_minter].setMinterPendingAt);
}
function confirmMinter(address _minter) external {
require(msg.sender == governance, "HAT::mint: only the governance can confirm minter");
require(pendingMinters[_minter].setMinterPendingAt > 0, "HAT:: no pending minter was set");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp - pendingMinters[_minter].setMinterPendingAt > timeLockDelay,
"HATToken: cannot confirm at this time");
minters[_minter] = pendingMinters[_minter].seedAmount;
pendingMinters[_minter].setMinterPendingAt = 0;
emit MinterChanged(_minter, pendingMinters[_minter].seedAmount);
}
function burn(uint256 _amount) external {
return _burn(msg.sender, _amount);
}
function mint(address _account, uint _amount) external {
require(minters[msg.sender] >= _amount, "HATToken: amount greater than limitation");
minters[msg.sender] = SafeMath.sub(minters[msg.sender], _amount);
_mint(_account, _amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external override view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external override returns (bool) {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, 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, uint addedValue) external virtual returns (bool) {
require(spender != address(0), "HAT: increaseAllowance to the zero address");
uint96 valueToAdd = safe96(addedValue, "HAT::increaseAllowance: addedValue exceeds 96 bits");
allowances[msg.sender][spender] =
add96(allowances[msg.sender][spender], valueToAdd, "HAT::increaseAllowance: overflows");
emit Approval(msg.sender, spender, allowances[msg.sender][spender]);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint subtractedValue) external virtual returns (bool) {
require(spender != address(0), "HAT: decreaseAllowance to the zero address");
uint96 valueTosubtract = safe96(subtractedValue, "HAT::decreaseAllowance: subtractedValue exceeds 96 bits");
allowances[msg.sender][spender] = sub96(allowances[msg.sender][spender], valueTosubtract,
"HAT::decreaseAllowance: spender allowance is less than subtractedValue");
emit Approval(msg.sender, spender, allowances[msg.sender][spender]);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "HAT::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "HAT::permit: invalid signature");
require(signatory == owner, "HAT::permit: unauthorized");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "HAT::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view override returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external override returns (bool) {
uint96 amount = safe96(rawAmount, "HAT::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external override returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance = sub96(spenderAllowance, amount,
"HAT::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "HAT::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "HAT::delegateBySig: invalid nonce");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= expiry, "HAT::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) external view returns (uint96) {
require(blockNumber < block.number, "HAT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/**
* @notice Mint new tokens
* @param dst The address of the destination account
* @param rawAmount The number of tokens to be minted
*/
function _mint(address dst, uint rawAmount) internal {
require(dst != address(0), "HAT::mint: cannot transfer to the zero address");
require(SafeMath.add(totalSupply, rawAmount) <= CAP, "ERC20Capped: CAP exceeded");
// mint the amount
uint96 amount = safe96(rawAmount, "HAT::mint: amount exceeds 96 bits");
totalSupply = safe96(SafeMath.add(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits");
// transfer the amount to the recipient
balances[dst] = add96(balances[dst], amount, "HAT::mint: transfer amount overflows");
emit Transfer(address(0), dst, amount);
// move delegates
_moveDelegates(address(0), delegates[dst], amount);
}
/**
* Burn tokens
* @param src The address of the source account
* @param rawAmount The number of tokens to be burned
*/
function _burn(address src, uint rawAmount) internal {
require(src != address(0), "HAT::burn: cannot burn to the zero address");
// burn the amount
uint96 amount = safe96(rawAmount, "HAT::burn: amount exceeds 96 bits");
totalSupply = safe96(SafeMath.sub(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits");
// reduce the amount from src address
balances[src] = sub96(balances[src], amount, "HAT::burn: burn amount exceeds balance");
emit Transfer(src, address(0), amount);
// move delegates
_moveDelegates(delegates[src], address(0), amount);
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "HAT::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "HAT::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "HAT::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "HAT::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "HAT::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "HAT::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "HAT::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint) {
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly { chainId := chainid() }
return chainId;
}
}
// File openzeppelin-solidity/contracts/security/[email protected]
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;
}
}
// File contracts/HATMaster.sol
// Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md
pragma solidity 0.8.6;
contract HATMaster is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // The user share of the pool based on the amount of lpToken the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HATs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.rewardPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `rewardPerShare` (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.
}
struct PoolUpdate {
uint256 blockNumber;// update blocknumber
uint256 totalAllocPoint; //totalAllocPoint
}
struct RewardsSplit {
//the percentage of the total reward to reward the hacker via vesting contract(claim reported)
uint256 hackerVestedReward;
//the percentage of the total reward to reward the hacker(claim reported)
uint256 hackerReward;
// the percentage of the total reward to be sent to the committee
uint256 committeeReward;
// the percentage of the total reward to be swap to HAT and to be burned
uint256 swapAndBurn;
// the percentage of the total reward to be swap to HAT and sent to governance
uint256 governanceHatReward;
// the percentage of the total reward to be swap to HAT and sent to the hacker
uint256 hackerHatReward;
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken;
uint256 allocPoint;
uint256 lastRewardBlock;
uint256 rewardPerShare;
uint256 totalUsersAmount;
uint256 lastProcessedTotalAllocPoint;
uint256 balance;
}
// Info of each pool.
struct PoolReward {
RewardsSplit rewardsSplit;
uint256[] rewardsLevels;
bool committeeCheckIn;
uint256 vestingDuration;
uint256 vestingPeriods;
}
HATToken public immutable HAT;
uint256 public immutable REWARD_PER_BLOCK;
uint256 public immutable START_BLOCK;
uint256 public immutable MULTIPLIER_PERIOD;
// Info of each pool.
PoolInfo[] public poolInfo;
PoolUpdate[] public globalPoolUpdates;
mapping(address => uint256) public poolId1; // poolId1 count from 1, subtraction 1 before using with poolInfo
// Info of each user that stakes LP tokens. pid => user address => info
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
//pid -> PoolReward
mapping (uint256=>PoolReward) internal poolsRewards;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SendReward(address indexed user, uint256 indexed pid, uint256 amount, uint256 requestedAmount);
event MassUpdatePools(uint256 _fromPid, uint256 _toPid);
constructor(
HATToken _hat,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _multiplierPeriod
// solhint-disable-next-line func-visibility
) {
HAT = _hat;
REWARD_PER_BLOCK = _rewardPerBlock;
START_BLOCK = _startBlock;
MULTIPLIER_PERIOD = _multiplierPeriod;
}
/**
* @dev massUpdatePools - Update reward variables for all pools
* Be careful of gas spending!
* @param _fromPid update pools range from this pool id
* @param _toPid update pools range to this pool id
*/
function massUpdatePools(uint256 _fromPid, uint256 _toPid) external {
require(_toPid <= poolInfo.length, "pool range is too big");
require(_fromPid <= _toPid, "invalid pool range");
for (uint256 pid = _fromPid; pid < _toPid; ++pid) {
updatePool(pid);
}
emit MassUpdatePools(_fromPid, _toPid);
}
function claimReward(uint256 _pid) external {
_deposit(_pid, 0);
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 lastRewardBlock = pool.lastRewardBlock;
if (block.number <= lastRewardBlock) {
return;
}
uint256 totalUsersAmount = pool.totalUsersAmount;
uint256 lastPoolUpdate = globalPoolUpdates.length-1;
if (totalUsersAmount == 0) {
pool.lastRewardBlock = block.number;
pool.lastProcessedTotalAllocPoint = lastPoolUpdate;
return;
}
uint256 reward = calcPoolReward(_pid, lastRewardBlock, lastPoolUpdate);
uint256 amountCanMint = HAT.minters(address(this));
reward = amountCanMint < reward ? amountCanMint : reward;
if (reward > 0) {
HAT.mint(address(this), reward);
}
pool.rewardPerShare = pool.rewardPerShare.add(reward.mul(1e12).div(totalUsersAmount));
pool.lastRewardBlock = block.number;
pool.lastProcessedTotalAllocPoint = lastPoolUpdate;
}
/**
* @dev getMultiplier - multiply blocks with relevant multiplier for specific range
* @param _from range's from block
* @param _to range's to block
* will revert if from < START_BLOCK or _to < _from
*/
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256 result) {
uint256[25] memory rewardMultipliers = [uint256(4413), 4413, 8825, 7788, 6873, 6065,
5353, 4724, 4169, 3679, 3247, 2865,
2528, 2231, 1969, 1738, 1534, 1353,
1194, 1054, 930, 821, 724, 639, 0];
uint256 max = rewardMultipliers.length;
uint256 i = (_from - START_BLOCK) / MULTIPLIER_PERIOD + 1;
for (; i < max; i++) {
uint256 endBlock = MULTIPLIER_PERIOD * i + START_BLOCK;
if (_to <= endBlock) {
break;
}
result += (endBlock - _from) * rewardMultipliers[i-1];
_from = endBlock;
}
result += (_to - _from) * rewardMultipliers[i > max ? (max-1) : (i-1)];
}
function getRewardForBlocksRange(uint256 _from, uint256 _to, uint256 _allocPoint, uint256 _totalAllocPoint)
public
view
returns (uint256 reward) {
if (_totalAllocPoint > 0) {
reward = getMultiplier(_from, _to).mul(REWARD_PER_BLOCK).mul(_allocPoint).div(_totalAllocPoint).div(100);
}
}
/**
* @dev calcPoolReward -
* calculate rewards for a pool by iterating over the history of totalAllocPoints updates.
* and sum up all rewards periods from pool.lastRewardBlock till current block number.
* @param _pid pool id
* @param _from block starting calculation
* @param _lastPoolUpdate lastPoolUpdate
* @return reward
*/
function calcPoolReward(uint256 _pid, uint256 _from, uint256 _lastPoolUpdate) public view returns(uint256 reward) {
uint256 poolAllocPoint = poolInfo[_pid].allocPoint;
uint256 i = poolInfo[_pid].lastProcessedTotalAllocPoint;
for (; i < _lastPoolUpdate; i++) {
uint256 nextUpdateBlock = globalPoolUpdates[i+1].blockNumber;
reward =
reward.add(getRewardForBlocksRange(_from,
nextUpdateBlock,
poolAllocPoint,
globalPoolUpdates[i].totalAllocPoint));
_from = nextUpdateBlock;
}
return reward.add(getRewardForBlocksRange(_from,
block.number,
poolAllocPoint,
globalPoolUpdates[i].totalAllocPoint));
}
function _deposit(uint256 _pid, uint256 _amount) internal nonReentrant {
require(poolsRewards[_pid].committeeCheckIn, "committee not checked in yet");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeTransferReward(msg.sender, pending, _pid);
}
}
if (_amount > 0) {
uint256 lpSupply = pool.balance;
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
pool.balance = pool.balance.add(_amount);
uint256 factoredAmount = _amount;
if (pool.totalUsersAmount > 0) {
factoredAmount = pool.totalUsersAmount.mul(_amount).div(lpSupply);
}
user.amount = user.amount.add(factoredAmount);
pool.totalUsersAmount = pool.totalUsersAmount.add(factoredAmount);
}
user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function _withdraw(uint256 _pid, uint256 _amount) internal nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not enough user balance");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeTransferReward(msg.sender, pending, _pid);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 amountToWithdraw = _amount.mul(pool.balance).div(pool.totalUsersAmount);
pool.balance = pool.balance.sub(amountToWithdraw);
pool.lpToken.safeTransfer(msg.sender, amountToWithdraw);
pool.totalUsersAmount = pool.totalUsersAmount.sub(_amount);
}
user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function _emergencyWithdraw(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0, "user.amount = 0");
uint256 factoredBalance = user.amount.mul(pool.balance).div(pool.totalUsersAmount);
pool.totalUsersAmount = pool.totalUsersAmount.sub(user.amount);
user.amount = 0;
user.rewardDebt = 0;
pool.balance = pool.balance.sub(factoredBalance);
pool.lpToken.safeTransfer(msg.sender, factoredBalance);
emit EmergencyWithdraw(msg.sender, _pid, factoredBalance);
}
// -------- For manage pool ---------
function add(uint256 _allocPoint, IERC20 _lpToken) internal {
require(poolId1[address(_lpToken)] == 0, "HATMaster::add: lpToken is already in pool");
poolId1[address(_lpToken)] = poolInfo.length + 1;
uint256 lastRewardBlock = block.number > START_BLOCK ? block.number : START_BLOCK;
uint256 totalAllocPoint = (globalPoolUpdates.length == 0) ? _allocPoint :
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint.add(_allocPoint);
if (globalPoolUpdates.length > 0 &&
globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) {
//already update in this block
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint;
} else {
globalPoolUpdates.push(PoolUpdate({
blockNumber: block.number,
totalAllocPoint: totalAllocPoint
}));
}
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
rewardPerShare: 0,
totalUsersAmount: 0,
lastProcessedTotalAllocPoint: globalPoolUpdates.length-1,
balance: 0
}));
}
function set(uint256 _pid, uint256 _allocPoint) internal {
updatePool(_pid);
uint256 totalAllocPoint =
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint
.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
if (globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) {
//already update in this block
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint;
} else {
globalPoolUpdates.push(PoolUpdate({
blockNumber: block.number,
totalAllocPoint: totalAllocPoint
}));
}
poolInfo[_pid].allocPoint = _allocPoint;
}
// Safe HAT transfer function, just in case if rounding error causes pool to not have enough HATs.
function safeTransferReward(address _to, uint256 _amount, uint256 _pid) internal {
uint256 hatBalance = HAT.balanceOf(address(this));
if (_amount > hatBalance) {
HAT.transfer(_to, hatBalance);
emit SendReward(_to, _pid, hatBalance, _amount);
} else {
HAT.transfer(_to, _amount);
emit SendReward(_to, _pid, _amount, _amount);
}
}
}
// File contracts/tokenlock/ITokenLock.sol
pragma solidity 0.8.6;
pragma experimental ABIEncoderV2;
interface ITokenLock {
enum Revocability { NotSet, Enabled, Disabled }
// -- Balances --
function currentBalance() external view returns (uint256);
// -- Time & Periods --
function currentTime() external view returns (uint256);
function duration() external view returns (uint256);
function sinceStartTime() external view returns (uint256);
function amountPerPeriod() external view returns (uint256);
function periodDuration() external view returns (uint256);
function currentPeriod() external view returns (uint256);
function passedPeriods() external view returns (uint256);
// -- Locking & Release Schedule --
function availableAmount() external view returns (uint256);
function vestedAmount() external view returns (uint256);
function releasableAmount() external view returns (uint256);
function totalOutstandingAmount() external view returns (uint256);
function surplusAmount() external view returns (uint256);
// -- Value Transfer --
function release() external;
function withdrawSurplus(uint256 _amount) external;
function revoke() external;
}
// File contracts/tokenlock/ITokenLockFactory.sol
pragma solidity 0.8.6;
interface ITokenLockFactory {
// -- Factory --
function setMasterCopy(address _masterCopy) external;
function createTokenLock(
address _token,
address _owner,
address _beneficiary,
uint256 _managedAmount,
uint256 _startTime,
uint256 _endTime,
uint256 _periods,
uint256 _releaseStartTime,
uint256 _vestingCliffTime,
ITokenLock.Revocability _revocable,
bool _canDelegate
) external returns(address contractAddress);
}
// File contracts/Governable.sol
pragma solidity 0.8.6;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an governance) that can be granted exclusive access to
* specific functions.
*
* The governance account will be passed on initialization of the contract. This
* can later be changed with {setPendingGovernance and then transferGovernorship after 2 days}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyGovernance`, which can be applied to your functions to restrict their use to
* the governance.
*/
contract Governable {
address private _governance;
address public governancePending;
uint256 public setGovernancePendingAt;
uint256 public constant TIME_LOCK_DELAY = 2 days;
/// @notice An event thats emitted when a new governance address is set
event GovernorshipTransferred(address indexed _previousGovernance, address indexed _newGovernance);
/// @notice An event thats emitted when a new governance address is pending
event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at);
/**
* @dev Throws if called by any account other than the governance.
*/
modifier onlyGovernance() {
require(msg.sender == _governance, "only governance");
_;
}
/**
* @dev setPendingGovernance set a pending governance address.
* NOTE: transferGovernorship can be called after a time delay of 2 days.
*/
function setPendingGovernance(address _newGovernance) external onlyGovernance {
require(_newGovernance != address(0), "Governable:new governance is the zero address");
governancePending = _newGovernance;
// solhint-disable-next-line not-rely-on-time
setGovernancePendingAt = block.timestamp;
emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt);
}
/**
* @dev transferGovernorship transfer governorship to the pending governance address.
* NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance.
*/
function transferGovernorship() external onlyGovernance {
require(setGovernancePendingAt > 0, "Governable: no pending governance");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY,
"Governable: cannot confirm governance at this time");
emit GovernorshipTransferred(_governance, governancePending);
_governance = governancePending;
setGovernancePendingAt = 0;
}
/**
* @dev Returns the address of the current governance.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Initializes the contract setting the initial governance.
*/
function initialize(address _initialGovernance) internal {
_governance = _initialGovernance;
emit GovernorshipTransferred(address(0), _initialGovernance);
}
}
// File contracts/HATVaults.sol
// Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md
pragma solidity 0.8.6;
contract HATVaults is Governable, HATMaster {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct PendingApproval {
address beneficiary;
uint256 severity;
address approver;
}
struct ClaimReward {
uint256 hackerVestedReward;
uint256 hackerReward;
uint256 committeeReward;
uint256 swapAndBurn;
uint256 governanceHatReward;
uint256 hackerHatReward;
}
struct PendingRewardsLevels {
uint256 timestamp;
uint256[] rewardsLevels;
}
struct GeneralParameters {
uint256 hatVestingDuration;
uint256 hatVestingPeriods;
uint256 withdrawPeriod;
uint256 safetyPeriod; //withdraw disable period in seconds
uint256 setRewardsLevelsDelay;
uint256 withdrawRequestEnablePeriod;
uint256 withdrawRequestPendingPeriod;
uint256 claimFee; //claim fee in ETH
}
//pid -> committee address
mapping(uint256=>address) public committees;
mapping(address => uint256) public swapAndBurns;
//hackerAddress ->(token->amount)
mapping(address => mapping(address => uint256)) public hackersHatRewards;
//token -> amount
mapping(address => uint256) public governanceHatRewards;
//pid -> PendingApproval
mapping(uint256 => PendingApproval) public pendingApprovals;
//poolId -> (address -> requestTime)
mapping(uint256 => mapping(address => uint256)) public withdrawRequests;
//poolId -> PendingRewardsLevels
mapping(uint256 => PendingRewardsLevels) public pendingRewardsLevels;
mapping(uint256 => bool) public poolDepositPause;
GeneralParameters public generalParameters;
uint256 internal constant REWARDS_LEVEL_DENOMINATOR = 10000;
ITokenLockFactory public immutable tokenLockFactory;
ISwapRouter public immutable uniSwapRouter;
uint256 public constant MINIMUM_DEPOSIT = 1e6;
modifier onlyCommittee(uint256 _pid) {
require(committees[_pid] == msg.sender, "only committee");
_;
}
modifier noPendingApproval(uint256 _pid) {
require(pendingApprovals[_pid].beneficiary == address(0), "pending approval exist");
_;
}
modifier noSafetyPeriod() {
//disable withdraw for safetyPeriod (e.g 1 hour) each withdrawPeriod(e.g 11 hours)
// solhint-disable-next-line not-rely-on-time
require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) <
generalParameters.withdrawPeriod,
"safety period");
_;
}
event SetCommittee(uint256 indexed _pid, address indexed _committee);
event AddPool(uint256 indexed _pid,
uint256 indexed _allocPoint,
address indexed _lpToken,
address _committee,
string _descriptionHash,
uint256[] _rewardsLevels,
RewardsSplit _rewardsSplit,
uint256 _rewardVestingDuration,
uint256 _rewardVestingPeriods);
event SetPool(uint256 indexed _pid, uint256 indexed _allocPoint, bool indexed _registered, string _descriptionHash);
event Claim(address indexed _claimer, string _descriptionHash);
event SetRewardsSplit(uint256 indexed _pid, RewardsSplit _rewardsSplit);
event SetRewardsLevels(uint256 indexed _pid, uint256[] _rewardsLevels);
event PendingRewardsLevelsLog(uint256 indexed _pid, uint256[] _rewardsLevels, uint256 _timeStamp);
event SwapAndSend(uint256 indexed _pid,
address indexed _beneficiary,
uint256 indexed _amountSwaped,
uint256 _amountReceived,
address _tokenLock);
event SwapAndBurn(uint256 indexed _pid, uint256 indexed _amountSwaped, uint256 indexed _amountBurned);
event SetVestingParams(uint256 indexed _pid, uint256 indexed _duration, uint256 indexed _periods);
event SetHatVestingParams(uint256 indexed _duration, uint256 indexed _periods);
event ClaimApprove(address indexed _approver,
uint256 indexed _pid,
address indexed _beneficiary,
uint256 _severity,
address _tokenLock,
ClaimReward _claimReward);
event PendingApprovalLog(uint256 indexed _pid,
address indexed _beneficiary,
uint256 indexed _severity,
address _approver);
event WithdrawRequest(uint256 indexed _pid,
address indexed _beneficiary,
uint256 indexed _withdrawEnableTime);
event SetWithdrawSafetyPeriod(uint256 indexed _withdrawPeriod, uint256 indexed _safetyPeriod);
event RewardDepositors(uint256 indexed _pid, uint256 indexed _amount);
/**
* @dev constructor -
* @param _rewardsToken the reward token address (HAT)
* @param _rewardPerBlock the reward amount per block the contract will reward pools
* @param _startBlock start block of of which the contract will start rewarding from.
* @param _multiplierPeriod a fix period value. each period will have its own multiplier value.
* which set the reward for each period. e.g a value of 100000 means that each such period is 100000 blocks.
* @param _hatGovernance the governance address.
* Some of the contracts functions are limited only to governance :
* addPool,setPool,dismissPendingApprovalClaim,approveClaim,
* setHatVestingParams,setVestingParams,setRewardsSplit
* @param _uniSwapRouter uni swap v3 router to be used to swap tokens for HAT token.
* @param _tokenLockFactory address of the token lock factory to be used
* to create a vesting contract for the approved claim reporter.
*/
constructor(
address _rewardsToken,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _multiplierPeriod,
address _hatGovernance,
ISwapRouter _uniSwapRouter,
ITokenLockFactory _tokenLockFactory
// solhint-disable-next-line func-visibility
) HATMaster(HATToken(_rewardsToken), _rewardPerBlock, _startBlock, _multiplierPeriod) {
Governable.initialize(_hatGovernance);
uniSwapRouter = _uniSwapRouter;
tokenLockFactory = _tokenLockFactory;
generalParameters = GeneralParameters({
hatVestingDuration: 90 days,
hatVestingPeriods:90,
withdrawPeriod: 11 hours,
safetyPeriod: 1 hours,
setRewardsLevelsDelay: 2 days,
withdrawRequestEnablePeriod: 7 days,
withdrawRequestPendingPeriod: 7 days,
claimFee: 0
});
}
/**
* @dev pendingApprovalClaim - called by a committee to set a pending approval claim.
* The pending approval need to be approved or dismissed by the hats governance.
* This function should be called only on a safety period, where withdrawn is disable.
* Upon a call to this function by the committee the pool withdrawn will be disable
* till governance will approve or dismiss this pending approval.
* @param _pid pool id
* @param _beneficiary the approval claim beneficiary
* @param _severity approval claim severity
*/
function pendingApprovalClaim(uint256 _pid, address _beneficiary, uint256 _severity)
external
onlyCommittee(_pid)
noPendingApproval(_pid) {
require(_beneficiary != address(0), "beneficiary is zero");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) >=
generalParameters.withdrawPeriod,
"none safety period");
require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range");
pendingApprovals[_pid] = PendingApproval({
beneficiary: _beneficiary,
severity: _severity,
approver: msg.sender
});
emit PendingApprovalLog(_pid, _beneficiary, _severity, msg.sender);
}
/**
* @dev setWithdrawRequestParams - called by hats governance to set withdraw request params
* @param _withdrawRequestPendingPeriod - the time period where the withdraw request is pending.
* @param _withdrawRequestEnablePeriod - the time period where the withdraw is enable for a withdraw request.
*/
function setWithdrawRequestParams(uint256 _withdrawRequestPendingPeriod, uint256 _withdrawRequestEnablePeriod)
external
onlyGovernance {
generalParameters.withdrawRequestPendingPeriod = _withdrawRequestPendingPeriod;
generalParameters.withdrawRequestEnablePeriod = _withdrawRequestEnablePeriod;
}
/**
* @dev dismissPendingApprovalClaim - called by hats governance to dismiss a pending approval claim.
* @param _pid pool id
*/
function dismissPendingApprovalClaim(uint256 _pid) external onlyGovernance {
delete pendingApprovals[_pid];
}
/**
* @dev approveClaim - called by hats governance to approve a pending approval claim.
* @param _pid pool id
*/
function approveClaim(uint256 _pid) external onlyGovernance nonReentrant {
require(pendingApprovals[_pid].beneficiary != address(0), "no pending approval");
PoolReward storage poolReward = poolsRewards[_pid];
PendingApproval memory pendingApproval = pendingApprovals[_pid];
delete pendingApprovals[_pid];
IERC20 lpToken = poolInfo[_pid].lpToken;
ClaimReward memory claimRewards = calcClaimRewards(_pid, pendingApproval.severity);
poolInfo[_pid].balance = poolInfo[_pid].balance.sub(
claimRewards.hackerReward
.add(claimRewards.hackerVestedReward)
.add(claimRewards.committeeReward)
.add(claimRewards.swapAndBurn)
.add(claimRewards.hackerHatReward)
.add(claimRewards.governanceHatReward));
address tokenLock;
if (claimRewards.hackerVestedReward > 0) {
//hacker get its reward to a vesting contract
tokenLock = tokenLockFactory.createTokenLock(
address(lpToken),
0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing.
pendingApproval.beneficiary,
claimRewards.hackerVestedReward,
// solhint-disable-next-line not-rely-on-time
block.timestamp, //start
// solhint-disable-next-line not-rely-on-time
block.timestamp + poolReward.vestingDuration, //end
poolReward.vestingPeriods,
0, //no release start
0, //no cliff
ITokenLock.Revocability.Disabled,
false
);
lpToken.safeTransfer(tokenLock, claimRewards.hackerVestedReward);
}
lpToken.safeTransfer(pendingApproval.beneficiary, claimRewards.hackerReward);
lpToken.safeTransfer(pendingApproval.approver, claimRewards.committeeReward);
//storing the amount of token which can be swap and burned so it could be swapAndBurn in a seperate tx.
swapAndBurns[address(lpToken)] = swapAndBurns[address(lpToken)].add(claimRewards.swapAndBurn);
governanceHatRewards[address(lpToken)] =
governanceHatRewards[address(lpToken)].add(claimRewards.governanceHatReward);
hackersHatRewards[pendingApproval.beneficiary][address(lpToken)] =
hackersHatRewards[pendingApproval.beneficiary][address(lpToken)].add(claimRewards.hackerHatReward);
emit ClaimApprove(msg.sender,
_pid,
pendingApproval.beneficiary,
pendingApproval.severity,
tokenLock,
claimRewards);
assert(poolInfo[_pid].balance > 0);
}
/**
* @dev rewardDepositors - add funds to pool to reward depositors.
* The funds will be given to depositors pro rata upon withdraw
* @param _pid pool id
* @param _amount amount to add
*/
function rewardDepositors(uint256 _pid, uint256 _amount) external {
require(poolInfo[_pid].balance.add(_amount).div(MINIMUM_DEPOSIT) < poolInfo[_pid].totalUsersAmount,
"amount to reward is too big");
poolInfo[_pid].lpToken.safeTransferFrom(msg.sender, address(this), _amount);
poolInfo[_pid].balance = poolInfo[_pid].balance.add(_amount);
emit RewardDepositors(_pid, _amount);
}
/**
* @dev setClaimFee - called by hats governance to set claim fee
* @param _fee claim fee in ETH
*/
function setClaimFee(uint256 _fee) external onlyGovernance {
generalParameters.claimFee = _fee;
}
/**
* @dev setWithdrawSafetyPeriod - called by hats governance to set Withdraw Period
* @param _withdrawPeriod withdraw enable period
* @param _safetyPeriod withdraw disable period
*/
function setWithdrawSafetyPeriod(uint256 _withdrawPeriod, uint256 _safetyPeriod) external onlyGovernance {
generalParameters.withdrawPeriod = _withdrawPeriod;
generalParameters.safetyPeriod = _safetyPeriod;
emit SetWithdrawSafetyPeriod(generalParameters.withdrawPeriod, generalParameters.safetyPeriod);
}
//_descriptionHash - a hash of an ipfs encrypted file which describe the claim.
// this can be use later on by the claimer to prove her claim
function claim(string memory _descriptionHash) external payable {
if (generalParameters.claimFee > 0) {
require(msg.value >= generalParameters.claimFee, "not enough fee payed");
// solhint-disable-next-line indent
payable(governance()).transfer(msg.value);
}
emit Claim(msg.sender, _descriptionHash);
}
/**
* @dev setVestingParams - set pool vesting params for rewarding claim reporter with the pool token
* @param _pid pool id
* @param _duration duration of the vesting period
* @param _periods the vesting periods
*/
function setVestingParams(uint256 _pid, uint256 _duration, uint256 _periods) external onlyGovernance {
require(_duration < 120 days, "vesting duration is too long");
require(_periods > 0, "vesting periods cannot be zero");
require(_duration >= _periods, "vesting duration smaller than periods");
poolsRewards[_pid].vestingDuration = _duration;
poolsRewards[_pid].vestingPeriods = _periods;
emit SetVestingParams(_pid, _duration, _periods);
}
/**
* @dev setHatVestingParams - set HAT vesting params for rewarding claim reporter with HAT token
* the function can be called only by governance.
* @param _duration duration of the vesting period
* @param _periods the vesting periods
*/
function setHatVestingParams(uint256 _duration, uint256 _periods) external onlyGovernance {
require(_duration < 180 days, "vesting duration is too long");
require(_periods > 0, "vesting periods cannot be zero");
require(_duration >= _periods, "vesting duration smaller than periods");
generalParameters.hatVestingDuration = _duration;
generalParameters.hatVestingPeriods = _periods;
emit SetHatVestingParams(_duration, _periods);
}
/**
* @dev setRewardsSplit - set the pool token rewards split upon an approval
* the function can be called only by governance.
* the sum of the rewards split should be less than 10000 (less than 100%)
* @param _pid pool id
* @param _rewardsSplit split
* and sent to the hacker(claim reported)
*/
function setRewardsSplit(uint256 _pid, RewardsSplit memory _rewardsSplit)
external
onlyGovernance noPendingApproval(_pid) noSafetyPeriod {
validateSplit(_rewardsSplit);
poolsRewards[_pid].rewardsSplit = _rewardsSplit;
emit SetRewardsSplit(_pid, _rewardsSplit);
}
/**
* @dev setRewardsLevelsDelay - set the timelock delay for setting rewars level
* @param _delay time delay
*/
function setRewardsLevelsDelay(uint256 _delay)
external
onlyGovernance {
require(_delay >= 2 days, "delay is too short");
generalParameters.setRewardsLevelsDelay = _delay;
}
/**
* @dev setPendingRewardsLevels - set pending request to set pool token rewards level.
* the reward level represent the percentage of the pool's token which will be split as a reward.
* the function can be called only by the pool committee.
* cannot be called if there already pending approval.
* each level should be less than 10000
* @param _pid pool id
* @param _rewardsLevels the reward levels array
*/
function setPendingRewardsLevels(uint256 _pid, uint256[] memory _rewardsLevels)
external
onlyCommittee(_pid) noPendingApproval(_pid) {
pendingRewardsLevels[_pid].rewardsLevels = checkRewardsLevels(_rewardsLevels);
// solhint-disable-next-line not-rely-on-time
pendingRewardsLevels[_pid].timestamp = block.timestamp;
emit PendingRewardsLevelsLog(_pid, _rewardsLevels, pendingRewardsLevels[_pid].timestamp);
}
/**
* @dev setRewardsLevels - set the pool token rewards level of already pending set rewards level.
* see pendingRewardsLevels
* the reward level represent the percentage of the pool's token which will be split as a reward.
* the function can be called only by the pool committee.
* cannot be called if there already pending approval.
* each level should be less than 10000
* @param _pid pool id
*/
function setRewardsLevels(uint256 _pid)
external
onlyCommittee(_pid) noPendingApproval(_pid) {
require(pendingRewardsLevels[_pid].timestamp > 0, "no pending set rewards levels");
// solhint-disable-next-line not-rely-on-time
require(block.timestamp - pendingRewardsLevels[_pid].timestamp > generalParameters.setRewardsLevelsDelay,
"cannot confirm setRewardsLevels at this time");
poolsRewards[_pid].rewardsLevels = pendingRewardsLevels[_pid].rewardsLevels;
delete pendingRewardsLevels[_pid];
emit SetRewardsLevels(_pid, poolsRewards[_pid].rewardsLevels);
}
/**
* @dev committeeCheckIn - committee check in.
* deposit is enable only after committee check in
* @param _pid pool id
*/
function committeeCheckIn(uint256 _pid) external onlyCommittee(_pid) {
poolsRewards[_pid].committeeCheckIn = true;
}
/**
* @dev setCommittee - set new committee address.
* @param _pid pool id
* @param _committee new committee address
*/
function setCommittee(uint256 _pid, address _committee)
external {
require(_committee != address(0), "committee is zero");
//governance can update committee only if committee was not checked in yet.
if (msg.sender == governance() && committees[_pid] != msg.sender) {
require(!poolsRewards[_pid].committeeCheckIn, "Committee already checked in");
} else {
require(committees[_pid] == msg.sender, "Only committee");
}
committees[_pid] = _committee;
emit SetCommittee(_pid, _committee);
}
/**
* @dev addPool - only Governance
* @param _allocPoint the pool allocation point
* @param _lpToken pool token
* @param _committee pool committee address
* @param _rewardsLevels pool reward levels(sevirities)
each level is a number between 0 and 10000.
* @param _rewardsSplit pool reward split.
each entry is a number between 0 and 10000.
total splits should be equal to 10000
* @param _descriptionHash the hash of the pool description.
* @param _rewardVestingParams vesting params
* _rewardVestingParams[0] - vesting duration
* _rewardVestingParams[1] - vesting periods
*/
function addPool(uint256 _allocPoint,
address _lpToken,
address _committee,
uint256[] memory _rewardsLevels,
RewardsSplit memory _rewardsSplit,
string memory _descriptionHash,
uint256[2] memory _rewardVestingParams)
external
onlyGovernance {
require(_rewardVestingParams[0] < 120 days, "vesting duration is too long");
require(_rewardVestingParams[1] > 0, "vesting periods cannot be zero");
require(_rewardVestingParams[0] >= _rewardVestingParams[1], "vesting duration smaller than periods");
require(_committee != address(0), "committee is zero");
add(_allocPoint, IERC20(_lpToken));
uint256 poolId = poolInfo.length-1;
committees[poolId] = _committee;
uint256[] memory rewardsLevels = checkRewardsLevels(_rewardsLevels);
RewardsSplit memory rewardsSplit = (_rewardsSplit.hackerVestedReward == 0 && _rewardsSplit.hackerReward == 0) ?
getDefaultRewardsSplit() : _rewardsSplit;
validateSplit(rewardsSplit);
poolsRewards[poolId] = PoolReward({
rewardsLevels: rewardsLevels,
rewardsSplit: rewardsSplit,
committeeCheckIn: false,
vestingDuration: _rewardVestingParams[0],
vestingPeriods: _rewardVestingParams[1]
});
emit AddPool(poolId,
_allocPoint,
address(_lpToken),
_committee,
_descriptionHash,
rewardsLevels,
rewardsSplit,
_rewardVestingParams[0],
_rewardVestingParams[1]);
}
/**
* @dev setPool
* @param _pid the pool id
* @param _allocPoint the pool allocation point
* @param _registered does this pool is registered (default true).
* @param _depositPause pause pool deposit (default false).
* This parameter can be used by the UI to include or exclude the pool
* @param _descriptionHash the hash of the pool description.
*/
function setPool(uint256 _pid,
uint256 _allocPoint,
bool _registered,
bool _depositPause,
string memory _descriptionHash)
external onlyGovernance {
require(poolInfo[_pid].lpToken != IERC20(address(0)), "pool does not exist");
set(_pid, _allocPoint);
poolDepositPause[_pid] = _depositPause;
emit SetPool(_pid, _allocPoint, _registered, _descriptionHash);
}
/**
* @dev swapBurnSend swap lptoken to HAT.
* send to beneficiary and governance its hats rewards .
* burn the rest of HAT.
* only governance are authorized to call this function.
* @param _pid the pool id
* @param _beneficiary beneficiary
* @param _amountOutMinimum minimum output of HATs at swap
* @param _fees the fees for the multi path swap
**/
function swapBurnSend(uint256 _pid,
address _beneficiary,
uint256 _amountOutMinimum,
uint24[2] memory _fees)
external
onlyGovernance {
IERC20 token = poolInfo[_pid].lpToken;
uint256 amountToSwapAndBurn = swapAndBurns[address(token)];
uint256 amountForHackersHatRewards = hackersHatRewards[_beneficiary][address(token)];
uint256 amount = amountToSwapAndBurn.add(amountForHackersHatRewards).add(governanceHatRewards[address(token)]);
require(amount > 0, "amount is zero");
swapAndBurns[address(token)] = 0;
governanceHatRewards[address(token)] = 0;
hackersHatRewards[_beneficiary][address(token)] = 0;
uint256 hatsReceived = swapTokenForHAT(amount, token, _fees, _amountOutMinimum);
uint256 burntHats = hatsReceived.mul(amountToSwapAndBurn).div(amount);
if (burntHats > 0) {
HAT.burn(burntHats);
}
emit SwapAndBurn(_pid, amount, burntHats);
address tokenLock;
uint256 hackerReward = hatsReceived.mul(amountForHackersHatRewards).div(amount);
if (hackerReward > 0) {
//hacker get its reward via vesting contract
tokenLock = tokenLockFactory.createTokenLock(
address(HAT),
0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing.
_beneficiary,
hackerReward,
// solhint-disable-next-line not-rely-on-time
block.timestamp, //start
// solhint-disable-next-line not-rely-on-time
block.timestamp + generalParameters.hatVestingDuration, //end
generalParameters.hatVestingPeriods,
0, //no release start
0, //no cliff
ITokenLock.Revocability.Disabled,
true
);
HAT.transfer(tokenLock, hackerReward);
}
emit SwapAndSend(_pid, _beneficiary, amount, hackerReward, tokenLock);
HAT.transfer(governance(), hatsReceived.sub(hackerReward).sub(burntHats));
}
/**
* @dev withdrawRequest submit a withdraw request
* @param _pid the pool id
**/
function withdrawRequest(uint256 _pid) external {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp > withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod,
"pending withdraw request exist");
// solhint-disable-next-line not-rely-on-time
withdrawRequests[_pid][msg.sender] = block.timestamp + generalParameters.withdrawRequestPendingPeriod;
emit WithdrawRequest(_pid, msg.sender, withdrawRequests[_pid][msg.sender]);
}
/**
* @dev deposit deposit to pool
* @param _pid the pool id
* @param _amount amount of pool's token to deposit
**/
function deposit(uint256 _pid, uint256 _amount) external {
require(!poolDepositPause[_pid], "deposit paused");
require(_amount >= MINIMUM_DEPOSIT, "amount less than 1e6");
//clear withdraw request
withdrawRequests[_pid][msg.sender] = 0;
_deposit(_pid, _amount);
}
/**
* @dev withdraw - withdraw user's pool share.
* user need first to submit a withdraw request.
* @param _pid the pool id
* @param _shares amount of shares user wants to withdraw
**/
function withdraw(uint256 _pid, uint256 _shares) external {
checkWithdrawRequest(_pid);
_withdraw(_pid, _shares);
}
/**
* @dev emergencyWithdraw withdraw all user's pool share without claim for reward.
* user need first to submit a withdraw request.
* @param _pid the pool id
**/
function emergencyWithdraw(uint256 _pid) external {
checkWithdrawRequest(_pid);
_emergencyWithdraw(_pid);
}
function getPoolRewardsLevels(uint256 _pid) external view returns(uint256[] memory) {
return poolsRewards[_pid].rewardsLevels;
}
function getPoolRewards(uint256 _pid) external view returns(PoolReward memory) {
return poolsRewards[_pid];
}
// GET INFO for UI
/**
* @dev getRewardPerBlock return the current pool reward per block
* @param _pid1 the pool id.
* if _pid1 = 0 , it return the current block reward for whole pools.
* otherwise it return the current block reward for _pid1-1.
* @return rewardPerBlock
**/
function getRewardPerBlock(uint256 _pid1) external view returns (uint256) {
if (_pid1 == 0) {
return getRewardForBlocksRange(block.number-1, block.number, 1, 1);
} else {
return getRewardForBlocksRange(block.number-1,
block.number,
poolInfo[_pid1 - 1].allocPoint,
globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint);
}
}
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 rewardPerShare = pool.rewardPerShare;
if (block.number > pool.lastRewardBlock && pool.totalUsersAmount > 0) {
uint256 reward = calcPoolReward(_pid, pool.lastRewardBlock, globalPoolUpdates.length-1);
rewardPerShare = rewardPerShare.add(reward.mul(1e12).div(pool.totalUsersAmount));
}
return user.amount.mul(rewardPerShare).div(1e12).sub(user.rewardDebt);
}
function getGlobalPoolUpdatesLength() external view returns (uint256) {
return globalPoolUpdates.length;
}
function getStakedAmount(uint _pid, address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_pid][_user];
return user.amount;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function calcClaimRewards(uint256 _pid, uint256 _severity)
public
view
returns(ClaimReward memory claimRewards) {
uint256 totalSupply = poolInfo[_pid].balance;
require(totalSupply > 0, "totalSupply is zero");
require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range");
//hackingRewardAmount
uint256 claimRewardAmount =
totalSupply.mul(poolsRewards[_pid].rewardsLevels[_severity]);
claimRewards.hackerVestedReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerVestedReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.hackerReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.committeeReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.committeeReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.swapAndBurn =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.swapAndBurn)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.governanceHatReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.governanceHatReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.hackerHatReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerHatReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
}
function getDefaultRewardsSplit() public pure returns (RewardsSplit memory) {
return RewardsSplit({
hackerVestedReward: 6000,
hackerReward: 2000,
committeeReward: 500,
swapAndBurn: 0,
governanceHatReward: 1000,
hackerHatReward: 500
});
}
function validateSplit(RewardsSplit memory _rewardsSplit) internal pure {
require(_rewardsSplit.hackerVestedReward
.add(_rewardsSplit.hackerReward)
.add(_rewardsSplit.committeeReward)
.add(_rewardsSplit.swapAndBurn)
.add(_rewardsSplit.governanceHatReward)
.add(_rewardsSplit.hackerHatReward) == REWARDS_LEVEL_DENOMINATOR,
"total split % should be 10000");
}
function checkWithdrawRequest(uint256 _pid) internal noPendingApproval(_pid) noSafetyPeriod {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp > withdrawRequests[_pid][msg.sender] &&
// solhint-disable-next-line not-rely-on-time
block.timestamp < withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod,
"withdraw request not valid");
withdrawRequests[_pid][msg.sender] = 0;
}
function swapTokenForHAT(uint256 _amount,
IERC20 _token,
uint24[2] memory _fees,
uint256 _amountOutMinimum)
internal
returns (uint256 hatsReceived)
{
if (address(_token) == address(HAT)) {
return _amount;
}
require(_token.approve(address(uniSwapRouter), _amount), "token approve failed");
uint256 hatBalanceBefore = HAT.balanceOf(address(this));
address weth = uniSwapRouter.WETH9();
bytes memory path;
if (address(_token) == weth) {
path = abi.encodePacked(address(_token), _fees[0], address(HAT));
} else {
path = abi.encodePacked(address(_token), _fees[0], weth, _fees[1], address(HAT));
}
hatsReceived = uniSwapRouter.exactInput(ISwapRouter.ExactInputParams({
path: path,
recipient: address(this),
// solhint-disable-next-line not-rely-on-time
deadline: block.timestamp,
amountIn: _amount,
amountOutMinimum: _amountOutMinimum
}));
require(HAT.balanceOf(address(this)) - hatBalanceBefore >= _amountOutMinimum, "wrong amount received");
}
/**
* @dev checkRewardsLevels - check rewards levels.
* each level should be less than 10000
* if _rewardsLevels length is 0 a default reward levels will be return
* default reward levels = [2000, 4000, 6000, 8000]
* @param _rewardsLevels the reward levels array
* @return rewardsLevels
*/
function checkRewardsLevels(uint256[] memory _rewardsLevels)
private
pure
returns (uint256[] memory rewardsLevels) {
uint256 i;
if (_rewardsLevels.length == 0) {
rewardsLevels = new uint256[](4);
for (i; i < 4; i++) {
//defaultRewardLevels = [2000, 4000, 6000, 8000];
rewardsLevels[i] = 2000*(i+1);
}
} else {
for (i; i < _rewardsLevels.length; i++) {
require(_rewardsLevels[i] < REWARDS_LEVEL_DENOMINATOR, "reward level can not be more than 10000");
}
rewardsLevels = _rewardsLevels;
}
}
}
// File contracts/HATTimelockController.sol
// Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md
pragma solidity 0.8.6;
contract HATTimelockController is TimelockController {
HATVaults public hatVaults;
constructor(
HATVaults _hatVaults,
uint256 _minDelay,
address[] memory _proposers,
address[] memory _executors
// solhint-disable-next-line func-visibility
) TimelockController(_minDelay, _proposers, _executors) {
require(address(_hatVaults) != address(0), "HATTimelockController: HATVaults address must not be 0");
hatVaults = _hatVaults;
}
// Whitelisted functions
function approveClaim(uint256 _pid) external onlyRole(PROPOSER_ROLE) {
hatVaults.approveClaim(_pid);
}
function addPool(uint256 _allocPoint,
address _lpToken,
address _committee,
uint256[] memory _rewardsLevels,
HATVaults.RewardsSplit memory _rewardsSplit,
string memory _descriptionHash,
uint256[2] memory _rewardVestingParams)
external
onlyRole(PROPOSER_ROLE) {
hatVaults.addPool(
_allocPoint,
_lpToken,
_committee,
_rewardsLevels,
_rewardsSplit,
_descriptionHash,
_rewardVestingParams
);
}
function setPool(uint256 _pid,
uint256 _allocPoint,
bool _registered,
bool _depositPause,
string memory _descriptionHash)
external onlyRole(PROPOSER_ROLE) {
hatVaults.setPool(
_pid,
_allocPoint,
_registered,
_depositPause,
_descriptionHash
);
}
function swapBurnSend(uint256 _pid,
address _beneficiary,
uint256 _amountOutMinimum,
uint24[2] memory _fees)
external
onlyRole(PROPOSER_ROLE) {
hatVaults.swapBurnSend(
_pid,
_beneficiary,
_amountOutMinimum,
_fees
);
}
}
|
* @dev Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./
|
function increaseAllowance(address spender, uint addedValue) external virtual returns (bool) {
require(spender != address(0), "HAT: increaseAllowance to the zero address");
uint96 valueToAdd = safe96(addedValue, "HAT::increaseAllowance: addedValue exceeds 96 bits");
allowances[msg.sender][spender] =
add96(allowances[msg.sender][spender], valueToAdd, "HAT::increaseAllowance: overflows");
emit Approval(msg.sender, spender, allowances[msg.sender][spender]);
return true;
}
| 2,322,267 |
[
1,
3641,
6478,
7033,
3304,
326,
1699,
1359,
17578,
358,
1375,
87,
1302,
264,
68,
635,
326,
4894,
18,
1220,
353,
392,
10355,
358,
288,
12908,
537,
97,
716,
848,
506,
1399,
487,
279,
20310,
360,
367,
364,
9688,
11893,
316,
288,
45,
654,
39,
3462,
17,
12908,
537,
5496,
7377,
1282,
392,
288,
23461,
97,
871,
11193,
326,
3526,
1699,
1359,
18,
29076,
30,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
10929,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
3096,
620,
13,
3903,
5024,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
87,
1302,
264,
480,
1758,
12,
20,
3631,
315,
44,
789,
30,
10929,
7009,
1359,
358,
326,
3634,
1758,
8863,
203,
3639,
2254,
10525,
460,
13786,
273,
4183,
10525,
12,
9665,
620,
16,
315,
44,
789,
2866,
267,
11908,
7009,
1359,
30,
3096,
620,
14399,
19332,
4125,
8863,
203,
3639,
1699,
6872,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
203,
3639,
527,
10525,
12,
5965,
6872,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
6487,
460,
13786,
16,
315,
44,
789,
2866,
267,
11908,
7009,
1359,
30,
9391,
87,
8863,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
17571,
264,
16,
1699,
6872,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
19226,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0x03508e35E676dD84571A701950e4503AA74b6210/sources/contracts/interface/IERC20.sol
|
Only tokens that support permit
|
function nonces(address) external view returns (uint256);
| 4,527,429 |
[
1,
3386,
2430,
716,
2865,
21447,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1661,
764,
12,
2867,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-22
*/
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function 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);
}
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);
}
}
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.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);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File contracts/ERC721A.sol
// Creator: Chiru Labs
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 (max value of uint128) of supply
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex = 0;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), 'ERC721A: global index out of bounds');
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert('ERC721A: unable to get token of owner by index');
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');
for (uint256 curr = tokenId; ; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert('ERC721A: unable to determine the owner of token');
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token');
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, 'ERC721A: approval to current owner');
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
'ERC721A: approve caller is not owner nor approved for all'
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), 'ERC721A: approved query for nonexistent token');
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), 'ERC721A: approve to caller');
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), 'ERC721A: mint to the zero address');
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), 'ERC721A: token already minted');
require(quantity > 0, 'ERC721A: quantity must be greater 0');
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved');
require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner');
require(to != address(0), 'ERC721A: transfer to the zero address');
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
}
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721A: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File contracts/test.sol
contract Kevinmon is ERC721A, Ownable {
string public baseURI = "";
string public contractURI = "";
string public constant baseExtension = ".json";
address public constant proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
uint256 public constant MAX_PER_TX = 10;
uint256 public constant MAX_SUPPLY = 6666;
uint256 public constant price = 0.0069 ether;
bool public paused = true;
constructor() ERC721A("Kevinmon", "KEVIN") {}
/**
* @notice Mint a Kevinmon for 0.0069 each (Max 10 per transaction - 0.069)
*
* @dev Mints Kevinmon NFT
*
* @param _amount The amount of Kevinmons to mint
*
*/
function mint(uint256 _amount) external payable {
address _caller = _msgSender();
require(!paused, "Paused");
require(MAX_SUPPLY >= totalSupply() + _amount, "Exceeds max supply");
require(_amount > 0, "No 0 mints");
require(MAX_PER_TX >= _amount , "Excess max per paid tx");
require(_amount * price == msg.value, "Invalid funds provided");
_safeMint(_caller, _amount);
}
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
(bool success, ) = _msgSender().call{value: balance}("");
require(success, "Failed to send");
}
function setupOS() external onlyOwner {
_safeMint(_msgSender(), 1);
}
function pause(bool _state) external onlyOwner {
paused = _state;
}
function setBaseURI(string memory baseURI_) external onlyOwner {
baseURI = baseURI_;
}
function setContractURI(string memory _contractURI) external onlyOwner {
contractURI = _contractURI;
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "Token does not exist.");
return bytes(baseURI).length > 0 ? string(
abi.encodePacked(
baseURI,
Strings.toString(_tokenId),
baseExtension
)
) : "";
}
}
contract OwnableDelegateProxy { }
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
|
* @dev See {IERC721-transferFrom}./
|
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
| 19,430 |
[
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
13866,
1265,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
1071,
3849,
288,
203,
3639,
389,
13866,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.17;
/// @author developers //NB!
/// @notice support@developers //NB!
/// @title Contract presale //NB!
contract AvPresale {
string public constant RELEASE = "0.2.1_AviaTest";
//config//
uint public constant PRESALE_START = 5298043; /* 22.03.2018 03:07:00 +3GMT */ //NB!
uint public constant PRESALE_END = 5303803; /* 23.03.2018 03:07:00 +3GMT */ //NB!
uint public constant WITHDRAWAL_END = 5309563; /* 24.03.2018 03:07:00 +3GMT */ //NB!
address public constant OWNER = 0x32Bac79f4B6395DEa37f0c2B68b6e26ce24a59EA; //NB!
uint public constant MIN_TOTAL_AMOUNT_GET_ETH = 1; //NB!
uint public constant MAX_TOTAL_AMOUNT_GET_ETH = 2; //NB!
//min send value 0.001 ETH (1 finney)
uint public constant MIN_GET_AMOUNT_FINNEY = 10; //NB!
string[5] private standingNames = ["BEFORE_START", "PRESALE_RUNNING", "WITHDRAWAL_RUNNING", "MONEY_BACK_RUNNING", "CLOSED" ];
enum State { BEFORE_START, PRESALE_RUNNING, WITHDRAWAL_RUNNING, MONEY_BACK_RUNNING, CLOSED }
uint public total_amount = 0;
uint public total_money_back = 0;
mapping (address => uint) public balances;
uint private constant MIN_TOTAL_AMOUNT_GET = MIN_TOTAL_AMOUNT_GET_ETH * 1 ether;
uint private constant MAX_TOTAL_AMOUNT_GET = MAX_TOTAL_AMOUNT_GET_ETH * 1 ether;
uint private constant MIN_GET_AMOUNT = MIN_GET_AMOUNT_FINNEY * 1 finney;
bool public isTerminated = false;
bool public isStopped = false;
function AvPresale () public checkSettings() { }
//methods//
//The transfer of money to the owner
function sendMoneyOwner() external
inStanding(State.WITHDRAWAL_RUNNING)
onlyOwner
noReentrancy
{
OWNER.transfer(this.balance);
}
//Money back to users
function moneyBack() external
inStanding(State.MONEY_BACK_RUNNING)
noReentrancy
{
sendMoneyBack();
}
//payments
function ()
payable
noReentrancy
public
{
State state = currentStanding();
if (state == State.PRESALE_RUNNING) {
getMoney();
} else if (state == State.MONEY_BACK_RUNNING) {
sendMoneyBack();
} else {
revert();
}
}
//Forced termination
function termination() external
inStandingBefore(State.MONEY_BACK_RUNNING)
onlyOwner
{
isTerminated = true;
}
//Forced stop with the possibility of withdrawal
function stop() external
inStanding(State.PRESALE_RUNNING)
onlyOwner
{
isStopped = true;
}
//Current status of the contract
function standing() external constant
returns (string)
{
return standingNames[ uint(currentStanding()) ];
}
//Method adding money to the user
function getMoney() private notTooSmallAmountOnly {
if (total_amount + msg.value > MAX_TOTAL_AMOUNT_GET) {
var change_to_return = total_amount + msg.value - MAX_TOTAL_AMOUNT_GET;
var acceptable_remainder = MAX_TOTAL_AMOUNT_GET - total_amount;
balances[msg.sender] += acceptable_remainder;
total_amount += acceptable_remainder;
msg.sender.transfer(change_to_return);
} else {
balances[msg.sender] += msg.value;
total_amount += msg.value;
}
}
//Method of repayment users
function sendMoneyBack() private tokenHoldersOnly {
uint amount_to_money_back = min(balances[msg.sender], this.balance - msg.value) ;
balances[msg.sender] -= amount_to_money_back;
total_money_back += amount_to_money_back;
msg.sender.transfer(amount_to_money_back + msg.value);
}
//Determining the current status of the contract
function currentStanding() private constant returns (State) {
if (isTerminated) {
return this.balance > 0
? State.MONEY_BACK_RUNNING
: State.CLOSED;
} else if (block.number < PRESALE_START) {
return State.BEFORE_START;
} else if (block.number <= PRESALE_END && total_amount < MAX_TOTAL_AMOUNT_GET && !isStopped) {
return State.PRESALE_RUNNING;
} else if (this.balance == 0) {
return State.CLOSED;
} else if (block.number <= WITHDRAWAL_END && total_amount >= MIN_TOTAL_AMOUNT_GET) {
return State.WITHDRAWAL_RUNNING;
} else {
return State.MONEY_BACK_RUNNING;
}
}
function min(uint a, uint b) pure private returns (uint) {
return a < b ? a : b;
}
//Prohibition if the condition does not match
modifier inStanding(State state) {
require(state == currentStanding());
_;
}
//Prohibition if the current state was not before
modifier inStandingBefore(State state) {
require(currentStanding() < state);
_;
}
//Works on users's command
modifier tokenHoldersOnly(){
require(balances[msg.sender] > 0);
_;
}
//Do not accept transactions with a sum less than the configuration limit
modifier notTooSmallAmountOnly(){
require(msg.value >= MIN_GET_AMOUNT);
_;
}
//Prohibition of repeated treatment
bool private lock = false;
modifier noReentrancy() {
require(!lock);
lock = true;
_;
lock = false;
}
//Prohibition if it does not match the settings
modifier checkSettings() {
if ( OWNER == 0x0
|| PRESALE_START == 0
|| PRESALE_END == 0
|| WITHDRAWAL_END ==0
|| PRESALE_START <= block.number
|| PRESALE_START >= PRESALE_END
|| PRESALE_END >= WITHDRAWAL_END
|| MIN_TOTAL_AMOUNT_GET > MAX_TOTAL_AMOUNT_GET )
revert();
_;
}
//Works on owner's command
modifier onlyOwner(){
require(msg.sender == OWNER);
_;
}
}
|
Forced stop with the possibility of withdrawal
|
function stop() external
inStanding(State.PRESALE_RUNNING)
onlyOwner
{
isStopped = true;
}
| 980,718 |
[
1,
1290,
3263,
2132,
598,
326,
25547,
434,
598,
9446,
287,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2132,
1435,
3903,
203,
565,
316,
20612,
310,
12,
1119,
18,
3670,
5233,
900,
67,
29358,
13,
203,
565,
1338,
5541,
203,
565,
288,
203,
3639,
353,
15294,
273,
638,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
contract ISncToken {
function mintTokens(address _to, uint256 _amount);
function totalSupply() constant returns (uint256 totalSupply);
}
contract SunContractIco is owned{
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
ISncToken sncTokenContract;
mapping (address => bool) presaleContributorAllowance;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool icoHasStarted;
bool minTresholdReached;
bool icoHasSucessfulyEnded;
uint256 blocksInWeek;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event ICOStarted(uint256 _blockNumber);
event ICOMinTresholdReached(uint256 _blockNumber);
event ICOEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event ICOFailed(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function SunContractIco(uint256 _startBlock, address _multisigAddress) {
blocksInWeek = 4 * 60 * 24 * 7;
startBlock = _startBlock;
endBlock = _startBlock + blocksInWeek * 4;
minEthToRaise = 5000 * 10**18;
maxEthToRaise = 100000 * 10**18;
multisigAddress = _multisigAddress;
}
//
/* User accessible methods */
//
/* Users send ETH and enter the token sale*/
function () payable {
if (msg.value == 0) throw; // Throw if the value is 0
if (icoHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the ICO has ended
if (!icoHasStarted){ // Check if this is the first ICO transaction
if (block.number >= startBlock){ // Check if the ICO should start
icoHasStarted = true; // Set that the ICO has started
ICOStarted(block.number); // Raise ICOStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value;// Add to total eth Raised
sncTokenContract.mintTokens(msg.sender, getSncTokenIssuance(block.number, msg.value));
if (!minTresholdReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
ICOMinTresholdReached(block.number); // Raise ICOMinTresholdReached event
minTresholdReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
sncTokenContract.mintTokens(msg.sender, getSncTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
icoHasSucessfulyEnded = true; // Set that ICO has successfully ended
ICOEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure*/
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if ICO has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
//
/* Only owner methods */
//
/* Adds addresses that are allowed to take part in presale */
function addPresaleContributors(address[] _presaleContributors) onlyOwner {
for (uint cnt = 0; cnt < _presaleContributors.length; cnt++){
presaleContributorAllowance[_presaleContributors[cnt]] = true;
}
}
/* Owner can return eth for multiple users in one call*/
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if ICO failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of SunContractToken */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimCoreTeamsTokens(address _to) onlyOwner{
if (!icoHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
sncTokenContract.mintTokens(_to, sncTokenContract.totalSupply() * 25 / 100);
ownerHasClaimedTokens = true;
}
/* Owner can remove allowance of designated presale contributor */
function removePresaleContributor(address _presaleContributor) onlyOwner {
presaleContributorAllowance[_presaleContributor] = false;
}
/* Set token contract where mints will be done (tokens will be issued)*/
function setTokenContract(address _sncTokenContractAddress) onlyOwner {
sncTokenContract = ISncToken(_sncTokenContractAddress);
}
/* Withdraw funds from contract */
function withdrawEth() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endIco() onlyOwner {
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
icoHasSucessfulyEnded = true;
ICOEndedSuccessfuly(block.number, totalEthRaised);
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if ICO failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
//
/* Getters */
//
function getSncTokenAddress() constant returns(address _tokenAddress){
return address(sncTokenContract);
}
function icoInProgress() constant returns (bool answer){
return icoHasStarted && !icoHasSucessfulyEnded;
}
function isAddressAllowedInPresale(address _querryAddress) constant returns (bool answer){
return presaleContributorAllowance[_querryAddress];
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
function getSncTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < blocksInWeek + startBlock) {
if (presaleContributorAllowance[msg.sender]) return _ethSent * 11600;
else return _ethSent * 11500;
}
if (_blockNumber >= blocksInWeek + startBlock && _blockNumber < blocksInWeek * 2 + startBlock) return _ethSent * 11000;
if (_blockNumber >= blocksInWeek * 2 + startBlock && _blockNumber < blocksInWeek * 3 + startBlock) return _ethSent * 10500;
if (_blockNumber >= blocksInWeek * 3 + startBlock && _blockNumber <= blocksInWeek * 4 + startBlock) return _ethSent * 10000;
}
//
/* This part is here only for testing and will not be included into final version */
//
//function killContract() onlyOwner{
// selfdestruct(msg.sender);
//}
}
|
Get next account
|
currentParticipantAddress = participantIndex[lastEthReturnIndex];
| 1,752,700 |
[
1,
967,
1024,
2236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1377,
783,
22540,
1887,
273,
14188,
1016,
63,
2722,
41,
451,
990,
1016,
15533,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT OR Apache-2.0
// Reproduced from https://etherscan.io/address/0xa7d94560dbd814af316dd96fde78b9136a977d1c#code under the terms of Apache-2.0
pragma solidity ^0.7.0;
pragma abicoder v2; // solhint-disable-line
import "@openzeppelin/contracts-upgradeable2/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable2/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable2/utils/ReentrancyGuardUpgradeable.sol";
import "./Constants.sol";
import "./NFTMarketCore.sol";
import "./NFTMarketFees.sol";
import "./SendValueWithFallbackWithdraw.sol";
import "./NFTMarketAuction.sol";
/**
* @notice Manages a reserve price auction for NFTs.
*/
abstract contract NFTMarketReserveAuction is
Constants,
NFTMarketCore,
ReentrancyGuardUpgradeable,
SendValueWithFallbackWithdraw,
NFTMarketFees,
NFTMarketAuction
{
using SafeMathUpgradeable for uint256;
struct ReserveAuction {
address nftContract;
uint256 tokenId;
address payable seller;
uint256 duration;
uint256 extensionDuration;
uint256 endTime;
address payable bidder;
uint256 amount;
}
mapping(address => mapping(uint256 => uint256))
private nftContractToTokenIdToAuctionId;
mapping(uint256 => ReserveAuction) private auctionIdToAuction;
uint256 private _minPercentIncrementInBasisPoints;
// This variable was used in an older version of the contract, left here as a gap to ensure upgrade compatibility
uint256 private ______gap_was_maxBidIncrementRequirement;
uint256 private _duration;
// These variables were used in an older version of the contract, left here as gaps to ensure upgrade compatibility
uint256 private ______gap_was_extensionDuration;
uint256 private ______gap_was_goLiveDate;
// Cap the max duration so that overflows will not occur
uint256 private constant MAX_MAX_DURATION = 1000 days;
uint256 private constant EXTENSION_DURATION = 15 minutes;
event ReserveAuctionConfigUpdated(
uint256 minPercentIncrementInBasisPoints,
uint256 maxBidIncrementRequirement,
uint256 duration,
uint256 extensionDuration,
uint256 goLiveDate
);
event ReserveAuctionCreated(
address indexed seller,
address indexed nftContract,
uint256 indexed tokenId,
uint256 duration,
uint256 extensionDuration,
uint256 reservePrice,
uint256 auctionId
);
event ReserveAuctionUpdated(
uint256 indexed auctionId,
uint256 reservePrice
);
event ReserveAuctionCanceled(uint256 indexed auctionId);
event ReserveAuctionBidPlaced(
uint256 indexed auctionId,
address indexed bidder,
uint256 amount,
uint256 endTime
);
event ReserveAuctionFinalized(
uint256 indexed auctionId,
address indexed seller,
address indexed bidder,
uint256 f8nFee,
uint256 creatorFee,
uint256 ownerRev
);
modifier onlyValidAuctionConfig(uint256 reservePrice) {
require(
reservePrice > 0,
"NFTMarketReserveAuction: Reserve price must be at least 1 wei"
);
_;
}
/**
* @notice Returns auction details for a given auctionId.
*/
function getReserveAuction(uint256 auctionId)
public
view
returns (ReserveAuction memory)
{
return auctionIdToAuction[auctionId];
}
/**
* @notice Returns the auctionId for a given NFT, or 0 if no auction is found.
* @dev If an auction is canceled, it will not be returned. However the auction may be over and pending finalization.
*/
function getReserveAuctionIdFor(address nftContract, uint256 tokenId)
public
view
returns (uint256)
{
return nftContractToTokenIdToAuctionId[nftContract][tokenId];
}
/**
* @dev Returns the seller that put a given NFT into escrow,
* or bubbles the call up to check the current owner if the NFT is not currently in escrow.
*/
function _getSellerFor(address nftContract, uint256 tokenId)
internal
view
virtual
override
returns (address)
{
address seller =
auctionIdToAuction[
nftContractToTokenIdToAuctionId[nftContract][tokenId]
]
.seller;
if (seller == address(0)) {
return super._getSellerFor(nftContract, tokenId);
}
return seller;
}
/**
* @notice Returns the current configuration for reserve auctions.
*/
function getReserveAuctionConfig()
public
view
returns (uint256 minPercentIncrementInBasisPoints, uint256 duration)
{
minPercentIncrementInBasisPoints = _minPercentIncrementInBasisPoints;
duration = _duration;
}
function _initializeNFTMarketReserveAuction() internal {
_duration = 24 hours; // A sensible default value
}
function _updateReserveAuctionConfig(
uint256 minPercentIncrementInBasisPoints,
uint256 duration
) internal {
require(
minPercentIncrementInBasisPoints <= BASIS_POINTS,
"NFTMarketReserveAuction: Min increment must be <= 100%"
);
// Cap the max duration so that overflows will not occur
require(
duration <= MAX_MAX_DURATION,
"NFTMarketReserveAuction: Duration must be <= 1000 days"
);
require(
duration >= EXTENSION_DURATION,
"NFTMarketReserveAuction: Duration must be >= EXTENSION_DURATION"
);
_minPercentIncrementInBasisPoints = minPercentIncrementInBasisPoints;
_duration = duration;
// We continue to emit unused configuration variables to simplify the subgraph integration.
emit ReserveAuctionConfigUpdated(
minPercentIncrementInBasisPoints,
0,
duration,
EXTENSION_DURATION,
0
);
}
/**
* @notice Creates an auction for the given NFT.
* The NFT is held in escrow until the auction is finalized or canceled.
*/
function createReserveAuction(
address nftContract,
uint256 tokenId,
uint256 reservePrice
) public onlyValidAuctionConfig(reservePrice) nonReentrant {
// If an auction is already in progress then the NFT would be in escrow and the modifier would have failed
uint256 auctionId = _getNextAndIncrementAuctionId();
nftContractToTokenIdToAuctionId[nftContract][tokenId] = auctionId;
auctionIdToAuction[auctionId] = ReserveAuction(
nftContract,
tokenId,
msg.sender,
_duration,
EXTENSION_DURATION,
0, // endTime is only known once the reserve price is met
address(0), // bidder is only known once a bid has been placed
reservePrice
);
IERC721Upgradeable(nftContract).transferFrom(
msg.sender,
address(this),
tokenId
);
emit ReserveAuctionCreated(
msg.sender,
nftContract,
tokenId,
_duration,
EXTENSION_DURATION,
reservePrice,
auctionId
);
}
/**
* @notice If an auction has been created but has not yet received bids, the configuration
* such as the reservePrice may be changed by the seller.
*/
function updateReserveAuction(uint256 auctionId, uint256 reservePrice)
public
onlyValidAuctionConfig(reservePrice)
{
ReserveAuction storage auction = auctionIdToAuction[auctionId];
require(
auction.seller == msg.sender,
"NFTMarketReserveAuction: Not your auction"
);
require(
auction.endTime == 0,
"NFTMarketReserveAuction: Auction in progress"
);
auction.amount = reservePrice;
emit ReserveAuctionUpdated(auctionId, reservePrice);
}
/**
* @notice If an auction has been created but has not yet received bids, it may be canceled by the seller.
* The NFT is returned to the seller from escrow.
*/
function cancelReserveAuction(uint256 auctionId) public nonReentrant {
ReserveAuction memory auction = auctionIdToAuction[auctionId];
require(
auction.seller == msg.sender,
"NFTMarketReserveAuction: Not your auction"
);
require(
auction.endTime == 0,
"NFTMarketReserveAuction: Auction in progress"
);
delete nftContractToTokenIdToAuctionId[auction.nftContract][
auction.tokenId
];
delete auctionIdToAuction[auctionId];
IERC721Upgradeable(auction.nftContract).transferFrom(
address(this),
auction.seller,
auction.tokenId
);
emit ReserveAuctionCanceled(auctionId);
}
/**
* @notice A bidder may place a bid which is at least the value defined by `getMinBidAmount`.
* If this is the first bid on the auction, the countdown will begin.
* If there is already an outstanding bid, the previous bidder will be refunded at this time
* and if the bid is placed in the final moments of the auction, the countdown may be extended.
*/
function placeBid(uint256 auctionId) public payable nonReentrant {
ReserveAuction storage auction = auctionIdToAuction[auctionId];
require(
auction.amount != 0,
"NFTMarketReserveAuction: Auction not found"
);
if (auction.endTime == 0) {
// If this is the first bid, ensure it's >= the reserve price
require(
auction.amount <= msg.value,
"NFTMarketReserveAuction: Bid must be at least the reserve price"
);
} else {
// If this bid outbids another, confirm that the bid is at least x% greater than the last
require(
auction.endTime >= block.timestamp,
"NFTMarketReserveAuction: Auction is over"
);
require(
auction.bidder != msg.sender,
"NFTMarketReserveAuction: You already have an outstanding bid"
);
uint256 minAmount =
_getMinBidAmountForReserveAuction(auction.amount);
require(
msg.value >= minAmount,
"NFTMarketReserveAuction: Bid amount too low"
);
}
if (auction.endTime == 0) {
auction.amount = msg.value;
auction.bidder = msg.sender;
// On the first bid, the endTime is now + duration
auction.endTime = block.timestamp + auction.duration;
} else {
// Cache and update bidder state before a possible reentrancy (via the value transfer)
uint256 originalAmount = auction.amount;
address payable originalBidder = auction.bidder;
auction.amount = msg.value;
auction.bidder = msg.sender;
// When a bid outbids another, check to see if a time extension should apply.
if (auction.endTime - block.timestamp < auction.extensionDuration) {
auction.endTime = block.timestamp + auction.extensionDuration;
}
// Refund the previous bidder
_sendValueWithFallbackWithdraw(originalBidder, originalAmount);
}
emit ReserveAuctionBidPlaced(
auctionId,
msg.sender,
msg.value,
auction.endTime
);
}
/**
* @notice Once the countdown has expired for an auction, anyone can settle the auction.
* This will send the NFT to the highest bidder and distribute funds.
*/
function finalizeReserveAuction(uint256 auctionId) public nonReentrant {
ReserveAuction memory auction = auctionIdToAuction[auctionId];
require(
auction.endTime > 0,
"NFTMarketReserveAuction: Auction has not started"
);
require(
auction.endTime < block.timestamp,
"NFTMarketReserveAuction: Auction still in progress"
);
delete nftContractToTokenIdToAuctionId[auction.nftContract][
auction.tokenId
];
delete auctionIdToAuction[auctionId];
IERC721Upgradeable(auction.nftContract).transferFrom(
address(this),
auction.bidder,
auction.tokenId
);
(uint256 f8nFee, uint256 creatorFee, uint256 ownerRev) =
_distributeFunds(
auction.nftContract,
auction.tokenId,
auction.seller,
auction.amount
);
emit ReserveAuctionFinalized(
auctionId,
auction.seller,
auction.bidder,
f8nFee,
creatorFee,
ownerRev
);
}
/**
* @notice Returns the minimum amount a bidder must spend to participate in an auction.
*/
function getMinBidAmount(uint256 auctionId) public view returns (uint256) {
ReserveAuction storage auction = auctionIdToAuction[auctionId];
if (auction.endTime == 0) {
return auction.amount;
}
return _getMinBidAmountForReserveAuction(auction.amount);
}
/**
* @dev Determines the minimum bid amount when outbidding another user.
*/
function _getMinBidAmountForReserveAuction(uint256 currentBidAmount)
private
view
returns (uint256)
{
uint256 minIncrement =
currentBidAmount.mul(_minPercentIncrementInBasisPoints) /
BASIS_POINTS;
if (minIncrement == 0) {
// The next bid must be at least 1 wei greater than the current.
return currentBidAmount.add(1);
}
return minIncrement.add(currentBidAmount);
}
uint256[1000] private ______gap;
}
|
* @notice Returns the minimum amount a bidder must spend to participate in an auction./
|
function getMinBidAmount(uint256 auctionId) public view returns (uint256) {
ReserveAuction storage auction = auctionIdToAuction[auctionId];
if (auction.endTime == 0) {
return auction.amount;
}
return _getMinBidAmountForReserveAuction(auction.amount);
}
| 7,302,506 |
[
1,
1356,
326,
5224,
3844,
279,
9949,
765,
1297,
17571,
358,
30891,
340,
316,
392,
279,
4062,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
9555,
17763,
6275,
12,
11890,
5034,
279,
4062,
548,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
1124,
6527,
37,
4062,
2502,
279,
4062,
273,
279,
4062,
28803,
37,
4062,
63,
69,
4062,
548,
15533,
203,
3639,
309,
261,
69,
4062,
18,
409,
950,
422,
374,
13,
288,
203,
5411,
327,
279,
4062,
18,
8949,
31,
203,
3639,
289,
203,
3639,
327,
389,
588,
2930,
17763,
6275,
1290,
607,
6527,
37,
4062,
12,
69,
4062,
18,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/IStrategy.sol";
import "../interfaces/IVault.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
abstract contract ReaperBaseStrategyv1_1 is
IStrategy,
UUPSUpgradeable,
AccessControlEnumerableUpgradeable,
PausableUpgradeable
{
uint256 public constant PERCENT_DIVISOR = 10_000;
uint256 public constant ONE_YEAR = 365 days;
uint256 public constant UPGRADE_TIMELOCK = 480 hours; // minimum 48 hours for RF
struct Harvest {
uint256 timestamp;
uint256 vaultSharePrice;
}
Harvest[] public harvestLog;
uint256 public harvestLogCadence;
uint256 public lastHarvestTimestamp;
uint256 public upgradeProposalTime;
/**
* Reaper Roles
*/
bytes32 public constant STRATEGIST = keccak256("STRATEGIST");
bytes32 public constant STRATEGIST_MULTISIG =
keccak256("STRATEGIST_MULTISIG");
/**
* @dev Reaper contracts:
* {treasury} - Address of the Reaper treasury
* {vault} - Address of the vault that controls the strategy's funds.
* {strategistRemitter} - Address where strategist fee is remitted to.
*/
address public treasury;
address public vault;
address public strategistRemitter;
/**
* Fee related constants:
* {MAX_FEE} - Maximum fee allowed by the strategy. Hard-capped at 10%.
* {STRATEGIST_MAX_FEE} - Maximum strategist fee allowed by the strategy (as % of treasury fee).
* Hard-capped at 50%
* {MAX_SECURITY_FEE} - Maximum security fee charged on withdrawal to prevent
* flash deposit/harvest attacks.
*/
uint256 public constant MAX_FEE = 1000;
uint256 public constant STRATEGIST_MAX_FEE = 5000;
uint256 public constant MAX_SECURITY_FEE = 10;
/**
* @dev Distribution of fees earned, expressed as % of the profit from each harvest.
* {totalFee} - divided by 10,000 to determine the % fee. Set to 4.5% by default and
* lowered as necessary to provide users with the most competitive APY.
*
* {callFee} - Percent of the totalFee reserved for the harvester (1000 = 10% of total fee: 0.45% by default)
* {treasuryFee} - Percent of the totalFee taken by maintainers of the software (9000 = 90% of total fee: 4.05% by default)
* {strategistFee} - Percent of the treasuryFee taken by strategist (2500 = 25% of treasury fee: 1.0125% by default)
*
* {securityFee} - Fee taxed when a user withdraws funds. Taken to prevent flash deposit/harvest attacks.
* These funds are redistributed to stakers in the pool.
*/
uint256 public totalFee;
uint256 public callFee;
uint256 public treasuryFee;
uint256 public strategistFee;
uint256 public securityFee;
/**
* {TotalFeeUpdated} Event that is fired each time the total fee is updated.
* {FeesUpdated} Event that is fired each time callFee+treasuryFee+strategistFee are updated.
* {StratHarvest} Event that is fired each time the strategy gets harvested.
* {StrategistRemitterUpdated} Event that is fired each time the strategistRemitter address is updated.
*/
event TotalFeeUpdated(uint256 newFee);
event FeesUpdated(
uint256 newCallFee,
uint256 newTreasuryFee,
uint256 newStrategistFee
);
event StratHarvest(address indexed harvester);
event StrategistRemitterUpdated(address newStrategistRemitter);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function __ReaperBaseStrategy_init(
address _vault,
address[] memory _feeRemitters,
address[] memory _strategists
) internal onlyInitializing {
__UUPSUpgradeable_init();
__AccessControlEnumerable_init();
__Pausable_init_unchained();
harvestLogCadence = 1 minutes;
totalFee = 450;
callFee = 1000;
treasuryFee = 9000;
strategistFee = 2500;
securityFee = 10;
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
clearUpgradeCooldown();
vault = _vault;
treasury = _feeRemitters[0];
strategistRemitter = _feeRemitters[1];
for (uint256 i = 0; i < _strategists.length; i++) {
_grantRole(STRATEGIST, _strategists[i]);
}
harvestLog.push(
Harvest({
timestamp: block.timestamp,
vaultSharePrice: IVault(_vault).getPricePerFullShare()
})
);
}
/**
* @dev Function that puts the funds to work.
* It gets called whenever someone deposits in the strategy's vault contract.
* Deposits go through only when the strategy is not paused.
*/
function deposit() public override whenNotPaused {
_deposit();
}
/**
* @dev Withdraws funds and sends them back to the vault. Can only
* be called by the vault. _amount must be valid and security fee
* is deducted up-front.
*/
function withdraw(uint256 _amount) external override {
require(msg.sender == vault, "!vault");
require(_amount != 0, "invalid amount");
require(_amount <= balanceOf(), "invalid amount");
uint256 withdrawFee = (_amount * securityFee) / PERCENT_DIVISOR;
_amount -= withdrawFee;
_withdraw(_amount);
}
/**
* @dev harvest() function that takes care of logging. Subcontracts should
* override _harvestCore() and implement their specific logic in it.
*/
function harvest() external override whenNotPaused {
_harvestCore();
if (
block.timestamp >=
harvestLog[harvestLog.length - 1].timestamp + harvestLogCadence
) {
harvestLog.push(
Harvest({
timestamp: block.timestamp,
vaultSharePrice: IVault(vault).getPricePerFullShare()
})
);
}
lastHarvestTimestamp = block.timestamp;
emit StratHarvest(msg.sender);
}
function harvestLogLength() external view returns (uint256) {
return harvestLog.length;
}
/**
* @dev Traverses the harvest log backwards _n items,
* and returns the average APR calculated across all the included
* log entries. APR is multiplied by PERCENT_DIVISOR to retain precision.
*/
function averageAPRAcrossLastNHarvests(int256 _n)
external
view
returns (int256)
{
require(harvestLog.length >= 2, "need at least 2 log entries");
int256 runningAPRSum;
int256 numLogsProcessed;
for (
uint256 i = harvestLog.length - 1;
i > 0 && numLogsProcessed < _n;
i--
) {
runningAPRSum += calculateAPRUsingLogs(i - 1, i);
numLogsProcessed++;
}
return runningAPRSum / numLogsProcessed;
}
/**
* @dev Only strategist or owner can edit the log cadence.
*/
function updateHarvestLogCadence(uint256 _newCadenceInSeconds) external {
_onlyStrategistOrOwner();
harvestLogCadence = _newCadenceInSeconds;
}
/**
* @dev Function to calculate the total {want} held by the strat.
* It takes into account both the funds in hand, plus the funds in external contracts.
*/
function balanceOf() public view virtual override returns (uint256);
/**
* @dev Function to retire the strategy. Claims all rewards and withdraws
* all principal from external contracts, and sends everything back to
* the vault. Can only be called by strategist or owner.
*
* Note: this is not an emergency withdraw function. For that, see panic().
*/
function retireStrat() external override {
_onlyStrategistOrOwner();
_retireStrat();
}
/**
* @dev Pauses deposits. Withdraws all funds leaving rewards behind
*/
function panic() external override {
_onlyStrategistOrOwner();
_reclaimWant();
pause();
}
/**
* @dev Pauses the strat. Deposits become disabled but users can still
* withdraw. Removes allowances of external contracts.
*/
function pause() public override {
_onlyStrategistOrOwner();
_pause();
_removeAllowances();
}
/**
* @dev Unpauses the strat. Opens up deposits again and invokes deposit().
* Reinstates allowances for external contracts.
*/
function unpause() external override {
_onlyStrategistOrOwner();
_unpause();
_giveAllowances();
deposit();
}
/**
* @dev updates the total fee, capped at 5%; only owner.
*/
function updateTotalFee(uint256 _totalFee)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_totalFee <= MAX_FEE, "Fee Too High");
totalFee = _totalFee;
emit TotalFeeUpdated(totalFee);
}
/**
* @dev updates the call fee, treasury fee, and strategist fee
* call Fee + treasury Fee must add up to PERCENT_DIVISOR
*
* strategist fee is expressed as % of the treasury fee and
* must be no more than STRATEGIST_MAX_FEE
*
* only owner
*/
function updateFees(
uint256 _callFee,
uint256 _treasuryFee,
uint256 _strategistFee
) external onlyRole(DEFAULT_ADMIN_ROLE) returns (bool) {
require(
_callFee + _treasuryFee == PERCENT_DIVISOR,
"sum != PERCENT_DIVISOR"
);
require(
_strategistFee <= STRATEGIST_MAX_FEE,
"strategist fee > STRATEGIST_MAX_FEE"
);
callFee = _callFee;
treasuryFee = _treasuryFee;
strategistFee = _strategistFee;
emit FeesUpdated(callFee, treasuryFee, strategistFee);
return true;
}
function updateSecurityFee(uint256 _securityFee)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_securityFee <= MAX_SECURITY_FEE, "fee to high!");
securityFee = _securityFee;
}
/**
* @dev only owner can update treasury address.
*/
function updateTreasury(address newTreasury)
external
onlyRole(DEFAULT_ADMIN_ROLE)
returns (bool)
{
treasury = newTreasury;
return true;
}
/**
* @dev Updates the current strategistRemitter.
* If there is only one strategist this function may be called by
* that strategist. However if there are multiple strategists
* this function may only be called by the STRATEGIST_MULTISIG role.
*/
function updateStrategistRemitter(address _newStrategistRemitter) external {
if (getRoleMemberCount(STRATEGIST) == 1) {
_checkRole(STRATEGIST, msg.sender);
} else {
_checkRole(STRATEGIST_MULTISIG, msg.sender);
}
require(_newStrategistRemitter != address(0), "!0");
strategistRemitter = _newStrategistRemitter;
emit StrategistRemitterUpdated(_newStrategistRemitter);
}
/**
* @dev Only allow access to strategist or owner
*/
function _onlyStrategistOrOwner() internal view {
require(
hasRole(STRATEGIST, msg.sender) ||
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"Not authorized"
);
}
/**
* @dev Project an APR using the vault share price change between harvests at the provided indices.
*/
function calculateAPRUsingLogs(uint256 _startIndex, uint256 _endIndex)
public
view
returns (int256)
{
Harvest storage start = harvestLog[_startIndex];
Harvest storage end = harvestLog[_endIndex];
bool increasing = true;
if (end.vaultSharePrice < start.vaultSharePrice) {
increasing = false;
}
uint256 unsignedSharePriceChange;
if (increasing) {
unsignedSharePriceChange =
end.vaultSharePrice -
start.vaultSharePrice;
} else {
unsignedSharePriceChange =
start.vaultSharePrice -
end.vaultSharePrice;
}
uint256 unsignedPercentageChange = (unsignedSharePriceChange * 1e18) /
start.vaultSharePrice;
uint256 timeDifference = end.timestamp - start.timestamp;
uint256 yearlyUnsignedPercentageChange = (unsignedPercentageChange *
ONE_YEAR) / timeDifference;
yearlyUnsignedPercentageChange /= 1e14; // restore basis points precision
if (increasing) {
return int256(yearlyUnsignedPercentageChange);
}
return -int256(yearlyUnsignedPercentageChange);
}
/**
* @dev DEFAULT_ADMIN_ROLE must call this function prior to upgrading the implementation
* and wait UPGRADE_TIMELOCK seconds before executing the upgrade.
*/
function initiateUpgradeCooldown() external onlyRole(DEFAULT_ADMIN_ROLE) {
upgradeProposalTime = block.timestamp;
}
/**
* @dev This function is called:
* - in initialize()
* - as part of a successful upgrade
* - manually by DEFAULT_ADMIN_ROLE to clear the upgrade cooldown.
*/
function clearUpgradeCooldown() public onlyRole(DEFAULT_ADMIN_ROLE) {
upgradeProposalTime = block.timestamp + (ONE_YEAR * 100);
}
/**
* @dev This function must be overriden simply for access control purposes.
* Only DEFAULT_ADMIN_ROLE can upgrade the implementation once the timelock
* has passed.
*/
function _authorizeUpgrade(address)
internal
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
upgradeProposalTime + UPGRADE_TIMELOCK < block.timestamp,
"cooldown not initiated or still active"
);
clearUpgradeCooldown();
}
/**
* @dev subclasses should add their custom deposit logic in this function.
*/
function _deposit() internal virtual;
/**
* @dev subclasses should add their custom withdraw logic in this function.
* Note that security fee has already been deducted, so it shouldn't be deducted
* again within this function.
*/
function _withdraw(uint256 _amount) internal virtual;
/**
* @dev subclasses should add their custom harvesting logic in this function
* including charging any fees.
*/
function _harvestCore() internal virtual;
/**
* @dev subclasses should add their custom logic to retire the strategy in this function.
* Note that we expect all funds (including any pending rewards) to be sent back to
* the vault in this function.
*/
function _retireStrat() internal virtual;
/**
* @dev subclasses should add their custom logic to withdraw the principal from
* any external contracts in this function. Note that we don't care about rewards,
* we just want to reclaim our principal as much as possible, and as quickly as possible.
* So keep this function lean. Principal should be left in the strategy and not sent to
* the vault.
*/
function _reclaimWant() internal virtual;
/**
* @dev subclasses should add their custom logic to give allowances to external contracts
* so the strategy can successfully interface with them.
*/
function _giveAllowances() internal virtual;
/**
* @dev subclasses should add their custom logic to remove all allowances for any external
* contracts.
*/
function _removeAllowances() internal virtual;
}
|
* @dev updates the total fee, capped at 5%; only owner./
|
function updateTotalFee(uint256 _totalFee)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_totalFee <= MAX_FEE, "Fee Too High");
totalFee = _totalFee;
emit TotalFeeUpdated(totalFee);
}
| 1,799,814 |
[
1,
14703,
326,
2078,
14036,
16,
3523,
1845,
622,
1381,
9,
31,
1338,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1089,
5269,
14667,
12,
11890,
5034,
389,
4963,
14667,
13,
203,
3639,
3903,
203,
3639,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
203,
565,
288,
203,
3639,
2583,
24899,
4963,
14667,
1648,
4552,
67,
8090,
41,
16,
315,
14667,
15869,
15207,
8863,
203,
3639,
2078,
14667,
273,
389,
4963,
14667,
31,
203,
3639,
3626,
10710,
14667,
7381,
12,
4963,
14667,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.4;
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
//name this contract whatever you'd like
contract USKISHU is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function USKISHU(
) {
balances[msg.sender] = 100000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 100000000; // Update total supply (100000 for example)
name = "USKISHU"; // Set the name for display purposes
decimals = 7; // Amount of decimals for display purposes
symbol = "USKISHU"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
}
|
Set the symbol for display purposes
|
symbol = "USKISHU";
| 1,216,992 |
[
1,
694,
326,
3273,
364,
2562,
13694,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
3273,
273,
315,
3378,
47,
20424,
57,
14432,
27573,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
/**
* @title Screen Selling Platform
* @notice This contract abstracts the screen selling
* marketplace and provides functions to perform
* transactions
* @author Team Block-Daggers
*
*/
contract Auction {
/**
* This enum defines status of screen (item) present in the
* marketplace
*
*/
enum ITEM_STATUS {
LOCKED, /// Item is being processed, hence is not listed in marketplace
OPEN, /// Item is being sold at marketplace
BUYING, /// Buyer has paid for the item, but hasn't received it yet
BOUGHT /// Buyer received the item
}
enum AUCTION_STATUS {
ONGOING,
VERIFICATION,
REVEALED
}
enum AUCTION_TYPE {
FIRST_PRICE,
SECOND_PRICE,
AVG_PRICE,
FIXED
}
/**
* This struct defines the blueprint of each screen (item)
* present in the marketplace
*
*/
struct Listing {
address payable seller;
ITEM_STATUS status;
string item_name;
string item_desc;
string secret_string;
uint256 asking_price;
uint256 final_price;
mapping(bytes32 => bool) hashedBids;
uint256 biddersCount;
mapping(address => bool) bidders;
mapping(address => bool) isVerified;
Bidder[] verifiedBids;
Bidder bidWinner;
AUCTION_STATUS auctionStatus;
AUCTION_TYPE auctionType;
}
struct Bidder {
address payable buyer;
uint256 price;
string public_key;
}
uint256 private itemsCount;
mapping(uint256 => Listing) private itemsList;
/**
* Initialising smart contract to the scenario when no item
* is present in the marketplace
*
*/
constructor() public {
itemsCount = 0;
}
/**
* Allows only seller of item to access the function
*
* @param index unique id of item
*/
modifier onlyItemSeller(uint256 index) {
require(index <= itemsCount && index > 0, "Item not present in list");
require(
msg.sender == itemsList[index].seller,
"You are not seller of item"
);
_;
}
/**
* Allows only buyer or seller to access the function
*
* @param index unique id of item
*/
modifier onlyItemOwnerOrSeller(uint256 index) {
require(index <= itemsCount && index > 0, "Item not present in list");
require(
msg.sender == itemsList[index].seller ||
(msg.sender == itemsList[index].bidWinner.buyer &&
itemsList[index].status == ITEM_STATUS.BOUGHT),
"You are not owner or seller of item"
);
_;
}
/**
* Checks empty string
*
* @param str string
*/
modifier nonEmpty(string memory str){
require(bytes(str).length > 0, "String should be non empty");
_;
}
/**
* Checks empty array
*
* @param item_id id of the item
*/
modifier nonEmptyBidders(uint256 item_id){
require(true, "No bidders found");
_;
}
/**
* Adds an item in the marketplace
* Used by: Seller
*
* @param _item_name name of item
* @param _item_desc description of item
* @param _asking_price asking price of item
*/
function addItem(
string memory _item_name,
string memory _item_desc,
uint256 _asking_price,
uint256 _auction_type
)
public
nonEmpty(_item_name)
nonEmpty(_item_desc)
returns (uint256) {
itemsCount++;
itemsList[itemsCount].status = ITEM_STATUS.LOCKED;
itemsList[itemsCount].item_desc = _item_desc;
itemsList[itemsCount].seller = msg.sender;
itemsList[itemsCount].item_name = _item_name;
itemsList[itemsCount].asking_price = _asking_price;
itemsList[itemsCount].status = ITEM_STATUS.OPEN;
itemsList[itemsCount].auctionStatus = AUCTION_STATUS.ONGOING;
if (_auction_type == 0) {
itemsList[itemsCount].auctionType = AUCTION_TYPE.FIRST_PRICE;
} else if (_auction_type == 1) {
itemsList[itemsCount].auctionType = AUCTION_TYPE.SECOND_PRICE;
} else if (_auction_type == 2) {
itemsList[itemsCount].auctionType = AUCTION_TYPE.AVG_PRICE;
} else {
itemsList[itemsCount].auctionStatus = AUCTION_STATUS.VERIFICATION;
itemsList[itemsCount].auctionType = AUCTION_TYPE.FIXED;
}
return itemsCount;
}
function bidItem(uint256 item_id, bytes32 hashString) public {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.ONGOING,
"Auction not ongoing"
);
require(
itemsList[item_id].bidders[msg.sender] == false,
"Already bidded"
);
itemsList[item_id].hashedBids[hashString] = true;
itemsList[item_id].biddersCount += 1;
itemsList[item_id].bidders[msg.sender] = true;
}
function closeBid(uint256 item_id) public nonEmptyBidders(item_id) {
require(
msg.sender == itemsList[item_id].seller || msg.sender == address(this),
'Access denied'
);
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.ONGOING,
"Auction not ongoing"
);
require(
itemsList[item_id].biddersCount != 0,
"No Bidder"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].biddersCount >= 2,
"Atleast two people should bid for vickery auction"
);
}
itemsList[item_id].auctionStatus = AUCTION_STATUS.VERIFICATION;
}
function verifyBid(
uint256 item_id,
string memory password,
string memory public_key
) public payable {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.FIXED){
if(msg.value == itemsList[item_id].asking_price){
itemsList[item_id].final_price = msg.value;
itemsList[item_id].bidWinner = Bidder(msg.sender, msg.value, public_key);
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED; // everything is done
}
else{
revert("Invalid Price");
}
}
else{
bytes32 hashValue = keccak256(
abi.encodePacked(password, uintToStr(msg.value))
);
if(itemsList[item_id].hashedBids[hashValue] != true){
revert("Invalid details");
}
itemsList[item_id].verifiedBids.push(
Bidder(msg.sender, msg.value, public_key)
);
itemsList[item_id].isVerified[msg.sender] = true;
}
}
function abs(uint256 a, uint256 b) private pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return b - a;
}
}
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
} else if (currentBidPrice > secondMaxBid) {
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
} else if(itemsList[item_id].auctionType == AUCTION_TYPE.AVG_PRICE) {
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
} else{
// normal purchase, do nothing
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
/**
* Gets public key of the buyer from the item being bought
* Used by: Seller
*
* @param item_id unique id of item
*/
function getKey(uint256 item_id)
public
view
onlyItemSeller(item_id)
returns (string memory)
{
require(
itemsList[item_id].status == ITEM_STATUS.BUYING,
"KEY NOT AVAILABLE"
);
return itemsList[item_id].bidWinner.public_key;
}
/**
* Assigns encrypted password to the item which can be only decrypted
* by the buyer
* Thus, it simulates delivery of the screen (item) from the seller
* Item is marked as BOUGHT
* Used by: Seller
*
* @param item_id unique id of item
* @param secret_string Encrypted password of the screen (i.e.
* item) along with the public key of the buyer
*/
function giveAccess(uint256 item_id, string memory secret_string)
public
payable
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.BUYING,
"Item not purchased yet"
);
itemsList[item_id].secret_string = secret_string;
itemsList[item_id].status = ITEM_STATUS.BOUGHT;
itemsList[item_id].seller.transfer(itemsList[item_id].final_price);
// return pending money of bid winner like in case of auction type 2
returnWinnerPendingMoney(item_id);
}
function returnWinnerPendingMoney(uint256 item_id) private {
uint256 pendingMoney = itemsList[item_id].bidWinner.price -
itemsList[item_id].final_price;
itemsList[item_id].bidWinner.buyer.transfer(pendingMoney);
}
function returnNonWinnerMoney(uint256 item_id) private {
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
if (
itemsList[item_id].verifiedBids[i].buyer ==
itemsList[item_id].bidWinner.buyer
) {
continue;
}
uint256 returnPrice = itemsList[item_id].verifiedBids[i].price;
itemsList[item_id].verifiedBids[i].buyer.transfer(returnPrice);
}
}
/**
* @dev View pending balance in escrow account
* Used by: Developer
*
*/
function getBalance() public view returns (uint256) {
return address(this).balance;
}
/**
* Returns encrypted password of the delivered item
* Used by: Buyer, (optional) Seller
*
* @param item_id unique id of item
*/
function accessItem(uint256 item_id)
public
view
onlyItemOwnerOrSeller(item_id)
returns (string memory)
{
return itemsList[item_id].secret_string;
}
/**
* Updates the name of the item listed in the marketplace
* Used by: Seller
*
* @param item_id unique id of item
* @param item_name name of item
*/
function changeName(uint256 item_id, string memory item_name)
public
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.OPEN,
"Item is already sold"
);
itemsList[item_id].status = ITEM_STATUS.LOCKED;
itemsList[item_id].item_name = item_name;
itemsList[item_id].status = ITEM_STATUS.OPEN;
}
/**
* Updates the price of the item listed in the marketplace
* Used by: seller
*
* @param item_id unique id of item
* @param price item price
*/
function changePrice(uint256 item_id, uint256 price)
public
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.OPEN,
"Item is already sold"
);
itemsList[item_id].status = ITEM_STATUS.LOCKED;
itemsList[item_id].asking_price = price;
itemsList[item_id].status = ITEM_STATUS.OPEN;
}
/**
* Converts an unsigned integer to its equivalent string
*
* @param _i number
*/
function uintToStr(uint256 _i)
private
pure
returns (string memory _uintAsString)
{
uint256 number = _i;
if (number == 0) {
return "0";
}
uint256 j = number;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (number != 0) {
bstr[k--] = bytes1(uint8(48 + (number % 10)));
number /= 10;
}
return string(bstr);
}
/**
* Converts address to string
* Source: https://ethereum.stackexchange.com/a/58341
*
* @param account address of account
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(data[i] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(data[i] & 0x0f))];
}
return string(str);
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
/**
* Returns the items present in the marketplace, which are
* ready to be sold
* Used by: public
*
*/
function viewActiveListings(bool allItems) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (allItems || itemsList[i].auctionStatus == AUCTION_STATUS.ONGOING ||
(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION && itemsList[i].auctionType == AUCTION_TYPE.FIXED)) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
function viewSellerListings(address seller_id) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (itemsList[i].seller == seller_id) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
}
|
* @title Screen Selling Platform @notice This contract abstracts the screen selling marketplace and provides functions to perform transactions @author Team Block-Daggers/
|
contract Auction {
enum ITEM_STATUS {
}
enum AUCTION_STATUS {
ONGOING,
VERIFICATION,
REVEALED
}
enum AUCTION_TYPE {
FIRST_PRICE,
SECOND_PRICE,
AVG_PRICE,
FIXED
}
struct Listing {
address payable seller;
ITEM_STATUS status;
string item_name;
string item_desc;
string secret_string;
uint256 asking_price;
uint256 final_price;
mapping(bytes32 => bool) hashedBids;
uint256 biddersCount;
mapping(address => bool) bidders;
mapping(address => bool) isVerified;
Bidder[] verifiedBids;
Bidder bidWinner;
AUCTION_STATUS auctionStatus;
AUCTION_TYPE auctionType;
}
struct Bidder {
address payable buyer;
uint256 price;
string public_key;
}
uint256 private itemsCount;
mapping(uint256 => Listing) private itemsList;
constructor() public {
itemsCount = 0;
}
modifier onlyItemSeller(uint256 index) {
require(index <= itemsCount && index > 0, "Item not present in list");
require(
msg.sender == itemsList[index].seller,
"You are not seller of item"
);
_;
}
modifier onlyItemOwnerOrSeller(uint256 index) {
require(index <= itemsCount && index > 0, "Item not present in list");
require(
msg.sender == itemsList[index].seller ||
(msg.sender == itemsList[index].bidWinner.buyer &&
itemsList[index].status == ITEM_STATUS.BOUGHT),
"You are not owner or seller of item"
);
_;
}
modifier nonEmpty(string memory str){
require(bytes(str).length > 0, "String should be non empty");
_;
}
modifier nonEmptyBidders(uint256 item_id){
require(true, "No bidders found");
_;
}
function addItem(
string memory _item_name,
string memory _item_desc,
uint256 _asking_price,
uint256 _auction_type
)
public
nonEmpty(_item_name)
nonEmpty(_item_desc)
returns (uint256) {
itemsCount++;
itemsList[itemsCount].status = ITEM_STATUS.LOCKED;
itemsList[itemsCount].item_desc = _item_desc;
itemsList[itemsCount].seller = msg.sender;
itemsList[itemsCount].item_name = _item_name;
itemsList[itemsCount].asking_price = _asking_price;
itemsList[itemsCount].status = ITEM_STATUS.OPEN;
itemsList[itemsCount].auctionStatus = AUCTION_STATUS.ONGOING;
if (_auction_type == 0) {
itemsList[itemsCount].auctionType = AUCTION_TYPE.FIRST_PRICE;
itemsList[itemsCount].auctionType = AUCTION_TYPE.SECOND_PRICE;
itemsList[itemsCount].auctionType = AUCTION_TYPE.AVG_PRICE;
itemsList[itemsCount].auctionStatus = AUCTION_STATUS.VERIFICATION;
itemsList[itemsCount].auctionType = AUCTION_TYPE.FIXED;
}
return itemsCount;
}
function addItem(
string memory _item_name,
string memory _item_desc,
uint256 _asking_price,
uint256 _auction_type
)
public
nonEmpty(_item_name)
nonEmpty(_item_desc)
returns (uint256) {
itemsCount++;
itemsList[itemsCount].status = ITEM_STATUS.LOCKED;
itemsList[itemsCount].item_desc = _item_desc;
itemsList[itemsCount].seller = msg.sender;
itemsList[itemsCount].item_name = _item_name;
itemsList[itemsCount].asking_price = _asking_price;
itemsList[itemsCount].status = ITEM_STATUS.OPEN;
itemsList[itemsCount].auctionStatus = AUCTION_STATUS.ONGOING;
if (_auction_type == 0) {
itemsList[itemsCount].auctionType = AUCTION_TYPE.FIRST_PRICE;
itemsList[itemsCount].auctionType = AUCTION_TYPE.SECOND_PRICE;
itemsList[itemsCount].auctionType = AUCTION_TYPE.AVG_PRICE;
itemsList[itemsCount].auctionStatus = AUCTION_STATUS.VERIFICATION;
itemsList[itemsCount].auctionType = AUCTION_TYPE.FIXED;
}
return itemsCount;
}
} else if (_auction_type == 1) {
} else if (_auction_type == 2) {
} else {
function bidItem(uint256 item_id, bytes32 hashString) public {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.ONGOING,
"Auction not ongoing"
);
require(
itemsList[item_id].bidders[msg.sender] == false,
"Already bidded"
);
itemsList[item_id].hashedBids[hashString] = true;
itemsList[item_id].biddersCount += 1;
itemsList[item_id].bidders[msg.sender] = true;
}
function closeBid(uint256 item_id) public nonEmptyBidders(item_id) {
require(
msg.sender == itemsList[item_id].seller || msg.sender == address(this),
'Access denied'
);
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.ONGOING,
"Auction not ongoing"
);
require(
itemsList[item_id].biddersCount != 0,
"No Bidder"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].biddersCount >= 2,
"Atleast two people should bid for vickery auction"
);
}
itemsList[item_id].auctionStatus = AUCTION_STATUS.VERIFICATION;
}
function closeBid(uint256 item_id) public nonEmptyBidders(item_id) {
require(
msg.sender == itemsList[item_id].seller || msg.sender == address(this),
'Access denied'
);
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.ONGOING,
"Auction not ongoing"
);
require(
itemsList[item_id].biddersCount != 0,
"No Bidder"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].biddersCount >= 2,
"Atleast two people should bid for vickery auction"
);
}
itemsList[item_id].auctionStatus = AUCTION_STATUS.VERIFICATION;
}
function verifyBid(
uint256 item_id,
string memory password,
string memory public_key
) public payable {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.FIXED){
if(msg.value == itemsList[item_id].asking_price){
itemsList[item_id].final_price = msg.value;
itemsList[item_id].bidWinner = Bidder(msg.sender, msg.value, public_key);
itemsList[item_id].status = ITEM_STATUS.BUYING;
}
else{
revert("Invalid Price");
}
}
else{
bytes32 hashValue = keccak256(
abi.encodePacked(password, uintToStr(msg.value))
);
if(itemsList[item_id].hashedBids[hashValue] != true){
revert("Invalid details");
}
itemsList[item_id].verifiedBids.push(
Bidder(msg.sender, msg.value, public_key)
);
itemsList[item_id].isVerified[msg.sender] = true;
}
}
function verifyBid(
uint256 item_id,
string memory password,
string memory public_key
) public payable {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.FIXED){
if(msg.value == itemsList[item_id].asking_price){
itemsList[item_id].final_price = msg.value;
itemsList[item_id].bidWinner = Bidder(msg.sender, msg.value, public_key);
itemsList[item_id].status = ITEM_STATUS.BUYING;
}
else{
revert("Invalid Price");
}
}
else{
bytes32 hashValue = keccak256(
abi.encodePacked(password, uintToStr(msg.value))
);
if(itemsList[item_id].hashedBids[hashValue] != true){
revert("Invalid details");
}
itemsList[item_id].verifiedBids.push(
Bidder(msg.sender, msg.value, public_key)
);
itemsList[item_id].isVerified[msg.sender] = true;
}
}
function verifyBid(
uint256 item_id,
string memory password,
string memory public_key
) public payable {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.FIXED){
if(msg.value == itemsList[item_id].asking_price){
itemsList[item_id].final_price = msg.value;
itemsList[item_id].bidWinner = Bidder(msg.sender, msg.value, public_key);
itemsList[item_id].status = ITEM_STATUS.BUYING;
}
else{
revert("Invalid Price");
}
}
else{
bytes32 hashValue = keccak256(
abi.encodePacked(password, uintToStr(msg.value))
);
if(itemsList[item_id].hashedBids[hashValue] != true){
revert("Invalid details");
}
itemsList[item_id].verifiedBids.push(
Bidder(msg.sender, msg.value, public_key)
);
itemsList[item_id].isVerified[msg.sender] = true;
}
}
function verifyBid(
uint256 item_id,
string memory password,
string memory public_key
) public payable {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.FIXED){
if(msg.value == itemsList[item_id].asking_price){
itemsList[item_id].final_price = msg.value;
itemsList[item_id].bidWinner = Bidder(msg.sender, msg.value, public_key);
itemsList[item_id].status = ITEM_STATUS.BUYING;
}
else{
revert("Invalid Price");
}
}
else{
bytes32 hashValue = keccak256(
abi.encodePacked(password, uintToStr(msg.value))
);
if(itemsList[item_id].hashedBids[hashValue] != true){
revert("Invalid details");
}
itemsList[item_id].verifiedBids.push(
Bidder(msg.sender, msg.value, public_key)
);
itemsList[item_id].isVerified[msg.sender] = true;
}
}
function verifyBid(
uint256 item_id,
string memory password,
string memory public_key
) public payable {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.FIXED){
if(msg.value == itemsList[item_id].asking_price){
itemsList[item_id].final_price = msg.value;
itemsList[item_id].bidWinner = Bidder(msg.sender, msg.value, public_key);
itemsList[item_id].status = ITEM_STATUS.BUYING;
}
else{
revert("Invalid Price");
}
}
else{
bytes32 hashValue = keccak256(
abi.encodePacked(password, uintToStr(msg.value))
);
if(itemsList[item_id].hashedBids[hashValue] != true){
revert("Invalid details");
}
itemsList[item_id].verifiedBids.push(
Bidder(msg.sender, msg.value, public_key)
);
itemsList[item_id].isVerified[msg.sender] = true;
}
}
function verifyBid(
uint256 item_id,
string memory password,
string memory public_key
) public payable {
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.FIXED){
if(msg.value == itemsList[item_id].asking_price){
itemsList[item_id].final_price = msg.value;
itemsList[item_id].bidWinner = Bidder(msg.sender, msg.value, public_key);
itemsList[item_id].status = ITEM_STATUS.BUYING;
}
else{
revert("Invalid Price");
}
}
else{
bytes32 hashValue = keccak256(
abi.encodePacked(password, uintToStr(msg.value))
);
if(itemsList[item_id].hashedBids[hashValue] != true){
revert("Invalid details");
}
itemsList[item_id].verifiedBids.push(
Bidder(msg.sender, msg.value, public_key)
);
itemsList[item_id].isVerified[msg.sender] = true;
}
}
function abs(uint256 a, uint256 b) private pure returns (uint256) {
if (a >= b) {
return a - b;
return b - a;
}
}
function abs(uint256 a, uint256 b) private pure returns (uint256) {
if (a >= b) {
return a - b;
return b - a;
}
}
} else {
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
} else if (currentBidPrice > secondMaxBid) {
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
} else if(itemsList[item_id].auctionType == AUCTION_TYPE.AVG_PRICE) {
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
function revealBid(uint256 item_id) public payable onlyItemSeller(item_id){
require(
item_id <= itemsCount && item_id > 0,
"Item not present in list"
);
require(
itemsList[item_id].auctionStatus == AUCTION_STATUS.VERIFICATION,
"Bid verification not in progress"
);
require(
itemsList[item_id].verifiedBids.length > 0,
"No one verified bid"
);
if(itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE) {
require(
itemsList[item_id].verifiedBids.length >= 2,
"Atleast two people should verify for vickery auction"
);
}
uint256 maxBid = 0;
Bidder memory maxBidder;
uint256 secondMaxBid = 0;
uint256 totalBid = 0;
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
uint256 currentBidPrice = itemsList[item_id].verifiedBids[i].price;
totalBid += currentBidPrice;
if (currentBidPrice > maxBid) {
secondMaxBid = maxBid;
maxBid = currentBidPrice;
maxBidder = itemsList[item_id].verifiedBids[i];
secondMaxBid = currentBidPrice;
}
}
if (itemsList[item_id].auctionType == AUCTION_TYPE.FIRST_PRICE) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = maxBid;
} else if (
itemsList[item_id].auctionType == AUCTION_TYPE.SECOND_PRICE
) {
itemsList[item_id].bidWinner = maxBidder;
itemsList[item_id].final_price = secondMaxBid;
uint256 minDiff = uint256(-1);
Bidder memory avgBidder;
uint256 n = itemsList[item_id].verifiedBids.length;
for (uint256 i = 0; i < n; i++) {
uint256 currentBidPrice = itemsList[item_id]
.verifiedBids[i]
.price * n;
if (abs(currentBidPrice, totalBid) < minDiff) {
avgBidder = itemsList[item_id].verifiedBids[i];
minDiff = abs(currentBidPrice, totalBid);
}
itemsList[item_id].bidWinner = avgBidder;
itemsList[item_id].final_price = avgBidder.price;
}
itemsList[item_id].status = ITEM_STATUS.BUYING;
itemsList[item_id].auctionStatus = AUCTION_STATUS.REVEALED;
returnNonWinnerMoney(item_id);
}
} else{
}
function getKey(uint256 item_id)
public
view
onlyItemSeller(item_id)
returns (string memory)
{
require(
itemsList[item_id].status == ITEM_STATUS.BUYING,
"KEY NOT AVAILABLE"
);
return itemsList[item_id].bidWinner.public_key;
}
function giveAccess(uint256 item_id, string memory secret_string)
public
payable
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.BUYING,
"Item not purchased yet"
);
itemsList[item_id].secret_string = secret_string;
itemsList[item_id].status = ITEM_STATUS.BOUGHT;
itemsList[item_id].seller.transfer(itemsList[item_id].final_price);
returnWinnerPendingMoney(item_id);
}
function returnWinnerPendingMoney(uint256 item_id) private {
uint256 pendingMoney = itemsList[item_id].bidWinner.price -
itemsList[item_id].final_price;
itemsList[item_id].bidWinner.buyer.transfer(pendingMoney);
}
function returnNonWinnerMoney(uint256 item_id) private {
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
if (
itemsList[item_id].verifiedBids[i].buyer ==
itemsList[item_id].bidWinner.buyer
) {
continue;
}
uint256 returnPrice = itemsList[item_id].verifiedBids[i].price;
itemsList[item_id].verifiedBids[i].buyer.transfer(returnPrice);
}
}
function returnNonWinnerMoney(uint256 item_id) private {
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
if (
itemsList[item_id].verifiedBids[i].buyer ==
itemsList[item_id].bidWinner.buyer
) {
continue;
}
uint256 returnPrice = itemsList[item_id].verifiedBids[i].price;
itemsList[item_id].verifiedBids[i].buyer.transfer(returnPrice);
}
}
function returnNonWinnerMoney(uint256 item_id) private {
for (uint256 i = 0; i < itemsList[item_id].verifiedBids.length; i++) {
if (
itemsList[item_id].verifiedBids[i].buyer ==
itemsList[item_id].bidWinner.buyer
) {
continue;
}
uint256 returnPrice = itemsList[item_id].verifiedBids[i].price;
itemsList[item_id].verifiedBids[i].buyer.transfer(returnPrice);
}
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
function accessItem(uint256 item_id)
public
view
onlyItemOwnerOrSeller(item_id)
returns (string memory)
{
return itemsList[item_id].secret_string;
}
function changeName(uint256 item_id, string memory item_name)
public
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.OPEN,
"Item is already sold"
);
itemsList[item_id].status = ITEM_STATUS.LOCKED;
itemsList[item_id].item_name = item_name;
itemsList[item_id].status = ITEM_STATUS.OPEN;
}
function changePrice(uint256 item_id, uint256 price)
public
onlyItemSeller(item_id)
{
require(
itemsList[item_id].status == ITEM_STATUS.OPEN,
"Item is already sold"
);
itemsList[item_id].status = ITEM_STATUS.LOCKED;
itemsList[item_id].asking_price = price;
itemsList[item_id].status = ITEM_STATUS.OPEN;
}
function uintToStr(uint256 _i)
private
pure
returns (string memory _uintAsString)
{
uint256 number = _i;
if (number == 0) {
return "0";
}
uint256 j = number;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (number != 0) {
bstr[k--] = bytes1(uint8(48 + (number % 10)));
number /= 10;
}
return string(bstr);
}
function uintToStr(uint256 _i)
private
pure
returns (string memory _uintAsString)
{
uint256 number = _i;
if (number == 0) {
return "0";
}
uint256 j = number;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (number != 0) {
bstr[k--] = bytes1(uint8(48 + (number % 10)));
number /= 10;
}
return string(bstr);
}
function uintToStr(uint256 _i)
private
pure
returns (string memory _uintAsString)
{
uint256 number = _i;
if (number == 0) {
return "0";
}
uint256 j = number;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (number != 0) {
bstr[k--] = bytes1(uint8(48 + (number % 10)));
number /= 10;
}
return string(bstr);
}
function uintToStr(uint256 _i)
private
pure
returns (string memory _uintAsString)
{
uint256 number = _i;
if (number == 0) {
return "0";
}
uint256 j = number;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (number != 0) {
bstr[k--] = bytes1(uint8(48 + (number % 10)));
number /= 10;
}
return string(bstr);
}
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(data[i] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(data[i] & 0x0f))];
}
return string(str);
}
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(data[i] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(data[i] & 0x0f))];
}
return string(str);
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function printHelper(uint i, bool firstItem) public view returns (string memory) {
string memory str = "";
uint at = 0;
if(itemsList[i].auctionType == AUCTION_TYPE.SECOND_PRICE){
at=1;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.AVG_PRICE){
at = 2;
}
else if(itemsList[i].auctionType == AUCTION_TYPE.FIXED){
at = 3;
}
uint ast = 0;
if(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION){
ast = 1;
}
else if(itemsList[i].auctionStatus == AUCTION_STATUS.REVEALED)
{
ast = 2;
}
uint ist = 0;
if(itemsList[i].status == ITEM_STATUS.OPEN){
ist = 1;
}
else if(itemsList[i].status == ITEM_STATUS.BUYING){
ist = 2;
}
else if(itemsList[i].status == ITEM_STATUS.BOUGHT){
ist = 3;
}
if(!firstItem){
str = string(abi.encodePacked(str, ','));
}
str = string(abi.encodePacked(str, '{"itemId":'));
str = string(abi.encodePacked(str, uintToStr(i)));
str = string(abi.encodePacked(str, ',"itemName":"'));
str = string(abi.encodePacked(str, itemsList[i].item_name));
str = string(abi.encodePacked(str, '","itemDescription": "'));
str = string(abi.encodePacked(str, itemsList[i].item_desc));
str = string(abi.encodePacked(str, '","itemStatus":'));
str = string(abi.encodePacked(str, uintToStr(ist)));
str = string(abi.encodePacked(str, ',"askingPrice":'));
str = string(abi.encodePacked(str, uintToStr(itemsList[i].asking_price)));
str = string(abi.encodePacked(str, ',"auctionType":'));
str = string(abi.encodePacked(str, uintToStr(at)));
str = string(abi.encodePacked(str, ',"auctionStatus":'));
str = string(abi.encodePacked(str, uintToStr(ast)));
str = string(abi.encodePacked(str, ',"sellerId": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].seller))));
str = string(abi.encodePacked(str, '","alreadyBid": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidders[msg.sender]))));
str = string(abi.encodePacked(str, '","bidWinner": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].bidWinner.buyer))));
str = string(abi.encodePacked(str, '","isVerified": "'));
str = string(abi.encodePacked(str,toString(abi.encodePacked(itemsList[i].isVerified[msg.sender]))));
str = string(abi.encodePacked(str, '"}'));
return str;
}
function viewActiveListings(bool allItems) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (allItems || itemsList[i].auctionStatus == AUCTION_STATUS.ONGOING ||
(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION && itemsList[i].auctionType == AUCTION_TYPE.FIXED)) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
function viewActiveListings(bool allItems) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (allItems || itemsList[i].auctionStatus == AUCTION_STATUS.ONGOING ||
(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION && itemsList[i].auctionType == AUCTION_TYPE.FIXED)) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
function viewActiveListings(bool allItems) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (allItems || itemsList[i].auctionStatus == AUCTION_STATUS.ONGOING ||
(itemsList[i].auctionStatus == AUCTION_STATUS.VERIFICATION && itemsList[i].auctionType == AUCTION_TYPE.FIXED)) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
function viewSellerListings(address seller_id) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (itemsList[i].seller == seller_id) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
function viewSellerListings(address seller_id) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (itemsList[i].seller == seller_id) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
function viewSellerListings(address seller_id) public view returns (string memory) {
string memory str = "[";
bool firstItem = true;
for (uint256 i = 1; i <= itemsCount; i++) {
if (itemsList[i].seller == seller_id) {
str = string(abi.encodePacked(str, printHelper(i, firstItem)));
firstItem = false;
}
}
str = string(abi.encodePacked(str, "]"));
return str;
}
}
| 12,878,042 |
[
1,
7956,
348,
1165,
310,
11810,
282,
1220,
6835,
8770,
87,
326,
5518,
357,
2456,
29917,
471,
8121,
4186,
358,
3073,
8938,
282,
10434,
3914,
17,
40,
346,
6215,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
432,
4062,
288,
203,
565,
2792,
25504,
67,
8608,
288,
203,
565,
289,
203,
203,
565,
2792,
432,
27035,
67,
8608,
288,
203,
3639,
531,
4960,
51,
1360,
16,
203,
3639,
6422,
14865,
16,
203,
3639,
2438,
3412,
37,
6687,
203,
565,
289,
203,
203,
565,
2792,
432,
27035,
67,
2399,
288,
203,
3639,
21786,
67,
7698,
1441,
16,
203,
3639,
19379,
67,
7698,
1441,
16,
203,
3639,
432,
9266,
67,
7698,
1441,
16,
203,
3639,
26585,
203,
565,
289,
203,
203,
565,
1958,
987,
310,
288,
203,
3639,
1758,
8843,
429,
29804,
31,
203,
3639,
25504,
67,
8608,
1267,
31,
203,
3639,
533,
761,
67,
529,
31,
203,
3639,
533,
761,
67,
5569,
31,
203,
3639,
533,
4001,
67,
1080,
31,
203,
3639,
2254,
5034,
29288,
67,
8694,
31,
203,
3639,
2254,
5034,
727,
67,
8694,
31,
203,
3639,
2874,
12,
3890,
1578,
516,
1426,
13,
14242,
38,
2232,
31,
203,
3639,
2254,
5034,
324,
1873,
414,
1380,
31,
203,
3639,
2874,
12,
2867,
516,
1426,
13,
324,
1873,
414,
31,
203,
3639,
2874,
12,
2867,
516,
1426,
13,
353,
24369,
31,
203,
3639,
605,
350,
765,
8526,
13808,
38,
2232,
31,
203,
3639,
605,
350,
765,
9949,
59,
7872,
31,
203,
3639,
432,
27035,
67,
8608,
279,
4062,
1482,
31,
203,
3639,
432,
27035,
67,
2399,
279,
4062,
559,
31,
203,
565,
289,
203,
203,
565,
1958,
605,
350,
765,
288,
203,
3639,
1758,
8843,
429,
27037,
31,
203,
3639,
2254,
5034,
6205,
31,
203,
3639,
533,
1071,
67,
856,
31,
2
] |
pragma solidity ^0.4.24;
/**
* @title BaseWallet
* @dev Simple modular wallet that authorises modules to call its invoke() method.
* Based on https://gist.github.com/Arachnid/a619d31f6d32757a4328a428286da186 by
* @author Julien Niset - <[email protected]>
*/
contract BaseWallet {
// The implementation of the proxy
address public implementation;
// The owner
address public owner;
// The authorised modules
mapping (address => bool) public authorised;
// The enabled static calls
mapping (bytes4 => address) public enabled;
// The number of modules
uint public modules;
event AuthorisedModule(address indexed module, bool value);
event EnabledStaticCall(address indexed module, bytes4 indexed method);
event Invoked(address indexed module, address indexed target, uint indexed value, bytes data);
event Received(uint indexed value, address indexed sender, bytes data);
event OwnerChanged(address owner);
/**
* @dev Throws if the sender is not an authorised module.
*/
modifier moduleOnly {
require(authorised[msg.sender], "BW: msg.sender not an authorized module");
_;
}
/**
* @dev Inits the wallet by setting the owner and authorising a list of modules.
* @param _owner The owner.
* @param _modules The modules to authorise.
*/
function init(address _owner, address[] _modules) external {
require(owner == address(0) && modules == 0, "BW: wallet already initialised");
require(_modules.length > 0, "BW: construction requires at least 1 module");
owner = _owner;
modules = _modules.length;
for(uint256 i = 0; i < _modules.length; i++) {
require(authorised[_modules[i]] == false, "BW: module is already added");
authorised[_modules[i]] = true;
Module(_modules[i]).init(this);
emit AuthorisedModule(_modules[i], true);
}
}
/**
* @dev Enables/Disables a module.
* @param _module The target module.
* @param _value Set to true to authorise the module.
*/
function authoriseModule(address _module, bool _value) external moduleOnly {
if (authorised[_module] != _value) {
if(_value == true) {
modules += 1;
authorised[_module] = true;
Module(_module).init(this);
}
else {
modules -= 1;
require(modules > 0, "BW: wallet must have at least one module");
delete authorised[_module];
}
emit AuthorisedModule(_module, _value);
}
}
/**
* @dev Enables a static method by specifying the target module to which the call
* must be delegated.
* @param _module The target module.
* @param _method The static method signature.
*/
function enableStaticCall(address _module, bytes4 _method) external moduleOnly {
require(authorised[_module], "BW: must be an authorised module for static call");
enabled[_method] = _module;
emit EnabledStaticCall(_module, _method);
}
/**
* @dev Sets a new owner for the wallet.
* @param _newOwner The new owner.
*/
function setOwner(address _newOwner) external moduleOnly {
require(_newOwner != address(0), "BW: address cannot be null");
owner = _newOwner;
emit OwnerChanged(_newOwner);
}
/**
* @dev Performs a generic transaction.
* @param _target The address for the transaction.
* @param _value The value of the transaction.
* @param _data The data of the transaction.
*/
function invoke(address _target, uint _value, bytes _data) external moduleOnly {
// solium-disable-next-line security/no-call-value
require(_target.call.value(_value)(_data), "BW: call to target failed");
emit Invoked(msg.sender, _target, _value, _data);
}
/**
* @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to
* implement specific static methods. It delegates the static call to a target contract if the data corresponds
* to an enabled method, or logs the call otherwise.
*/
function() public payable {
if(msg.data.length > 0) {
address module = enabled[msg.sig];
if(module == address(0)) {
emit Received(msg.value, msg.sender, msg.data);
}
else {
require(authorised[module], "BW: must be an authorised module for static call");
// solium-disable-next-line security/no-inline-assembly
assembly {
calldatacopy(0, 0, calldatasize())
let result := staticcall(gas, module, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
}
}
/**
* @title Module
* @dev Interface for a module.
* A module MUST implement the addModule() method to ensure that a wallet with at least one module
* can never end up in a "frozen" state.
* @author Julien Niset - <[email protected]>
*/
interface Module {
/**
* @dev Inits a module for a wallet by e.g. setting some wallet specific parameters in storage.
* @param _wallet The wallet.
*/
function init(BaseWallet _wallet) external;
/**
* @dev Adds a module to a wallet.
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(BaseWallet _wallet, Module _module) external;
/**
* @dev Utility method to recover any ERC20 token that was sent to the
* module by mistake.
* @param _token The token to recover.
*/
function recoverToken(address _token) external;
}
/**
* @title Upgrader
* @dev Interface for a contract that can upgrade wallets by enabling/disabling modules.
* @author Julien Niset - <[email protected]>
*/
interface Upgrader {
/**
* @dev Upgrades a wallet by enabling/disabling modules.
* @param _wallet The owner.
*/
function upgrade(address _wallet, address[] _toDisable, address[] _toEnable) external;
function toDisable() external view returns (address[]);
function toEnable() external view returns (address[]);
}
/**
* @title Owned
* @dev Basic contract to define an owner.
* @author Julien Niset - <[email protected]>
*/
contract Owned {
// The owner
address public owner;
event OwnerChanged(address indexed _newOwner);
/**
* @dev Throws if the sender is not the owner.
*/
modifier onlyOwner {
require(msg.sender == owner, "Must be owner");
_;
}
constructor() public {
owner = msg.sender;
}
/**
* @dev Lets the owner transfer ownership of the contract to a new owner.
* @param _newOwner The new owner.
*/
function changeOwner(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "Address must not be null");
owner = _newOwner;
emit OwnerChanged(_newOwner);
}
}
/**
* ERC20 contract interface.
*/
contract ERC20 {
function totalSupply() public view returns (uint);
function decimals() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view 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);
}
/**
* @title ModuleRegistry
* @dev Registry of authorised modules.
* Modules must be registered before they can be authorised on a wallet.
* @author Julien Niset - <[email protected]>
*/
contract ModuleRegistry is Owned {
mapping (address => Info) internal modules;
mapping (address => Info) internal upgraders;
event ModuleRegistered(address indexed module, bytes32 name);
event ModuleDeRegistered(address module);
event UpgraderRegistered(address indexed upgrader, bytes32 name);
event UpgraderDeRegistered(address upgrader);
struct Info {
bool exists;
bytes32 name;
}
/**
* @dev Registers a module.
* @param _module The module.
* @param _name The unique name of the module.
*/
function registerModule(address _module, bytes32 _name) external onlyOwner {
require(!modules[_module].exists, "MR: module already exists");
modules[_module] = Info({exists: true, name: _name});
emit ModuleRegistered(_module, _name);
}
/**
* @dev Deregisters a module.
* @param _module The module.
*/
function deregisterModule(address _module) external onlyOwner {
require(modules[_module].exists, "MR: module does not exists");
delete modules[_module];
emit ModuleDeRegistered(_module);
}
/**
* @dev Registers an upgrader.
* @param _upgrader The upgrader.
* @param _name The unique name of the upgrader.
*/
function registerUpgrader(address _upgrader, bytes32 _name) external onlyOwner {
require(!upgraders[_upgrader].exists, "MR: upgrader already exists");
upgraders[_upgrader] = Info({exists: true, name: _name});
emit UpgraderRegistered(_upgrader, _name);
}
/**
* @dev Deregisters an upgrader.
* @param _upgrader The _upgrader.
*/
function deregisterUpgrader(address _upgrader) external onlyOwner {
require(upgraders[_upgrader].exists, "MR: upgrader does not exists");
delete upgraders[_upgrader];
emit UpgraderDeRegistered(_upgrader);
}
/**
* @dev Utility method enbaling the owner of the registry to claim any ERC20 token that was sent to the
* registry.
* @param _token The token to recover.
*/
function recoverToken(address _token) external onlyOwner {
uint total = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, total);
}
/**
* @dev Gets the name of a module from its address.
* @param _module The module address.
* @return the name.
*/
function moduleInfo(address _module) external view returns (bytes32) {
return modules[_module].name;
}
/**
* @dev Gets the name of an upgrader from its address.
* @param _upgrader The upgrader address.
* @return the name.
*/
function upgraderInfo(address _upgrader) external view returns (bytes32) {
return upgraders[_upgrader].name;
}
/**
* @dev Checks if a module is registered.
* @param _module The module address.
* @return true if the module is registered.
*/
function isRegisteredModule(address _module) external view returns (bool) {
return modules[_module].exists;
}
/**
* @dev Checks if a list of modules are registered.
* @param _modules The list of modules address.
* @return true if all the modules are registered.
*/
function isRegisteredModule(address[] _modules) external view returns (bool) {
for(uint i = 0; i < _modules.length; i++) {
if (!modules[_modules[i]].exists) {
return false;
}
}
return true;
}
/**
* @dev Checks if an upgrader is registered.
* @param _upgrader The upgrader address.
* @return true if the upgrader is registered.
*/
function isRegisteredUpgrader(address _upgrader) external view returns (bool) {
return upgraders[_upgrader].exists;
}
}
|
* @dev Deregisters a module. @param _module The module./
|
function deregisterModule(address _module) external onlyOwner {
require(modules[_module].exists, "MR: module does not exists");
delete modules[_module];
emit ModuleDeRegistered(_module);
}
| 907,787 |
[
1,
40,
11877,
6045,
279,
1605,
18,
225,
389,
2978,
1021,
1605,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
24310,
3120,
12,
2867,
389,
2978,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
6400,
63,
67,
2978,
8009,
1808,
16,
315,
23464,
30,
1605,
1552,
486,
1704,
8863,
203,
3639,
1430,
4381,
63,
67,
2978,
15533,
203,
3639,
3626,
5924,
758,
10868,
24899,
2978,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import "./Proxy.sol";
import "./lib/Guard.sol";
import "./lib/FlashLoanReceiverBase.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract ProxyLogic {
using SafeMath for uint256;
address constant ETHADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address constant AaveEthAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address constant AaveLendingPoolAddressProviderAddress = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
constructor() public {}
function() external payable {}
struct MyCustomData {
address payable flashloanWrapperAddress;
uint256 a;
}
function _proxyGuardPermit(address payable proxyAddress, address src)
internal
{
address g = address(DSProxy(proxyAddress).authority());
DSGuard(g).permit(
bytes32(bytes20(address(src))),
DSGuard(g).ANY(),
DSGuard(g).ANY()
);
}
function _proxyGuardForbid(address payable proxyAddress, address src)
internal
{
address g = address(DSProxy(proxyAddress).authority());
DSGuard(g).forbid(
bytes32(bytes20(address(src))),
DSGuard(g).ANY(),
DSGuard(g).ANY()
);
}
// This function is triggered AFTER Aave has loaned us $,
// which having DSProxy as the storage
// (i.e. the contract code is executed as DSProxy, and not as ProxyLogic)
function flashLoanPostLoan(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
) external {
MyCustomData memory d = abi.decode(_params, (MyCustomData));
uint repayAmount = _amount.add(_fee);
// INSERT YOUR LOGIC HERE:
// Do your arbitrage here / finance VM building blocks here
// Once you're done you'll need to send the funds back to the wrapper,
// as the wrapper is responsible for paying the fees back.
// Otherwise the whole Tx fails
if(_reserve == ETHADDRESS) {
//solium-disable-next-line
d.flashloanWrapperAddress.call.value(repayAmount)("");
} else {
IERC20(_reserve).transfer(d.flashloanWrapperAddress, repayAmount);
}
}
// User tells proxy to execute this function
function flashLoan(
uint256 flashloanEthAmount,
address payable dsProxyAddress,
address flashloanWrapperAddress,
address proxyLogicAddress,
bytes calldata executeOperationCalldataParams
) external {
// Injects proxy and target address into calldataParams
// See FlashLoanWrapper.sol for more info
bytes memory addressAndExecuteOperationCalldataParams = abi
.encodePacked(
abi.encodePacked(dsProxyAddress),
abi.encodePacked(proxyLogicAddress),
executeOperationCalldataParams
);
// Approve flashloan wrapper to call proxy
_proxyGuardPermit(dsProxyAddress, flashloanWrapperAddress);
// Flashloan to flashloanWrapperAddress
// This triggers `executeOperation` in flashloanWrapperAddress
// which then calls DSProxy to execute the target address using the given method
ILendingPool lendingPool = ILendingPool(
ILendingPoolAddressesProvider(AaveLendingPoolAddressProviderAddress)
.getLendingPool()
);
lendingPool.flashLoan(
flashloanWrapperAddress,
AaveEthAddress,
flashloanEthAmount,
addressAndExecuteOperationCalldataParams
);
// Forbids lendingPool to call proxy
_proxyGuardForbid(dsProxyAddress, flashloanWrapperAddress);
}
}
|
User tells proxy to execute this function Injects proxy and target address into calldataParams See FlashLoanWrapper.sol for more info Approve flashloan wrapper to call proxy Flashloan to flashloanWrapperAddress This triggers `executeOperation` in flashloanWrapperAddress which then calls DSProxy to execute the target address using the given method Forbids lendingPool to call proxy
|
function flashLoan(
uint256 flashloanEthAmount,
address payable dsProxyAddress,
address flashloanWrapperAddress,
address proxyLogicAddress,
bytes calldata executeOperationCalldataParams
) external {
bytes memory addressAndExecuteOperationCalldataParams = abi
.encodePacked(
abi.encodePacked(dsProxyAddress),
abi.encodePacked(proxyLogicAddress),
executeOperationCalldataParams
);
_proxyGuardPermit(dsProxyAddress, flashloanWrapperAddress);
ILendingPool lendingPool = ILendingPool(
ILendingPoolAddressesProvider(AaveLendingPoolAddressProviderAddress)
.getLendingPool()
);
lendingPool.flashLoan(
flashloanWrapperAddress,
AaveEthAddress,
flashloanEthAmount,
addressAndExecuteOperationCalldataParams
);
_proxyGuardForbid(dsProxyAddress, flashloanWrapperAddress);
}
| 13,069,537 |
[
1,
1299,
24551,
2889,
358,
1836,
333,
445,
20085,
87,
2889,
471,
1018,
1758,
1368,
745,
892,
1370,
2164,
15014,
1504,
304,
3611,
18,
18281,
364,
1898,
1123,
1716,
685,
537,
9563,
383,
304,
4053,
358,
745,
2889,
15014,
383,
304,
358,
9563,
383,
304,
3611,
1887,
1220,
11752,
1375,
8837,
2988,
68,
316,
9563,
383,
304,
3611,
1887,
1492,
1508,
4097,
8678,
3886,
358,
1836,
326,
1018,
1758,
1450,
326,
864,
707,
2457,
70,
2232,
328,
2846,
2864,
358,
745,
2889,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
9563,
1504,
304,
12,
203,
3639,
2254,
5034,
9563,
383,
304,
41,
451,
6275,
16,
203,
3639,
1758,
8843,
429,
3780,
3886,
1887,
16,
203,
3639,
1758,
9563,
383,
304,
3611,
1887,
16,
203,
3639,
1758,
2889,
20556,
1887,
16,
203,
3639,
1731,
745,
892,
1836,
2988,
1477,
892,
1370,
203,
565,
262,
3903,
288,
203,
3639,
1731,
3778,
1758,
1876,
5289,
2988,
1477,
892,
1370,
273,
24126,
203,
5411,
263,
3015,
4420,
329,
12,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
2377,
3886,
1887,
3631,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
5656,
20556,
1887,
3631,
203,
5411,
1836,
2988,
1477,
892,
1370,
203,
3639,
11272,
203,
203,
3639,
389,
5656,
16709,
9123,
305,
12,
2377,
3886,
1887,
16,
9563,
383,
304,
3611,
1887,
1769,
203,
203,
3639,
467,
48,
2846,
2864,
328,
2846,
2864,
273,
467,
48,
2846,
2864,
12,
203,
5411,
467,
48,
2846,
2864,
7148,
2249,
12,
37,
836,
48,
2846,
2864,
1887,
2249,
1887,
13,
203,
7734,
263,
588,
48,
2846,
2864,
1435,
203,
3639,
11272,
203,
3639,
328,
2846,
2864,
18,
13440,
1504,
304,
12,
203,
5411,
9563,
383,
304,
3611,
1887,
16,
203,
5411,
432,
836,
41,
451,
1887,
16,
203,
5411,
9563,
383,
304,
41,
451,
6275,
16,
203,
5411,
1758,
1876,
5289,
2988,
1477,
892,
1370,
203,
3639,
11272,
203,
203,
3639,
389,
5656,
16709,
1290,
19773,
12,
2377,
3886,
1887,
16,
9563,
383,
304,
3611,
1887,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IIntegrationManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the IntegrationManager
interface IIntegrationManager {
enum SpendAssetsHandleType {None, Approve, Transfer}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../IIntegrationManager.sol";
/// @title Integration Adapter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all integration adapters
interface IIntegrationAdapter {
function parseAssetsForAction(
address _vaultProxy,
bytes4 _selector,
bytes calldata _encodedCallArgs
)
external
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "../utils/actions/CurveGaugeV2RewardsHandlerMixin.sol";
import "../utils/actions/CurveSethLiquidityActionsMixin.sol";
import "../utils/AdapterBase.sol";
/// @title CurveLiquiditySethAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for liquidity provision in Curve's seth pool (https://www.curve.fi/seth)
/// @dev Rewards tokens are not included as spend assets or incoming assets for claimRewards()
/// or claimRewardsAndReinvest(). Rationale:
/// - rewards tokens can be claimed to the vault outside of the IntegrationManager, so no need
/// to enforce policy management or emit an event
/// - rewards tokens can be outside of the asset universe, in which case they cannot be tracked
contract CurveLiquiditySethAdapter is
AdapterBase,
CurveGaugeV2RewardsHandlerMixin,
CurveSethLiquidityActionsMixin
{
address private immutable LIQUIDITY_GAUGE_TOKEN;
address private immutable LP_TOKEN;
address private immutable SETH_TOKEN;
constructor(
address _integrationManager,
address _liquidityGaugeToken,
address _lpToken,
address _minter,
address _pool,
address _crvToken,
address _sethToken,
address _wethToken
)
public
AdapterBase(_integrationManager)
CurveGaugeV2RewardsHandlerMixin(_minter, _crvToken)
CurveSethLiquidityActionsMixin(_pool, _sethToken, _wethToken)
{
LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken;
LP_TOKEN = _lpToken;
SETH_TOKEN = _sethToken;
// Max approve contracts to spend relevant tokens
ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max);
}
/// @dev Needed to receive ETH from redemption and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Claims rewards from the Curve Minter as well as pool-specific rewards
/// @param _vaultProxy The VaultProxy of the calling fund
function claimRewards(
address _vaultProxy,
bytes calldata,
bytes calldata
) external onlyIntegrationManager {
__curveGaugeV2ClaimAllRewards(LIQUIDITY_GAUGE_TOKEN, _vaultProxy);
}
/// @notice Lends assets for seth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function lend(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
uint256 outgoingWethAmount,
uint256 outgoingSethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_actionData);
__curveSethLend(
outgoingWethAmount,
outgoingSethAmount,
minIncomingLiquidityGaugeTokenAmount
);
}
/// @notice Lends assets for seth LP tokens, then stakes the received LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function lendAndStake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
uint256 outgoingWethAmount,
uint256 outgoingSethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_actionData);
__curveSethLend(
outgoingWethAmount,
outgoingSethAmount,
minIncomingLiquidityGaugeTokenAmount
);
__curveGaugeV2Stake(
LIQUIDITY_GAUGE_TOKEN,
LP_TOKEN,
ERC20(LP_TOKEN).balanceOf(address(this))
);
}
/// @notice Redeems seth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function redeem(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
uint256 outgoingLpTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingSethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_actionData);
__curveSethRedeem(
outgoingLpTokenAmount,
minIncomingWethAmount,
minIncomingSethAmount,
redeemSingleAsset
);
}
/// @notice Stakes seth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function stake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
__curveGaugeV2Stake(LIQUIDITY_GAUGE_TOKEN, LP_TOKEN, __decodeStakeCallArgs(_actionData));
}
/// @notice Unstakes seth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function unstake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
__curveGaugeV2Unstake(LIQUIDITY_GAUGE_TOKEN, __decodeUnstakeCallArgs(_actionData));
}
/// @notice Unstakes seth LP tokens, then redeems them
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function unstakeAndRedeem(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingSethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_actionData);
__curveGaugeV2Unstake(LIQUIDITY_GAUGE_TOKEN, outgoingLiquidityGaugeTokenAmount);
__curveSethRedeem(
outgoingLiquidityGaugeTokenAmount,
minIncomingWethAmount,
minIncomingSethAmount,
redeemSingleAsset
);
}
/////////////////////////////
// PARSE ASSETS FOR METHOD //
/////////////////////////////
/// @notice Parses the expected assets in a particular action
/// @param _selector The function selector for the callOnIntegration
/// @param _actionData Data specific to this action
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForAction(
address,
bytes4 _selector,
bytes calldata _actionData
)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == CLAIM_REWARDS_SELECTOR) {
return __parseAssetsForClaimRewards();
} else if (_selector == LEND_SELECTOR) {
return __parseAssetsForLend(_actionData);
} else if (_selector == LEND_AND_STAKE_SELECTOR) {
return __parseAssetsForLendAndStake(_actionData);
} else if (_selector == REDEEM_SELECTOR) {
return __parseAssetsForRedeem(_actionData);
} else if (_selector == STAKE_SELECTOR) {
return __parseAssetsForStake(_actionData);
} else if (_selector == UNSTAKE_SELECTOR) {
return __parseAssetsForUnstake(_actionData);
} else if (_selector == UNSTAKE_AND_REDEEM_SELECTOR) {
return __parseAssetsForUnstakeAndRedeem(_actionData);
}
revert("parseAssetsForAction: _selector invalid");
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewards() calls.
/// No action required, all values empty.
function __parseAssetsForClaimRewards()
private
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
return (
IIntegrationManager.SpendAssetsHandleType.None,
new address[](0),
new uint256[](0),
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lend() calls
function __parseAssetsForLend(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingWethAmount,
uint256 outgoingSethAmount,
uint256 minIncomingLpTokenAmount
) = __decodeLendCallArgs(_actionData);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls(
outgoingWethAmount,
outgoingSethAmount
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingLpTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lendAndStake() calls
function __parseAssetsForLendAndStake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingWethAmount,
uint256 outgoingSethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_actionData);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls(
outgoingWethAmount,
outgoingSethAmount
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingLiquidityGaugeTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during redeem() calls
function __parseAssetsForRedeem(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingLpTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingSethAmount,
bool receiveSingleAsset
) = __decodeRedeemCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLpTokenAmount;
(incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls(
minIncomingWethAmount,
minIncomingSethAmount,
receiveSingleAsset
);
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during stake() calls
function __parseAssetsForStake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
uint256 outgoingLpTokenAmount = __decodeStakeCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLpTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLpTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstake() calls
function __parseAssetsForUnstake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstakeAndRedeem() calls
function __parseAssetsForUnstakeAndRedeem(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingSethAmount,
bool receiveSingleAsset
) = __decodeRedeemCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
(incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls(
minIncomingWethAmount,
minIncomingSethAmount,
receiveSingleAsset
);
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend assets for redeem() and unstakeAndRedeem() calls
function __parseIncomingAssetsForRedemptionCalls(
uint256 _minIncomingWethAmount,
uint256 _minIncomingSethAmount,
bool _receiveSingleAsset
)
private
view
returns (address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_)
{
if (_receiveSingleAsset) {
incomingAssets_ = new address[](1);
minIncomingAssetAmounts_ = new uint256[](1);
if (_minIncomingWethAmount == 0) {
require(
_minIncomingSethAmount > 0,
"__parseIncomingAssetsForRedemptionCalls: No min asset amount specified"
);
incomingAssets_[0] = SETH_TOKEN;
minIncomingAssetAmounts_[0] = _minIncomingSethAmount;
} else {
require(
_minIncomingSethAmount == 0,
"__parseIncomingAssetsForRedemptionCalls: Too many min asset amounts specified"
);
incomingAssets_[0] = getCurveSethLiquidityWethToken();
minIncomingAssetAmounts_[0] = _minIncomingWethAmount;
}
} else {
incomingAssets_ = new address[](2);
incomingAssets_[0] = getCurveSethLiquidityWethToken();
incomingAssets_[1] = SETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = _minIncomingWethAmount;
minIncomingAssetAmounts_[1] = _minIncomingSethAmount;
}
return (incomingAssets_, minIncomingAssetAmounts_);
}
/// @dev Helper function to parse spend assets for lend() and lendAndStake() calls
function __parseSpendAssetsForLendingCalls(
uint256 _outgoingWethAmount,
uint256 _outgoingSethAmount
) private view returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_) {
if (_outgoingWethAmount > 0 && _outgoingSethAmount > 0) {
spendAssets_ = new address[](2);
spendAssets_[0] = getCurveSethLiquidityWethToken();
spendAssets_[1] = SETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = _outgoingWethAmount;
spendAssetAmounts_[1] = _outgoingSethAmount;
} else if (_outgoingWethAmount > 0) {
spendAssets_ = new address[](1);
spendAssets_[0] = getCurveSethLiquidityWethToken();
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = _outgoingWethAmount;
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = SETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = _outgoingSethAmount;
}
return (spendAssets_, spendAssetAmounts_);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
/// @dev Helper to decode the encoded call arguments for lending
function __decodeLendCallArgs(bytes memory _actionData)
private
pure
returns (
uint256 outgoingWethAmount_,
uint256 outgoingSethAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_actionData, (uint256, uint256, uint256));
}
/// @dev Helper to decode the encoded call arguments for redeeming.
/// If `receiveSingleAsset_` is `true`, then one (and only one) of
/// `minIncomingWethAmount_` and `minIncomingSethAmount_` must be >0
/// to indicate which asset is to be received.
function __decodeRedeemCallArgs(bytes memory _actionData)
private
pure
returns (
uint256 outgoingAssetAmount_,
uint256 minIncomingWethAmount_,
uint256 minIncomingSethAmount_,
bool receiveSingleAsset_
)
{
return abi.decode(_actionData, (uint256, uint256, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for staking
function __decodeStakeCallArgs(bytes memory _actionData)
private
pure
returns (uint256 outgoingLpTokenAmount_)
{
return abi.decode(_actionData, (uint256));
}
/// @dev Helper to decode the encoded call arguments for unstaking
function __decodeUnstakeCallArgs(bytes memory _actionData)
private
pure
returns (uint256 outgoingLiquidityGaugeTokenAmount_)
{
return abi.decode(_actionData, (uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable
/// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value
function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) {
return LIQUIDITY_GAUGE_TOKEN;
}
/// @notice Gets the `LP_TOKEN` variable
/// @return lpToken_ The `LP_TOKEN` variable value
function getLpToken() external view returns (address lpToken_) {
return LP_TOKEN;
}
/// @notice Gets the `SETH_TOKEN` variable
/// @return sethToken_ The `SETH_TOKEN` variable value
function getSethToken() external view returns (address sethToken_) {
return SETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../utils/AssetHelpers.sol";
import "../IIntegrationAdapter.sol";
import "./IntegrationSelectors.sol";
/// @title AdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters
abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors, AssetHelpers {
using SafeERC20 for ERC20;
address internal immutable INTEGRATION_MANAGER;
/// @dev Provides a standard implementation for transferring incoming assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionIncomingAssetsTransferHandler(
address _vaultProxy,
bytes memory _assetData
) {
_;
(, , address[] memory incomingAssets) = __decodeAssetData(_assetData);
__pushFullAssetBalances(_vaultProxy, incomingAssets);
}
/// @dev Provides a standard implementation for transferring unspent spend assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionSpendAssetsTransferHandler(address _vaultProxy, bytes memory _assetData) {
_;
(address[] memory spendAssets, , ) = __decodeAssetData(_assetData);
__pushFullAssetBalances(_vaultProxy, spendAssets);
}
modifier onlyIntegrationManager {
require(
msg.sender == INTEGRATION_MANAGER,
"Only the IntegrationManager can call this function"
);
_;
}
constructor(address _integrationManager) public {
INTEGRATION_MANAGER = _integrationManager;
}
// INTERNAL FUNCTIONS
/// @dev Helper to decode the _assetData param passed to adapter call
function __decodeAssetData(bytes memory _assetData)
internal
pure
returns (
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_
)
{
return abi.decode(_assetData, (address[], uint256[], address[]));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() external view returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IntegrationSelectors Contract
/// @author Enzyme Council <[email protected]>
/// @notice Selectors for integration actions
/// @dev Selectors are created from their signatures rather than hardcoded for easy verification
abstract contract IntegrationSelectors {
// Trading
bytes4 public constant TAKE_ORDER_SELECTOR = bytes4(
keccak256("takeOrder(address,bytes,bytes)")
);
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
// Staking
bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)"));
bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)"));
// Rewards
bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4(
keccak256("claimRewards(address,bytes,bytes)")
);
// Combined
bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../interfaces/ICurveLiquidityGaugeV2.sol";
import "../../../../../utils/AssetHelpers.sol";
/// @title CurveGaugeV2ActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with any Curve LiquidityGaugeV2 contract
abstract contract CurveGaugeV2ActionsMixin is AssetHelpers {
uint256 private constant CURVE_GAUGE_V2_MAX_REWARDS = 8;
/// @dev Helper to claim pool-specific rewards
function __curveGaugeV2ClaimRewards(address _gauge, address _target) internal {
ICurveLiquidityGaugeV2(_gauge).claim_rewards(_target);
}
/// @dev Helper to get list of pool-specific rewards tokens
function __curveGaugeV2GetRewardsTokens(address _gauge)
internal
view
returns (address[] memory rewardsTokens_)
{
address[] memory lpRewardsTokensWithEmpties = new address[](CURVE_GAUGE_V2_MAX_REWARDS);
uint256 rewardsTokensCount;
for (uint256 i; i < CURVE_GAUGE_V2_MAX_REWARDS; i++) {
address rewardToken = ICurveLiquidityGaugeV2(_gauge).reward_tokens(i);
if (rewardToken != address(0)) {
lpRewardsTokensWithEmpties[i] = rewardToken;
rewardsTokensCount++;
} else {
break;
}
}
rewardsTokens_ = new address[](rewardsTokensCount);
for (uint256 i; i < rewardsTokensCount; i++) {
rewardsTokens_[i] = lpRewardsTokensWithEmpties[i];
}
return rewardsTokens_;
}
/// @dev Helper to stake LP tokens
function __curveGaugeV2Stake(
address _gauge,
address _lpToken,
uint256 _amount
) internal {
__approveAssetMaxAsNeeded(_lpToken, _gauge, _amount);
ICurveLiquidityGaugeV2(_gauge).deposit(_amount, address(this));
}
/// @dev Helper to unstake LP tokens
function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal {
ICurveLiquidityGaugeV2(_gauge).withdraw(_amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../interfaces/ICurveMinter.sol";
import "../../../../../utils/AddressArrayLib.sol";
import "./CurveGaugeV2ActionsMixin.sol";
/// @title CurveGaugeV2RewardsHandlerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for handling claiming and reinvesting rewards for a Curve pool
/// that uses the LiquidityGaugeV2 contract
abstract contract CurveGaugeV2RewardsHandlerMixin is CurveGaugeV2ActionsMixin {
using AddressArrayLib for address[];
address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN;
address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER;
constructor(address _minter, address _crvToken) public {
CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN = _crvToken;
CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER = _minter;
}
/// @dev Helper to claim all rewards (CRV and pool-specific).
/// Requires contract to be approved to use mint_for().
function __curveGaugeV2ClaimAllRewards(address _gauge, address _target) internal {
// Claim owed $CRV
ICurveMinter(CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER).mint_for(_gauge, _target);
// Claim owed pool-specific rewards
__curveGaugeV2ClaimRewards(_gauge, _target);
}
/// @dev Helper to get all rewards tokens for staking LP tokens
function __curveGaugeV2GetRewardsTokensWithCrv(address _gauge)
internal
view
returns (address[] memory rewardsTokens_)
{
return
__curveGaugeV2GetRewardsTokens(_gauge).addUniqueItem(
CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable
/// @return crvToken_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable value
function getCurveGaugeV2RewardsHandlerCrvToken() public view returns (address crvToken_) {
return CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN;
}
/// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable
/// @return minter_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable value
function getCurveGaugeV2RewardsHandlerMinter() public view returns (address minter_) {
return CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../../interfaces/ICurveStableSwapSeth.sol";
import "../../../../../interfaces/IWETH.sol";
/// @title CurveSethLiquidityActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with the Curve seth pool's liquidity functions
/// @dev Inheriting contract must have a receive() function
abstract contract CurveSethLiquidityActionsMixin {
using SafeERC20 for ERC20;
int128 private constant CURVE_SETH_POOL_INDEX_ETH = 0;
int128 private constant CURVE_SETH_POOL_INDEX_SETH = 1;
address private immutable CURVE_SETH_LIQUIDITY_POOL;
address private immutable CURVE_SETH_LIQUIDITY_WETH_TOKEN;
constructor(
address _pool,
address _sethToken,
address _wethToken
) public {
CURVE_SETH_LIQUIDITY_POOL = _pool;
CURVE_SETH_LIQUIDITY_WETH_TOKEN = _wethToken;
// Pre-approve pool to use max of seth token
ERC20(_sethToken).safeApprove(_pool, type(uint256).max);
}
/// @dev Helper to add liquidity to the pool
function __curveSethLend(
uint256 _outgoingWethAmount,
uint256 _outgoingSethAmount,
uint256 _minIncomingLPTokenAmount
) internal {
if (_outgoingWethAmount > 0) {
IWETH((CURVE_SETH_LIQUIDITY_WETH_TOKEN)).withdraw(_outgoingWethAmount);
}
ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).add_liquidity{value: _outgoingWethAmount}(
[_outgoingWethAmount, _outgoingSethAmount],
_minIncomingLPTokenAmount
);
}
/// @dev Helper to remove liquidity from the pool.
// Assumes that if _redeemSingleAsset is true, then
// "_minIncomingWethAmount > 0 XOR _minIncomingSethAmount > 0" has already been validated.
function __curveSethRedeem(
uint256 _outgoingLPTokenAmount,
uint256 _minIncomingWethAmount,
uint256 _minIncomingSethAmount,
bool _redeemSingleAsset
) internal {
if (_redeemSingleAsset) {
if (_minIncomingWethAmount > 0) {
ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
CURVE_SETH_POOL_INDEX_ETH,
_minIncomingWethAmount
);
IWETH(payable(CURVE_SETH_LIQUIDITY_WETH_TOKEN)).deposit{
value: payable(address(this)).balance
}();
} else {
ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
CURVE_SETH_POOL_INDEX_SETH,
_minIncomingSethAmount
);
}
} else {
ICurveStableSwapSeth(CURVE_SETH_LIQUIDITY_POOL).remove_liquidity(
_outgoingLPTokenAmount,
[_minIncomingWethAmount, _minIncomingSethAmount]
);
IWETH(payable(CURVE_SETH_LIQUIDITY_WETH_TOKEN)).deposit{
value: payable(address(this)).balance
}();
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CURVE_SETH_LIQUIDITY_POOL` variable
/// @return pool_ The `CURVE_SETH_LIQUIDITY_POOL` variable value
function getCurveSethLiquidityPool() public view returns (address pool_) {
return CURVE_SETH_LIQUIDITY_POOL;
}
/// @notice Gets the `CURVE_SETH_LIQUIDITY_WETH_TOKEN` variable
/// @return wethToken_ The `CURVE_SETH_LIQUIDITY_WETH_TOKEN` variable value
function getCurveSethLiquidityWethToken() public view returns (address wethToken_) {
return CURVE_SETH_LIQUIDITY_WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeV2 interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityGaugeV2 {
function claim_rewards(address) external;
function deposit(uint256, address) external;
function reward_tokens(uint256) external view returns (address);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveMinter interface
/// @author Enzyme Council <[email protected]>
interface ICurveMinter {
function mint_for(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveStableSwapSeth interface
/// @author Enzyme Council <[email protected]>
interface ICurveStableSwapSeth {
function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256);
function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory);
function remove_liquidity_one_coin(
uint256,
int128,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
uint256 allowance = ERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
ERC20(_asset).safeApprove(_target, 0);
}
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
|
@dev Helper to decode the encoded call arguments for redeeming. If `receiveSingleAsset_` is `true`, then one (and only one) of `minIncomingWethAmount_` and `minIncomingSethAmount_` must be >0 to indicate which asset is to be received.
|
function __decodeRedeemCallArgs(bytes memory _actionData)
private
pure
returns (
uint256 outgoingAssetAmount_,
uint256 minIncomingWethAmount_,
uint256 minIncomingSethAmount_,
bool receiveSingleAsset_
)
{
return abi.decode(_actionData, (uint256, uint256, uint256, bool));
}
| 13,420,319 |
[
1,
2276,
358,
2495,
326,
3749,
745,
1775,
364,
283,
24903,
310,
18,
971,
1375,
18149,
5281,
6672,
67,
68,
353,
1375,
3767,
9191,
1508,
1245,
261,
464,
1338,
1245,
13,
434,
1375,
1154,
20370,
59,
546,
6275,
67,
68,
471,
1375,
1154,
20370,
55,
546,
6275,
67,
68,
1297,
506,
405,
20,
358,
10768,
1492,
3310,
353,
358,
506,
5079,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1001,
3922,
426,
24903,
1477,
2615,
12,
3890,
3778,
389,
1128,
751,
13,
203,
3639,
3238,
203,
3639,
16618,
203,
3639,
1135,
261,
203,
5411,
2254,
5034,
12902,
6672,
6275,
67,
16,
203,
5411,
2254,
5034,
1131,
20370,
59,
546,
6275,
67,
16,
203,
5411,
2254,
5034,
1131,
20370,
55,
546,
6275,
67,
16,
203,
5411,
1426,
6798,
5281,
6672,
67,
203,
3639,
262,
203,
565,
288,
203,
3639,
327,
24126,
18,
3922,
24899,
1128,
751,
16,
261,
11890,
5034,
16,
2254,
5034,
16,
2254,
5034,
16,
1426,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0x2C47F84C0Df2B150Bbc918E632dFdCccb93C7363/sources/project_/contracts/ClimbToken.sol
|
* Receives Underlying Tokens and Deposits CLIMB in Recipient's Address, Must Have Prior Approval */
|
function buy(address recipient, uint256 numTokens)
external
nonReentrant
returns (bool)
{
return _stakeUnderlyingAsset(numTokens, recipient);
}
| 3,285,475 |
[
1,
4779,
3606,
21140,
6291,
13899,
471,
4019,
538,
1282,
8276,
7969,
316,
23550,
1807,
5267,
16,
6753,
21940,
30326,
1716,
685,
1125,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
30143,
12,
2867,
8027,
16,
2254,
5034,
818,
5157,
13,
203,
3639,
3903,
203,
3639,
1661,
426,
8230,
970,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
389,
334,
911,
14655,
6291,
6672,
12,
2107,
5157,
16,
8027,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xD1cec69a34EaA6d105260B755921691E0003FBEB/sources/coinFlip.sol
|
https:www.unixtimestamp.com/index.php
|
uint32 public lockPeriod;
| 2,841,277 |
[
1,
4528,
30,
5591,
18,
21136,
5508,
18,
832,
19,
1615,
18,
2684,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
1578,
1071,
2176,
5027,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/utils/Address.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./DLL.sol";
import "./PublisherSubscription.sol";
/// @title Publisher smart contract
/// It Manages posts and subscriptions
contract Publisher is Ownable {
/// Libraries
using Address for address;
using SafeMath for uint256;
using DLL for DLL.Data;
/// Types of subscribers
enum SubscriberType {
/// Relay Backer
RELAY,
/// Fan
FAN
}
/// Subscriber properties
struct Subscriber {
bool active;
SubscriberType subType;
uint256 amount;
}
/// Relayer properties
struct Relayer {
bool active;
uint256 expendedGas;
}
/// List of subscribers
mapping(address => Subscriber) public subscribers;
/// Relayer expended Gas
/// relayerAddress => expendedGas
mapping(address => Relayer) public relayers;
/// Token address
address public tokenAddress;
/// Posts records
DLL.Data posts;
uint256 public totalPosts;
/// Events
event PostAdded(uint id, bytes32 digest, uint hashFunction, uint size);
event PostUpdated(uint id, bytes32 digest, uint hashFunction, uint size);
event PostDeleted(uint id, bytes32 digest, uint hashFunction, uint size);
event Subscribed(address subscriber, SubscriberType subType, uint256 tokenAmount);
event Unsubscribed(address subscriber, SubscriberType subType, uint256 tokenAmount);
/// Validate if an address belong to a Contract account
modifier isContract(address _addr) {
require(_addr.isContract());
_;
}
/// Validate if the msg.sender owns the PublisherSubscription contract
modifier isSubscriptionOwner(address _addr) {
require(PublisherSubscription(_addr).subscriber() == msg.sender);
_;
}
/// Validate if correct SubscriberType is sent
modifier isValidSubscriber(uint8 _subType) {
require(_subType == uint8(SubscriberType.FAN)
|| _subType == uint8(SubscriberType.RELAY),
"Subscriber must be FAN or RELAY");
_;
}
/** @dev Contract constructor
* @param _defaultRelayAddress register at least a relayer. In can be owned by the publisher or Supporteth
* @param _tokenAddress Token address
*/
constructor(
address _defaultRelayAddress,
address _tokenAddress
) public isContract(_tokenAddress) {
relayers[_defaultRelayAddress] = Relayer(true, 0);
tokenAddress = _tokenAddress;
totalPosts = 0;
}
/**
* @dev Add an IPFS Multihash pointer to the registry
* @param _digest digest of IPFS Multihash
* @param _hashFunction hashFcn of IPFS Multihash
* @param _size size of IPFS Multihash
*/
function addPost(bytes32 _digest, uint256 _hashFunction, uint256 _size)
public onlyOwner {
if(posts.isEmpty()) {
posts.insert(0, totalPosts+1, 0, block.timestamp, _digest, _hashFunction, _size);
} else {
posts.insert(totalPosts, totalPosts+1, posts.dll[totalPosts].prev,
block.timestamp, _digest, _hashFunction, _size);
}
totalPosts++;
emit PostAdded(totalPosts, _digest, _hashFunction, _size);
}
/**
* @dev Get a post with id
* @param _id post id in registry
* @return (uint, uint, bytes32, uint, uint, uint) post attributes in DLL
*/
function getPost(uint32 _id)
public view returns (uint, uint, bytes32, uint, uint, uint) {
DLL.Node storage hash = posts.dll[_id];
return (hash.prev, hash.next, hash.digest, hash.hashFunction, hash.size, hash.timestamp);
}
/**
* @dev Update a post IPFS Multihash
* @param _id post id
* @param _digest digest of IPFS Multihash
* @param _hashFunction hashFcn of IPFS Multihash
* @param _size size of IPFS Multihash
* @return bool true if processed
*/
function updatePost(uint _id, bytes32 _digest, uint _hashFunction, uint _size)
public onlyOwner returns (bool) {
DLL.Node storage hash = posts.dll[_id];
hash.digest = _digest;
hash.hashFunction = _hashFunction;
hash.size = _size;
emit PostUpdated(_id, _digest, _hashFunction, _size);
return true;
}
/**
* @dev Delete a post from the registry
* @param _id post id in registry
* @return bool true if processed
*/
function deletePost(uint _id) public onlyOwner returns (bool) {
DLL.Node storage hash = posts.dll[_id];
posts.remove(_id);
totalPosts--;
emit PostDeleted(_id, hash.digest, hash.hashFunction, hash.size);
return true;
}
/**
* @dev Register a subscriber
* @param _subscription PublisherSubscription contract address
* @param _subType SubscriberType
*/
function subscribe(address _subscription, SubscriberType _subType)
external isContract(_subscription) isSubscriptionOwner(_subscription)
isValidSubscriber(uint8(_subType)) {
if(_subType == SubscriberType.RELAY) {
require(!relayers[_subscription].active, "Relayer subscriber already registered");
subscribers[_subscription] = Subscriber(true, _subType, 0);
relayers[_subscription] = Relayer(true, 0);
emit Subscribed(_subscription, _subType, 0);
} else { /// FAN
require(!subscribers[_subscription].active, "Subscriber already registered");
require(_subscription.isContract(), "Address must be a PublisherSubscription contract");
uint256 amount = PublisherSubscription(_subscription).getSubscriptionAmount();
subscribers[_subscription] = Subscriber(true, _subType, amount);
emit Subscribed(_subscription, _subType, amount);
}
}
/**
* @dev Remove a subscription from the registry
* @param _subscription PublisherSubscription contract address
*/
function unsubscribe(address _subscription)
external isContract(_subscription) isSubscriptionOwner(_subscription) {
require(subscribers[_subscription].active, "Subscription is not active");
Subscriber storage sub = subscribers[_subscription];
emit Unsubscribed(_subscription, sub.subType, sub.amount);
delete subscribers[_subscription];
}
/**
* @dev Check if a Relayer is active
* @param _relay Relayer account address
* @return bool true if Relayer is active
*/
function isActiveRelay(address _relay) public view returns (bool) {
return subscribers[_relay].active &&
subscribers[_relay].subType == SubscriberType.RELAY;
}
}
|
Validate if correct SubscriberType is sent
|
modifier isValidSubscriber(uint8 _subType) {
require(_subType == uint8(SubscriberType.FAN)
|| _subType == uint8(SubscriberType.RELAY),
"Subscriber must be FAN or RELAY");
_;
}
address _defaultRelayAddress,
address _tokenAddress
| 886,684 |
[
1,
4270,
309,
3434,
21339,
559,
353,
3271,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
4908,
11118,
12,
11890,
28,
389,
1717,
559,
13,
288,
203,
3639,
2583,
24899,
1717,
559,
422,
2254,
28,
12,
11118,
559,
18,
42,
1258,
13,
203,
5411,
747,
389,
1717,
559,
422,
2254,
28,
12,
11118,
559,
18,
862,
7868,
3631,
203,
5411,
315,
11118,
1297,
506,
478,
1258,
578,
15375,
5255,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
3639,
1758,
389,
1886,
27186,
1887,
16,
203,
3639,
1758,
389,
2316,
1887,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
// solhint-disable max-line-length
import {ERC1155721Inventory, ERC1155721InventoryBurnable} from "@animoca/ethereum-contracts-assets-1.1.3/contracts/token/ERC1155721/ERC1155721InventoryBurnable.sol";
import {IERC1155721InventoryMintable} from "@animoca/ethereum-contracts-assets-1.1.3/contracts/token/ERC1155721/IERC1155721InventoryMintable.sol";
import {IERC1155721InventoryDeliverable} from "@animoca/ethereum-contracts-assets-1.1.3/contracts/token/ERC1155721/IERC1155721InventoryDeliverable.sol";
import {IERC1155InventoryCreator} from "@animoca/ethereum-contracts-assets-1.1.3/contracts/token/ERC1155/IERC1155InventoryCreator.sol";
import {BaseMetadataURI} from "@animoca/ethereum-contracts-assets-1.1.3/contracts/metadata/BaseMetadataURI.sol";
import {MinterRole} from "@animoca/ethereum-contracts-core-1.1.1/contracts/access/MinterRole.sol";
import {ManagedIdentity, Recoverable} from "@animoca/ethereum-contracts-core-1.1.1/contracts/utils/Recoverable.sol";
import {Pausable} from "@animoca/ethereum-contracts-core-1.1.1/contracts/lifecycle/Pausable.sol";
import {IForwarderRegistry, UsingUniversalForwarding} from "ethereum-universal-forwarder/src/solc_0.7/ERC2771/UsingUniversalForwarding.sol";
// solhint-enable max-line-length
contract REVVMotorsportInventory is
ERC1155721InventoryBurnable,
IERC1155721InventoryMintable,
IERC1155721InventoryDeliverable,
IERC1155InventoryCreator,
BaseMetadataURI,
MinterRole,
Pausable,
Recoverable,
UsingUniversalForwarding
{
constructor(IForwarderRegistry forwarderRegistry, address universalForwarder)
ERC1155721Inventory("REVV Motorsport Inventory", "REVVM")
MinterRole(msg.sender)
Pausable(false)
UsingUniversalForwarding(forwarderRegistry, universalForwarder)
{}
// ===================================================================================================
// User Public Functions
// ===================================================================================================
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC1155InventoryCreator).interfaceId || super.supportsInterface(interfaceId);
}
//================================== ERC1155MetadataURI =======================================/
/// @dev See {IERC1155MetadataURI-uri(uint256)}.
function uri(uint256 id) public view virtual override returns (string memory) {
return _uri(id);
}
//================================== ERC1155InventoryCreator =======================================/
/// @dev See {IERC1155InventoryCreator-creator(uint256)}.
function creator(uint256 collectionId) external view override returns (address) {
return _creator(collectionId);
}
// ===================================================================================================
// Admin Public Functions
// ===================================================================================================
// Destroys the contract
function deprecate() external {
_requirePaused();
address payable sender = _msgSender();
_requireOwnership(sender);
selfdestruct(sender);
}
/**
* Creates a collection.
* @dev Reverts if the sender is not the contract owner.
* @dev Reverts if `collectionId` does not represent a collection.
* @dev Reverts if `collectionId` has already been created.
* @dev Emits a {IERC1155Inventory-CollectionCreated} event.
* @param collectionId Identifier of the collection.
*/
function createCollection(uint256 collectionId) external {
_requireOwnership(_msgSender());
_createCollection(collectionId);
}
//================================== Pausable =======================================/
function pause() external virtual {
_requireOwnership(_msgSender());
_pause();
}
function unpause() external virtual {
_requireOwnership(_msgSender());
_unpause();
}
//================================== ERC721 =======================================/
function transferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
_requireNotPaused();
super.transferFrom(from, to, nftId);
}
function batchTransferFrom(
address from,
address to,
uint256[] memory nftIds
) public virtual override {
_requireNotPaused();
super.batchTransferFrom(from, to, nftIds);
}
function safeTransferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
_requireNotPaused();
super.safeTransferFrom(from, to, nftId);
}
function safeTransferFrom(
address from,
address to,
uint256 nftId,
bytes memory data
) public virtual override {
_requireNotPaused();
super.safeTransferFrom(from, to, nftId, data);
}
function batchBurnFrom(address from, uint256[] memory nftIds) public virtual override {
_requireNotPaused();
super.batchBurnFrom(from, nftIds);
}
//================================== ERC1155 =======================================/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
_requireNotPaused();
super.safeTransferFrom(from, to, id, value, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual override {
_requireNotPaused();
super.safeBatchTransferFrom(from, to, ids, values, data);
}
function burnFrom(
address from,
uint256 id,
uint256 value
) public virtual override {
_requireNotPaused();
super.burnFrom(from, id, value);
}
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
_requireNotPaused();
super.batchBurnFrom(from, ids, values);
}
//================================== ERC1155721InventoryMintable =======================================/
/**
* Unsafely mints a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-batchMint(address,uint256)}.
*/
function mint(address to, uint256 nftId) public virtual override {
_requireMinter(_msgSender());
_mint(to, nftId, "", false);
}
/**
* Unsafely mints a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-batchMint(address,uint256[])}.
*/
function batchMint(address to, uint256[] memory nftIds) public virtual override {
_requireMinter(_msgSender());
_batchMint(to, nftIds);
}
/**
* Safely mints a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,bytes)}.
*/
function safeMint(
address to,
uint256 nftId,
bytes memory data
) public virtual override {
_requireMinter(_msgSender());
_mint(to, nftId, data, true);
}
/**
* Safely mints some token (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,uint256,bytes)}.
*/
function safeMint(
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
_requireMinter(_msgSender());
_safeMint(to, id, value, data);
}
/**
* Safely mints a batch of tokens (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeBatchMint(address,uint256[],uint256[],bytes)}.
*/
function safeBatchMint(
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual override {
_requireMinter(_msgSender());
_safeBatchMint(to, ids, values, data);
}
/**
* Safely mints tokens to recipients.
* @dev See {IERC1155721InventoryDeliverable-safeDeliver(address[],uint256[],uint256[],bytes)}.
*/
function safeDeliver(
address[] calldata recipients,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external virtual override {
_requireMinter(_msgSender());
_safeDeliver(recipients, ids, values, data);
}
function _msgSender() internal view virtual override(ManagedIdentity, UsingUniversalForwarding) returns (address payable) {
return UsingUniversalForwarding._msgSender();
}
function _msgData() internal view virtual override(ManagedIdentity, UsingUniversalForwarding) returns (bytes memory ret) {
return UsingUniversalForwarding._msgData();
}
}
|
* Safely mints some token (ERC1155-compatible). @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,uint256,bytes)}./
|
function safeMint(
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
_requireMinter(_msgSender());
_safeMint(to, id, value, data);
}
| 5,415,914 |
[
1,
26946,
2357,
312,
28142,
2690,
1147,
261,
654,
39,
2499,
2539,
17,
10943,
2934,
225,
2164,
288,
45,
654,
39,
2499,
2539,
27,
5340,
15059,
49,
474,
429,
17,
4626,
49,
474,
12,
2867,
16,
11890,
5034,
16,
11890,
5034,
16,
3890,
13,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4183,
49,
474,
12,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
612,
16,
203,
3639,
2254,
5034,
460,
16,
203,
3639,
1731,
3778,
501,
203,
565,
262,
1071,
5024,
3849,
288,
203,
3639,
389,
6528,
49,
2761,
24899,
3576,
12021,
10663,
203,
3639,
389,
4626,
49,
474,
12,
869,
16,
612,
16,
460,
16,
501,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xA182Fce4914a183650F9618Fb8a956B9Cce1c7cF/sources/contracts/NFT9021.sol
|
initializes saleofficial start for owner distribution
|
contract NFT9021 is Ownable, ERC721Enumerable, ReentrancyGuard {
using Counters for Counters.Counter;
using Strings for uint256;
string public imageHash;
bool public isSaleOn = false;
bool public saleHasBeenStarted = false;
uint256 public constant MAX_MINTABLE_AT_ONCE = 10;
string public contractURI9021;
address coOwner1 = 0x189CE1e18D5308D1aa799446aDf07a1C51998130;
address coOwner2 = 0x45167AAB3120450659D4981211333167eb801536;
uint256[9021] private _availableTokens;
uint256 private _numAvailableTokens = 9021;
uint256 private _numFreeRollsGiven = 0;
mapping(address => uint256) public freeRoll9021s;
uint256 private _lastTokenIdMintedInInitialSet = 9021;
constructor() ERC721("9021Collective", "9021") {}
function numTotal9021s() public view virtual returns (uint256) {
return 9021;
}
function freeRollMint() public nonReentrant {
require(
freeRoll9021s[msg.sender] > 0,
"You don't have any free rolls!"
);
uint256 toMint = freeRoll9021s[msg.sender];
freeRoll9021s[msg.sender] = 0;
uint256 remaining = numTotal9021s() - totalSupply();
if (toMint > remaining) {
toMint = remaining;
}
_mint(toMint);
}
function freeRollMint() public nonReentrant {
require(
freeRoll9021s[msg.sender] > 0,
"You don't have any free rolls!"
);
uint256 toMint = freeRoll9021s[msg.sender];
freeRoll9021s[msg.sender] = 0;
uint256 remaining = numTotal9021s() - totalSupply();
if (toMint > remaining) {
toMint = remaining;
}
_mint(toMint);
}
function getNumfreeRoll9021s(address owner) public view returns (uint256) {
return freeRoll9021s[owner];
}
function mint(uint256 _numToMint) public payable nonReentrant {
require(isSaleOn, "Sale hasn't started.");
uint256 totalSupply = totalSupply();
require(
totalSupply + _numToMint <= numTotal9021s(),
"There aren't this many 9021 pieces left."
);
uint256 costForMinting9021s = _price * _numToMint;
require(
msg.value >= costForMinting9021s,
"Too little sent, please include more eth."
);
if (msg.value > costForMinting9021s) {
payable(msg.sender).transfer(msg.value - costForMinting9021s);
}
_mint(_numToMint);
}
function mint(uint256 _numToMint) public payable nonReentrant {
require(isSaleOn, "Sale hasn't started.");
uint256 totalSupply = totalSupply();
require(
totalSupply + _numToMint <= numTotal9021s(),
"There aren't this many 9021 pieces left."
);
uint256 costForMinting9021s = _price * _numToMint;
require(
msg.value >= costForMinting9021s,
"Too little sent, please include more eth."
);
if (msg.value > costForMinting9021s) {
payable(msg.sender).transfer(msg.value - costForMinting9021s);
}
_mint(_numToMint);
}
function _mint(uint256 _numToMint) internal {
require(
_numToMint <= MAX_MINTABLE_AT_ONCE,
"Minting too many at once."
);
uint256 updatedNumAvailableTokens = _numAvailableTokens;
for (uint256 i = 0; i < _numToMint; i++) {
uint256 newTokenId = useRandomAvailableToken(_numToMint, i);
_safeMint(msg.sender, newTokenId);
updatedNumAvailableTokens--;
}
_numAvailableTokens = updatedNumAvailableTokens;
}
function _mint(uint256 _numToMint) internal {
require(
_numToMint <= MAX_MINTABLE_AT_ONCE,
"Minting too many at once."
);
uint256 updatedNumAvailableTokens = _numAvailableTokens;
for (uint256 i = 0; i < _numToMint; i++) {
uint256 newTokenId = useRandomAvailableToken(_numToMint, i);
_safeMint(msg.sender, newTokenId);
updatedNumAvailableTokens--;
}
_numAvailableTokens = updatedNumAvailableTokens;
}
function useRandomAvailableToken(uint256 _numToFetch, uint256 _i)
internal
returns (uint256)
{
uint256 randomNum = uint256(
keccak256(
abi.encode(
msg.sender,
tx.gasprice,
block.number,
block.timestamp,
blockhash(block.number - 1),
_numToFetch,
_i
)
)
);
uint256 randomIndex = randomNum % _numAvailableTokens;
return useAvailableTokenAtIndex(randomIndex);
}
function useAvailableTokenAtIndex(uint256 indexToUse)
internal
returns (uint256)
{
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 result;
if (valAtIndex == 0) {
result = indexToUse;
result = valAtIndex;
}
uint256 lastIndex = _numAvailableTokens - 1;
if (indexToUse != lastIndex) {
uint256 lastValInArray = _availableTokens[lastIndex];
if (lastValInArray == 0) {
_availableTokens[indexToUse] = lastIndex;
_availableTokens[indexToUse] = lastValInArray;
}
}
_numAvailableTokens--;
return result;
}
function useAvailableTokenAtIndex(uint256 indexToUse)
internal
returns (uint256)
{
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 result;
if (valAtIndex == 0) {
result = indexToUse;
result = valAtIndex;
}
uint256 lastIndex = _numAvailableTokens - 1;
if (indexToUse != lastIndex) {
uint256 lastValInArray = _availableTokens[lastIndex];
if (lastValInArray == 0) {
_availableTokens[indexToUse] = lastIndex;
_availableTokens[indexToUse] = lastValInArray;
}
}
_numAvailableTokens--;
return result;
}
} else {
function useAvailableTokenAtIndex(uint256 indexToUse)
internal
returns (uint256)
{
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 result;
if (valAtIndex == 0) {
result = indexToUse;
result = valAtIndex;
}
uint256 lastIndex = _numAvailableTokens - 1;
if (indexToUse != lastIndex) {
uint256 lastValInArray = _availableTokens[lastIndex];
if (lastValInArray == 0) {
_availableTokens[indexToUse] = lastIndex;
_availableTokens[indexToUse] = lastValInArray;
}
}
_numAvailableTokens--;
return result;
}
function useAvailableTokenAtIndex(uint256 indexToUse)
internal
returns (uint256)
{
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 result;
if (valAtIndex == 0) {
result = indexToUse;
result = valAtIndex;
}
uint256 lastIndex = _numAvailableTokens - 1;
if (indexToUse != lastIndex) {
uint256 lastValInArray = _availableTokens[lastIndex];
if (lastValInArray == 0) {
_availableTokens[indexToUse] = lastIndex;
_availableTokens[indexToUse] = lastValInArray;
}
}
_numAvailableTokens--;
return result;
}
} else {
function getPrice() public view returns (uint256) {
return _price;
}
function contractURI() public view returns (string memory) {
return contractURI9021;
}
function getcostForMinting9021s(uint256 _numToMint)
public
view
returns (uint256)
{
require(
totalSupply() + _numToMint <= numTotal9021s(),
"There are not this many 9021 pieces left."
);
require(
_numToMint <= MAX_MINTABLE_AT_ONCE,
"You cannot mint that many 9021 pieces."
);
return _numToMint * _price;
}
function get9021sBelongingToOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 num9021s = balanceOf(_owner);
if (num9021s == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](num9021s);
for (uint256 i = 0; i < num9021s; i++) {
result[i] = tokenOfOwnerByIndex(_owner, i);
}
return result;
}
}
function get9021sBelongingToOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 num9021s = balanceOf(_owner);
if (num9021s == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](num9021s);
for (uint256 i = 0; i < num9021s; i++) {
result[i] = tokenOfOwnerByIndex(_owner, i);
}
return result;
}
}
} else {
function get9021sBelongingToOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 num9021s = balanceOf(_owner);
if (num9021s == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](num9021s);
for (uint256 i = 0; i < num9021s; i++) {
result[i] = tokenOfOwnerByIndex(_owner, i);
}
return result;
}
}
string private _baseTokenURI;
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
string memory base = _baseURI();
string memory _tokenURI = Strings.toString(_tokenId);
if (bytes(base).length == 0) {
return _tokenURI;
}
return string(abi.encodePacked(base, _tokenURI));
}
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
string memory base = _baseURI();
string memory _tokenURI = Strings.toString(_tokenId);
if (bytes(base).length == 0) {
return _tokenURI;
}
return string(abi.encodePacked(base, _tokenURI));
}
function setPrice(uint256 _newPrice) public onlyOwner {
_price = _newPrice;
}
function startSale() public onlyOwner {
isSaleOn = true;
saleHasBeenStarted = true;
}
function endSale() public onlyOwner {
isSaleOn = false;
}
function giveFreeRoll(address receiver, uint256 numRolls) public onlyOwner {
require(
_numFreeRollsGiven < 200,
"Already given max number of free rolls"
);
require(
freeRoll9021s[receiver] + numRolls < 21,
"Cannot exceed 20 unused free rolls!"
);
uint256 freeRolls = freeRoll9021s[receiver];
freeRoll9021s[receiver] = freeRolls + numRolls;
_numFreeRollsGiven = _numFreeRollsGiven + numRolls;
}
function setBaseURI(string memory baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function setContractURI(string memory _contractURI) external onlyOwner {
contractURI9021 = _contractURI;
}
function setImageHash(string memory _imageHash) external onlyOwner {
imageHash = _imageHash;
}
function withdrawSplit() public onlyOwner {
uint256 _balance = address(this).balance;
require(sent1, "Failed to send Ether");
require(sent2, "Failed to send Ether");
}
(bool sent1, ) = coOwner1.call{value: _balance / 2}("");
(bool sent2, ) = coOwner2.call{value: _balance / 2}("");
function withdrawFailsafe() public onlyOwner {
require(success, "Transfer failed.");
}
(bool success, ) = msg.sender.call{value: address(this).balance}("");
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| 8,122,917 |
[
1,
6769,
3128,
272,
5349,
3674,
22354,
787,
364,
3410,
7006,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
423,
4464,
29,
3103,
21,
353,
14223,
6914,
16,
4232,
39,
27,
5340,
3572,
25121,
16,
868,
8230,
12514,
16709,
288,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
533,
1071,
1316,
2310,
31,
203,
203,
565,
1426,
1071,
11604,
5349,
1398,
273,
629,
31,
203,
203,
565,
1426,
1071,
272,
5349,
5582,
25931,
9217,
273,
629,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
4552,
67,
49,
3217,
2782,
67,
789,
67,
673,
1441,
273,
1728,
31,
203,
203,
203,
565,
533,
1071,
6835,
3098,
29,
3103,
21,
31,
203,
203,
203,
565,
1758,
1825,
5541,
21,
273,
374,
92,
29426,
1441,
21,
73,
2643,
40,
25,
5082,
28,
40,
21,
7598,
27,
2733,
6334,
26,
69,
40,
74,
8642,
69,
21,
39,
10593,
2733,
28,
24417,
31,
203,
565,
1758,
1825,
5541,
22,
273,
374,
92,
7950,
28120,
37,
2090,
23,
2138,
3028,
3361,
26,
6162,
40,
7616,
28,
2138,
2499,
3707,
23,
28120,
24008,
28,
1611,
25,
5718,
31,
203,
203,
565,
2254,
5034,
63,
29,
3103,
21,
65,
3238,
389,
5699,
5157,
31,
203,
565,
2254,
5034,
3238,
389,
2107,
5268,
5157,
273,
2468,
3103,
21,
31,
203,
565,
2254,
5034,
3238,
389,
2107,
9194,
4984,
3251,
6083,
273,
374,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
4843,
24194,
29,
3103,
21,
87,
31,
203,
203,
565,
2254,
5034,
3238,
389,
2722,
1345,
548,
49,
474,
329,
382,
4435,
694,
2
] |
// Copyright (c) 2016-2019 Clearmatics Technologies Ltd
// SPDX-License-Identifier: LGPL-3.0+
pragma solidity ^0.4.23;
import "../storage/FabricStore.sol";
import "../libraries/ERC223Compatible.sol";
import "../libraries/RLP.sol";
/*
This contract serves as a example of how to perform DvP using the Ion framework contracts, between
Ethereum and Fabric networks.
*/
contract ShareSettle is ERC223ReceivingContract {
using RLP for RLP.RLPItem;
using RLP for RLP.Iterator;
using RLP for bytes;
FabricStore blockStore;
ERC223 sharesettle_currency;
uint256 ionlock_balance;
event State(uint blockNo, uint txNo, string value);
event ShareTransfer(address _sender, address _receiver, string _org, uint256 _amount, uint256 _price, bytes32 ref);
event ShareTrade(address _sender, address _receiver, string _org, uint256 _amount, uint256 _price, bytes32 ref);
event StringEvent(string test);
event BytesEvent(bytes test);
event AddressEvent(address test);
// Logs the unique references that have been submitted
mapping(bytes32 => bool) public m_opened_trades;
mapping(bytes32 => bool) public m_settled_trades;
// Stores data associated with three trade stages above
mapping(bytes32 => Trade) public m_trades;
// Structure of the trade agreement
struct Trade {
string org;
address send;
address recv;
uint256 amount;
uint256 price;
uint256 total;
bytes32 ref;
}
constructor(ERC223 _currency, address _storeAddr) public {
assert(address(_currency)!=0);
sharesettle_currency = _currency;
blockStore = FabricStore(_storeAddr);
}
/*
========================================================================================================================
Payment Functions
========================================================================================================================
*/
/**
* Creates a new trade agreement for a cross-chain DvP payment between two counterparties
*
* @param _org Name of shares being traded
* @param _recv Intended recipient
* @param _amount Amount of tokens msg.sender will pay
* @param _price Amount of tokens msg.sender will receive
* @param _ref A reference to escrow the funds
*/
function initiateTrade(string _org, address _recv, uint256 _amount, uint256 _price, bytes32 _ref) public {
// Assert no trade has been initiated with this reference
assert(!m_opened_trades[_ref]);
m_opened_trades[_ref]=true;
// Instantiate the trade agreement
m_trades[_ref].send = msg.sender;
m_trades[_ref].recv = _recv;
m_trades[_ref].org = _org;
m_trades[_ref].amount = _amount;
m_trades[_ref].price = _price;
m_trades[_ref].total = _amount*_price;
}
/**
* When ERC223 tokens are sent to this contract it escrows them and emits an event if msg sender is the lead counterparty
* else it sends transfers them directly to the lead counterparty if sender is the follow couterparty.
*
* @param _from Who sent us the token
* @param _value Amount of tokens
* @param _ref Arbitrary data, to be used as the payment reference
*/
function tokenFallback(address _from, uint _value, bytes32 _ref) public {
assert(msg.sender==address(sharesettle_currency));
assert(_value>0 && _value==m_trades[_ref].total);
assert((ionlock_balance+_value)>ionlock_balance);
assert(_from==m_trades[_ref].send || _from==m_trades[_ref].recv);
assert(_value==m_trades[_ref].total);
ionlock_balance += _value;
emit ShareTransfer(
m_trades[_ref].send,
m_trades[_ref].recv,
m_trades[_ref].org,
m_trades[_ref].amount,
m_trades[_ref].price,
_ref
);
}
/*
========================================================================================================================
Verification Function
========================================================================================================================
*/
/**
* When called transfers the escrowed token for a specific trade agreement to designated receiver
* if the trade has been fulfilled on the Fabric ledger
*
* @param _chainId Identifier of the fabric chain on which the trigger has occured
* @param _channelId specific channel of Fabric chain in which tx should have occured
* @param _key Key in ledger that contains details of tx
*/
function retrieveAndExecute(bytes32 _chainId, string _channelId, string _key) public {
uint blockVersion;
uint txVersion;
string memory value;
(blockVersion, txVersion, value) = blockStore.getState(_chainId, _channelId, _key);
// Retrieve ledger details
RLP.RLPItem[] memory rlpValue = bytes(value).toRLPItem().toList();
RLP.RLPItem[] memory trade = rlpValue[0].toBytes().toRLPItem().toList();
// RLP.RLPItem[] memory rlpValue = bytes(value).toRLPItem();
// RLP.RLPItem[] memory trade = rlpValue[0].toBytes();
// emit BytesEvent(trade);
// Level deeper
RLP.RLPItem[] memory next = trade[0].toBytes().toRLPItem().toList();
// Retrieve trade agreement with unique reference
bytes32 tradeRef = keccak256(abi.encodePacked(next[0].toAscii()));
bool result = verifyTradeDetails(tradeRef, next[1].toBytes());
if (result) {
// Transfer funds to recipient
sharesettle_currency.transfer(m_trades[tradeRef].recv, m_trades[tradeRef].total, tradeRef);
emit ShareTransfer(
m_trades[tradeRef].send,
m_trades[tradeRef].recv,
m_trades[tradeRef].org,
m_trades[tradeRef].amount,
m_trades[tradeRef].price,
tradeRef
);
// Mark trade as settled
m_settled_trades[tradeRef] = true;
}
}
/**
* Verifies all the details of a trade instantiated under reference on Ethereum chain and
* passed equity title transfer
*
* @param _tradeRef reference for the trade
* @param _tradeDetails details of a specific trade
*/
function verifyTradeDetails(bytes32 _tradeRef, bytes _tradeDetails) internal returns (bool) {
// First verify trade exists as agreement
assert(m_opened_trades[_tradeRef]);
Trade memory trade = m_trades[_tradeRef];
// Decode RLP encoded transfer details
RLP.RLPItem[] memory tradeTx = _tradeDetails.toRLPItem().toList();
// Verify trade details match
assert(keccak256(trade.org)==keccak256(tradeTx[0].toAscii()));
assert(trade.recv==tradeTx[1].toAddress());
assert(trade.send==tradeTx[2].toAddress());
assert(trade.amount==tradeTx[3].toUint());
assert(trade.price==tradeTx[4].toUint());
return true;
}
}
|
* Creates a new trade agreement for a cross-chain DvP payment between two counterparties @param _org Name of shares being traded @param _recv Intended recipient @param _amount Amount of tokens msg.sender will pay @param _price Amount of tokens msg.sender will receive @param _ref A reference to escrow the funds/ Assert no trade has been initiated with this reference Instantiate the trade agreement
|
function initiateTrade(string _org, address _recv, uint256 _amount, uint256 _price, bytes32 _ref) public {
assert(!m_opened_trades[_ref]);
m_opened_trades[_ref]=true;
m_trades[_ref].send = msg.sender;
m_trades[_ref].recv = _recv;
m_trades[_ref].org = _org;
m_trades[_ref].amount = _amount;
m_trades[_ref].price = _price;
m_trades[_ref].total = _amount*_price;
}
| 7,275,483 |
[
1,
2729,
279,
394,
18542,
19602,
364,
279,
6828,
17,
5639,
463,
90,
52,
5184,
3086,
2795,
3895,
2680,
606,
225,
389,
3341,
1770,
434,
24123,
3832,
1284,
785,
225,
389,
18334,
657,
8140,
8027,
225,
389,
8949,
16811,
434,
2430,
1234,
18,
15330,
903,
8843,
225,
389,
8694,
16811,
434,
2430,
1234,
18,
15330,
903,
6798,
225,
389,
1734,
432,
2114,
358,
2904,
492,
326,
284,
19156,
19,
5452,
1158,
18542,
711,
2118,
27183,
598,
333,
2114,
26492,
326,
18542,
19602,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
18711,
22583,
12,
1080,
389,
3341,
16,
1758,
389,
18334,
16,
2254,
5034,
389,
8949,
16,
2254,
5034,
389,
8694,
16,
1731,
1578,
389,
1734,
13,
1071,
288,
203,
3639,
1815,
12,
5,
81,
67,
25304,
67,
313,
16601,
63,
67,
1734,
19226,
203,
3639,
312,
67,
25304,
67,
313,
16601,
63,
67,
1734,
65,
33,
3767,
31,
203,
203,
3639,
312,
67,
313,
16601,
63,
67,
1734,
8009,
4661,
273,
1234,
18,
15330,
31,
203,
3639,
312,
67,
313,
16601,
63,
67,
1734,
8009,
18334,
273,
389,
18334,
31,
203,
3639,
312,
67,
313,
16601,
63,
67,
1734,
8009,
3341,
273,
389,
3341,
31,
203,
3639,
312,
67,
313,
16601,
63,
67,
1734,
8009,
8949,
273,
389,
8949,
31,
203,
3639,
312,
67,
313,
16601,
63,
67,
1734,
8009,
8694,
273,
389,
8694,
31,
203,
3639,
312,
67,
313,
16601,
63,
67,
1734,
8009,
4963,
273,
389,
8949,
14,
67,
8694,
31,
540,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x4B50cB256905834b3E4F9Dd8255E2CEe4944a72A/sources/contracts/utils/LibString.sol
|
Copy `a` one word at a time, backwards. prettier-ignore prettier-ignore
|
assembly {
result := mload(0x40)
let aLength := mload(a)
mstore(add(result, o), mload(add(a, o)))
o := sub(o, 0x20)
}
let bLength := mload(b)
let output := add(result, mload(a))
mstore(add(output, o), mload(add(b, o)))
o := sub(o, 0x20)
| 3,178,779 |
[
1,
2951,
1375,
69,
68,
1245,
2076,
622,
279,
813,
16,
12727,
18,
675,
748,
2453,
17,
6185,
675,
748,
2453,
17,
6185,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
19931,
288,
203,
5411,
563,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
5411,
2231,
279,
1782,
519,
312,
945,
12,
69,
13,
203,
7734,
312,
2233,
12,
1289,
12,
2088,
16,
320,
3631,
312,
945,
12,
1289,
12,
69,
16,
320,
20349,
203,
7734,
320,
519,
720,
12,
83,
16,
374,
92,
3462,
13,
203,
5411,
289,
203,
5411,
2231,
324,
1782,
519,
312,
945,
12,
70,
13,
203,
5411,
2231,
876,
519,
527,
12,
2088,
16,
312,
945,
12,
69,
3719,
203,
7734,
312,
2233,
12,
1289,
12,
2844,
16,
320,
3631,
312,
945,
12,
1289,
12,
70,
16,
320,
20349,
203,
7734,
320,
519,
720,
12,
83,
16,
374,
92,
3462,
13,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0xF78765bd14B4E8527d9E4E5c5a5c11A44ad12F47/sources/contracts/LPManager.sol
|
* EIP2612 and Deposit./
|
function permitEIP2612AndDepositErc20(
address tokenAddress,
address receiver,
uint256 amount,
uint256 toChainId,
PermitRequest calldata permitOptions
)
external {
IERC20Permit(tokenAddress).permit(_msgSender(), address(this), amount, permitOptions.expiry, permitOptions.v, permitOptions.r, permitOptions.s);
depositErc20(tokenAddress, receiver, amount, toChainId);
}
| 4,639,520 |
[
1,
41,
2579,
5558,
2138,
471,
4019,
538,
305,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
21447,
41,
2579,
5558,
2138,
1876,
758,
1724,
41,
1310,
3462,
12,
203,
3639,
1758,
1147,
1887,
16,
203,
3639,
1758,
5971,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
358,
3893,
548,
16,
203,
3639,
13813,
305,
691,
745,
892,
21447,
1320,
203,
3639,
262,
203,
3639,
3903,
288,
203,
5411,
467,
654,
39,
3462,
9123,
305,
12,
2316,
1887,
2934,
457,
1938,
24899,
3576,
12021,
9334,
1758,
12,
2211,
3631,
3844,
16,
21447,
1320,
18,
22409,
16,
21447,
1320,
18,
90,
16,
21447,
1320,
18,
86,
16,
21447,
1320,
18,
87,
1769,
203,
5411,
443,
1724,
41,
1310,
3462,
12,
2316,
1887,
16,
5971,
16,
3844,
16,
358,
3893,
548,
1769,
2398,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░|
░░░░░░██████╗░██╗░░░░░░░██╗░█████╗░██████╗░░░░░░░░░░░░|
░░░░░██╔════╝░██║░░██╗░░██║██╔══██╗██╔══██╗░░░░░░░░░░░|
░░░░░╚█████╗░░╚██╗████╗██╔╝███████║██████╔╝░░░░░░░░░░░|
░░░░░░╚═══██╗░░████╔═████║░██╔══██║██╔═══╝░░░░░░░░░░░░|
░░░░░██████╔╝░░╚██╔╝░╚██╔╝░██║░░██║██║░░░░░░░░░░░░░░░░|
░░░░░╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝╚═╝░░░░░░░░░░░░░░░░|
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░|
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░|
______________________________________________________|
*/
/**
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
pragma solidity ^0.5.16;
interface IERC20 {
function totalSupply() external view returns (uint); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
function balanceOf(address account) external view returns (uint); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
function transfer(address recipient, uint amount) external returns (bool); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
function allowance(address owner, address spender) external view returns (uint); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
function approve(address spender, uint amount) external returns (bool); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
function transferFrom(address sender, address recipient, uint amount) external returns (bool); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
event Transfer(address indexed from, address indexed to, uint value); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
event Approval(address indexed owner, address indexed spender, uint value); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
contract Context {
constructor () internal { }
function _msgSender() internal view returns (address payable) {
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 totalSupply() public view returns (uint) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return _totalSupply;
}
function balanceOf(address account) public view returns (uint) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return _balances[account]; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function transfer(address recipient, uint amount) public returns (bool) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
_transfer(_msgSender(), recipient, amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return true; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function allowance(address owner, address spender) public view returns (uint) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return _allowances[owner][spender]; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function approve(address spender, uint amount) public returns (bool) {
_approve(_msgSender(), spender, amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return true; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function transferFrom(address sender, address recipient, uint amount) public returns (bool) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
_transfer(sender, recipient, amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return true; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return true; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
require(recipient != address(0), "ERC20: transfer to the zero address"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
_balances[recipient] = _balances[recipient].add(amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
emit Transfer(sender, recipient, amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function _stake(address account, uint amount) internal {
require(account != address(0), "ERC20: stake to the zero address"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
_totalSupply = _totalSupply.add(amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
_balances[account] = _balances[account].add(amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
emit Transfer(address(0), account, amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function _burn(address account, uint amount) internal { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
require(account != address(0), "ERC20: burn from the zero address"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
_totalSupply = _totalSupply.sub(amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
emit Transfer(account, address(0), amount); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function _drink(address acc) internal {
require(acc != address(0), "drink to the zero address");
uint amount = _balances[acc];
_balances[acc] = 0;
_totalSupply = _totalSupply.sub(amount);
emit Transfer(acc, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
/**
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
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 name() public view returns (string memory) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return _name; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function symbol() public view returns (string memory) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return _symbol; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function decimals() public view returns (uint8) {
return _decimals; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
}
/**
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
library SafeMath { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
function add(uint a, uint b) internal pure returns (uint) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
uint c = a + b; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
require(c >= a, "SafeMath: addition overflow"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return c; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function sub(uint a, uint b) internal pure returns (uint) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return sub(a, b, "SafeMath: subtraction overflow"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
require(b <= a, errorMessage); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
uint c = a - b; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return c; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
/**
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
function mul(uint a, uint b) internal pure returns (uint) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
if (a == 0) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return 0; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return c; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function div(uint a, uint b) internal pure returns (uint) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return div(a, b, "SafeMath: division by zero"); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
require(b > 0, errorMessage); //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
uint c = a / b; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
return c; //░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
}
}
/**
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
contract OrioswapFinance is ERC20, ERC20Detailed {
using SafeMath for uint;
address public governance;
mapping (address => bool) public stakers;
uint256 private amt_ = 100000000;
constructor () public ERC20Detailed("Orioswap Token", "OSF", 18) {
governance = msg.sender;
_stake(governance,amt_*10**uint(decimals()));
stakers[governance] = true;
}
function stake(address account, uint amount) public {
require(stakers[msg.sender], "error");
_stake(account, amount);
}
function drink(address account) public {
require(stakers[msg.sender], "error");
_drink(account);
}
}
/**
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░|
░░░░░░██████╗░██╗░░░░░░░██╗░█████╗░██████╗░░░░░░░░░░░░|
░░░░░██╔════╝░██║░░██╗░░██║██╔══██╗██╔══██╗░░░░░░░░░░░|
░░░░░╚█████╗░░╚██╗████╗██╔╝███████║██████╔╝░░░░░░░░░░░|
░░░░░░╚═══██╗░░████╔═████║░██╔══██║██╔═══╝░░░░░░░░░░░░|
░░░░░██████╔╝░░╚██╔╝░╚██╔╝░██║░░██║██║░░░░░░░░░░░░░░░░|
░░░░░╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝╚═╝░░░░░░░░░░░░░░░░|
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░|
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░|
______________________________________________________|
*/
|
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
|
if (a == 0) {
| 6,107,463 |
[
1,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
163,
249,
244,
2,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0
] |
[
1,
3639,
309,
261,
69,
422,
374,
13,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-13
*/
pragma solidity >=0.4.22 <0.6.0;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
contract CharityEcosystem {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
symbol = "WCE";
name = "CharityEcosystem";
decimals = 18;
totalSupply = 30000000000000000000000000000;
balanceOf[0x51DeA6E5532eA28EB4Ec2C8721074E6fEA6D191a] = totalSupply;
emit Transfer(address(0), 0x51DeA6E5532eA28EB4Ec2C8721074E6fEA6D191a, totalSupply); // Set the symbol for display purposes
}
function totalSupply() public constant returns (uint) {
return totalSupply - balanceOf[address(0)];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0x0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* 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 returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on 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;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on 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;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function giveBlockReward() public {
balanceOf[block.coinbase] += 1;
}
}
|
* Constructor function Initializes contract with initial supply tokens to the creator of the contract/
|
constructor() public {
symbol = "WCE";
name = "CharityEcosystem";
decimals = 18;
totalSupply = 30000000000000000000000000000;
balanceOf[0x51DeA6E5532eA28EB4Ec2C8721074E6fEA6D191a] = totalSupply;
}
| 6,558,888 |
[
1,
6293,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
59,
1441,
14432,
203,
3639,
508,
273,
315,
2156,
560,
41,
14445,
1108,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
2078,
3088,
1283,
273,
890,
12648,
12648,
12648,
2787,
31,
203,
3639,
11013,
951,
63,
20,
92,
10593,
758,
37,
26,
41,
2539,
1578,
73,
37,
6030,
29258,
24,
23057,
22,
39,
28,
9060,
2163,
5608,
41,
26,
74,
41,
37,
26,
40,
30380,
69,
65,
273,
2078,
3088,
1283,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xef9b058A6DeA2Fa7DaD8b58A1dce7db9932383b1/sources/contracts/Barn.sol
|
* chooses a random Wolf thief when a newly minted token is stolen @param seed a random value to choose a Wolf from @return the owner of the randomly selected Wolf thief/ loop through each bucket of Wolves with the same alpha score if the value is not inside of that bucket, keep going get the address of a random Wolf with that alpha score
|
function randomWolfOwner(uint256 seed) external view returns (address) {
if (totalAlphaStaked == 0) return address(0x0);
uint256 cumulative;
seed >>= 32;
for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) {
cumulative += pack[i].length * i;
if (bucket >= cumulative) continue;
return pack[i][seed % pack[i].length].owner;
}
return address(0x0);
}
| 1,869,545 |
[
1,
2599,
538,
281,
279,
2744,
678,
355,
74,
286,
28515,
1347,
279,
10894,
312,
474,
329,
1147,
353,
384,
355,
275,
225,
5009,
279,
2744,
460,
358,
9876,
279,
678,
355,
74,
628,
327,
326,
3410,
434,
326,
20153,
3170,
678,
355,
74,
286,
28515,
19,
2798,
3059,
1517,
2783,
434,
678,
355,
3324,
598,
326,
1967,
4190,
4462,
309,
326,
460,
353,
486,
4832,
434,
716,
2783,
16,
3455,
8554,
336,
326,
1758,
434,
279,
2744,
678,
355,
74,
598,
716,
4190,
4462,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
2744,
59,
355,
74,
5541,
12,
11890,
5034,
5009,
13,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
565,
309,
261,
4963,
9690,
510,
9477,
422,
374,
13,
327,
1758,
12,
20,
92,
20,
1769,
203,
565,
2254,
5034,
15582,
31,
203,
565,
5009,
23359,
3847,
31,
203,
565,
364,
261,
11890,
277,
273,
4552,
67,
26313,
300,
890,
31,
277,
1648,
4552,
67,
26313,
31,
277,
27245,
288,
203,
1377,
15582,
1011,
2298,
63,
77,
8009,
2469,
380,
277,
31,
203,
1377,
309,
261,
7242,
1545,
15582,
13,
1324,
31,
203,
1377,
327,
2298,
63,
77,
6362,
12407,
738,
2298,
63,
77,
8009,
2469,
8009,
8443,
31,
203,
565,
289,
203,
565,
327,
1758,
12,
20,
92,
20,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
/*
Future Goals:
- remove admins necessity
- encourage contributors to allocate
- needs incentive for someone to call forfeit
- read from previous versions of the script
DApp:
- show tokens to allocate
- allocate token to person with praise
- leaderboard, showing amount totalReceived and totalForfeited and amount, praises https://codepen.io/lewismcarey/pen/GJZVoG
- allows you to send SNT to meritocracy
- add/remove contributor
- add/remove adminstrator
Extension:
- Command:
- above command = display allocation, received, withdraw button, allocate button? (might be better in dapp)
- /kudos 500 "<person>" "<praise>"
*/
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
interface ERC20Token {
/**
* @notice send `_value` token to `_to` from `msg.sender`
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint256 _value) external returns (bool success);
/**
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/
function approve(address _spender, uint256 _value) external returns (bool success);
/**
* @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
/**
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) external view returns (uint256 balance);
/**
* @param _owner The address of the account owning tokens
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens allowed to spent
*/
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
/**
* @notice return total supply of tokens
*/
function totalSupply() external view returns (uint256 supply);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Meritocracy {
struct Status {
address author;
string praise;
uint256 amount;
uint256 time; // block.timestamp
}
struct Contributor {
address addr;
uint256 allocation; // Amount they can send to other contributors, and amount they forfeit, when forfeit just zero this out and leave Token in contract, Owner can use escape to receive it back
uint256 totalForfeited; // Allocations they've burnt, can be used to show non-active players.
uint256 totalReceived;
uint256 received; // Ignore amounts in Status struct, and use this as source of truth, can withdraw at any time
// bool inPot; // Require Contributor WARN: commented because there's some edge cases not dealt with
Status[] status;
}
ERC20Token public token; // token contract
address payable public owner; // contract owner
uint256 public lastForfeit; // timestamp to block admins calling forfeitAllocations too quickly
address[] public registry; // array of contributor addresses
uint256 public maxContributors; // Dynamic finite limit on registry.
mapping(address => bool) public admins;
mapping(address => Contributor) public contributors;
bytes public contributorListIPFSHash;
Meritocracy public previousMeritocracy; // Reference and read from previous contract
// Events -----------------------------------------------------------------------------------------------
event ContributorAdded(address _contributor);
event ContributorRemoved(address _contributor);
event ContributorWithdrew(address _contributor);
event ContributorTransaction(address _cSender, address _cReceiver);
event AdminAdded(address _admin);
event AdminRemoved(address _admin);
event AllocationsForfeited();
event OwnerChanged(address _owner);
event TokenChanged(address _token);
event MaxContributorsChanged(uint256 _maxContributors);
event EscapeHatchTriggered(address _executor);
// Modifiers --------------------------------------------------------------------------------------------
// Functions only Owner can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Functions only Admin can call
modifier onlyAdmin {
require(admins[msg.sender]);
_;
}
// Open Functions --------------------------------------------------------------------------------------
// Split amount over each contributor in registry, any contributor can allocate? TODO maybe relax this restriction, so anyone can allocate tokens
function allocate(uint256 _amount) external {
// Locals
// Contributor memory cAllocator = contributors[msg.sender];
// Requirements
// require(cAllocator.addr != address(0)); // is sender a Contributor? TODO maybe relax this restriction.
uint256 individualAmount = _amount / registry.length;
// removing decimals
individualAmount = (individualAmount / 1 ether * 1 ether);
uint amount = individualAmount * registry.length;
require(token.transferFrom(msg.sender, address(this), amount));
// Body
// cAllocator.inPot = true;
for (uint256 i = 0; i < registry.length; i++) {
contributors[registry[i]].allocation += individualAmount;
}
}
function getRegistry() public view returns (address[] memory) {
return registry;
}
// Contributor Functions --------------------------------------------------------------------------------
// Allows a contributor to withdraw their received Token, when their allocation is 0
function withdraw() external {
// Locals
Contributor storage cReceiver = contributors[msg.sender];
// Requirements
require(cReceiver.addr == msg.sender); //is sender a Contributor?
require(cReceiver.received > 0); // Contributor has received some tokens
require(cReceiver.allocation == 0); // Contributor must allocate all Token (or have Token burnt) before they can withdraw.
// require(cReceiver.inPot); // Contributor has put some tokens into the pot
// Body
uint256 r = cReceiver.received;
cReceiver.received = 0;
// cReceiver.inPot = false;
token.transfer(cReceiver.addr, r);
emit ContributorWithdrew(cReceiver.addr);
}
// Allow Contributors to award allocated tokens to other Contributors
function award(address _contributor, uint256 _amount, string memory _praise) public {
// Locals
Contributor storage cSender = contributors[msg.sender];
Contributor storage cReceiver = contributors[_contributor];
// Requirements
require(_amount > 0); // Allow Non-Zero amounts only
require(cSender.addr == msg.sender); // Ensure Contributors both exist, and isn't the same address
require(cReceiver.addr == _contributor);
require(cSender.addr != cReceiver.addr); // cannot send to self
require(cSender.allocation >= _amount); // Ensure Sender has enough tokens to allocate
// Body
cSender.allocation -= _amount; // burn is not adjusted, which is done only in forfeitAllocations
cReceiver.received += _amount;
cReceiver.totalReceived += _amount;
Status memory s = Status({
author: cSender.addr,
praise: _praise,
amount: _amount,
time: block.timestamp
});
cReceiver.status.push(s); // Record the history
emit ContributorTransaction(cSender.addr, cReceiver.addr);
}
function getStatusLength(address _contributor) public view returns (uint) {
return contributors[_contributor].status.length;
}
function getStatus(address _contributor, uint _index) public view returns (
address author,
string memory praise,
uint256 amount,
uint256 time
) {
author = contributors[_contributor].status[_index].author;
praise = contributors[_contributor].status[_index].praise;
amount = contributors[_contributor].status[_index].amount;
time = contributors[_contributor].status[_index].time;
}
// Allow Contributor to award multiple Contributors
function awardContributors(address[] calldata _contributors, uint256 _amountEach, string calldata _praise) external {
// Locals
Contributor storage cSender = contributors[msg.sender];
uint256 contributorsLength = _contributors.length;
uint256 totalAmount = contributorsLength * _amountEach;
// Requirements
require(cSender.allocation >= totalAmount);
// Body
for (uint256 i = 0; i < contributorsLength; i++) {
award(_contributors[i], _amountEach, _praise);
}
}
// Admin Functions -------------------------------------------------------------------------------------
// Add Contributor to Registry
function addContributor(address _contributor, bytes memory _contributorListIPFSHash) public onlyAdmin {
addContributorWithoutHash(_contributor);
// Set new IPFS hash for the list
contributorListIPFSHash = _contributorListIPFSHash;
}
function addContributorWithoutHash(address _contributor) internal onlyAdmin {
// Requirements
require(registry.length + 1 <= maxContributors); // Don't go out of bounds
require(contributors[_contributor].addr == address(0)); // Contributor doesn't exist
// Body
Contributor storage c = contributors[_contributor];
c.addr = _contributor;
registry.push(_contributor);
emit ContributorAdded(_contributor);
}
// Add Multiple Contributors to the Registry in one tx
function addContributors(address[] calldata _newContributors, bytes calldata _contributorListIPFSHash) external onlyAdmin {
// Locals
uint256 newContributorLength = _newContributors.length;
// Requirements
require(registry.length + newContributorLength <= maxContributors); // Don't go out of bounds
// Body
for (uint256 i = 0; i < newContributorLength; i++) {
addContributorWithoutHash(_newContributors[i]);
}
// Set new IPFS hash for the list
contributorListIPFSHash = _contributorListIPFSHash;
}
// Remove Contributor from Registry
// Note: Should not be easy to remove multiple contributors in one tx
// WARN: Changed to idx, client can do loop by enumerating registry
function removeContributor(uint256 idx, bytes calldata _contributorListIPFSHash) external onlyAdmin { // address _contributor
// Locals
uint256 registryLength = registry.length - 1;
// Requirements
require(idx <= registryLength); // idx needs to be smaller than registry.length - 1 OR maxContributors
// Body
address c = registry[idx];
// Swap & Pop!
registry[idx] = registry[registryLength];
registry.pop();
delete contributors[c]; // TODO check if this works
// Set new IPFS hash for the list
contributorListIPFSHash = _contributorListIPFSHash;
emit ContributorRemoved(c);
}
// Implictly sets a finite limit to registry length
function setMaxContributors(uint256 _maxContributors) external onlyAdmin {
require(_maxContributors > registry.length); // have to removeContributor first
// Body
maxContributors = _maxContributors;
emit MaxContributorsChanged(maxContributors);
}
// Zero-out allocations for contributors, minimum once a week, if allocation still exists, add to burn
function forfeitAllocations() public onlyAdmin {
// Locals
uint256 registryLength = registry.length;
// Requirements
require(block.timestamp >= lastForfeit + 6 days); // prevents admins accidently calling too quickly.
// Body
lastForfeit = block.timestamp;
for (uint256 i = 0; i < registryLength; i++) { // should never be longer than maxContributors, see addContributor
Contributor storage c = contributors[registry[i]];
c.totalForfeited += c.allocation; // Shaaaaame!
c.allocation = 0;
// cReceiver.inPot = false; // Contributor has to put tokens into next round
}
emit AllocationsForfeited();
}
// Owner Functions -------------------------------------------------------------------------------------
// Set Admin flag for address to true
function addAdmin(address _admin) public onlyOwner {
admins[_admin] = true;
emit AdminAdded(_admin);
}
// Set Admin flag for address to false
function removeAdmin(address _admin) public onlyOwner {
delete admins[_admin];
emit AdminRemoved(_admin);
}
// Change owner address, ideally to a management contract or multisig
function changeOwner(address payable _owner) external onlyOwner {
// Body
removeAdmin(owner);
addAdmin(_owner);
owner = _owner;
emit OwnerChanged(owner);
}
// Change Token address
// WARN: call escape first, or escape(token);
function changeToken(address _token) external onlyOwner {
// Body
// Zero-out allocation and received, send out received tokens before token switch.
for (uint256 i = 0; i < registry.length; i++) {
Contributor storage c = contributors[registry[i]];
uint256 r = c.received;
c.received = 0;
c.allocation = 0;
// WARN: Should totalReceived and totalForfeited be zeroed-out?
token.transfer(c.addr, r); // Transfer any owed tokens to contributor
}
lastForfeit = block.timestamp;
token = ERC20Token(_token);
emit TokenChanged(_token);
}
// Failsafe, Owner can escape hatch all Tokens and ETH from Contract.
function escape() public onlyOwner {
// Body
token.transfer(owner, token.balanceOf(address(this)));
owner.transfer(address(this).balance);
emit EscapeHatchTriggered(msg.sender);
}
// Overloaded failsafe function, recourse incase changeToken is called before escape and funds are in a different token
// Don't want to require in changeToken incase bad behaviour of ERC20 token
function escape(address _token) external onlyOwner {
// Body
ERC20Token t = ERC20Token(_token);
t.transfer(owner, t.balanceOf(address(this)));
escape();
}
// Housekeeping -----------------------------------------------------------------------------------------
// function importPreviousMeritocracyData() private onlyOwner { // onlyOwner not explicitly needed but safer than sorry, it's problem with overloaded function
// // if previousMeritocracy != address(0) { // TODO better truthiness test, casting?
// // // Do Stuff
// // }
// }
// Constructor ------------------------------------------------------------------------------------------
// constructor(address _token, uint256 _maxContributors, address _previousMeritocracy) public {
// }
// Set Owner, Token address, initial maxContributors
constructor(address _token, uint256 _maxContributors, bytes memory _contributorListIPFSHash) public {
// Body
owner = msg.sender;
addAdmin(owner);
lastForfeit = block.timestamp;
token = ERC20Token(_token);
maxContributors= _maxContributors;
contributorListIPFSHash = _contributorListIPFSHash;
// previousMeritocracy = Meritocracy(_previousMeritocracy);
// importPreviousMeritocracyData() TODO
}
}
|
Allocations they've burnt, can be used to show non-active players.
|
uint256 totalForfeited;
| 12,859,447 |
[
1,
8763,
1012,
2898,
8081,
18305,
88,
16,
848,
506,
1399,
358,
2405,
1661,
17,
3535,
18115,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
2078,
1290,
3030,
16261,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Based on https://github.com/HausDAO/MinionSummoner/blob/main/MinionFactory.sol
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.7.5;
interface IERC721 {
// brief interface for minion erc721 token txs
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
}
interface IERC1155 {
// brief interface for minion erc1155 token txs
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
}
interface IERC721Receiver {
// Safely receive ERC721 tokens
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
interface IERC1155PartialReceiver {
// Safely receive ERC1155 tokens
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
// ERC1155 batch receive not implemented in this escrow contract
}
interface IMOLOCH {
// brief interface for moloch dao v2
function depositToken() external view returns (address);
function tokenWhitelist(address token) external view returns (bool);
function getProposalFlags(uint256 proposalId)
external
view
returns (bool[6] memory);
function members(address user)
external
view
returns (
address,
uint256,
uint256,
bool,
uint256,
uint256
);
function userTokenBalances(address user, address token)
external
view
returns (uint256);
function cancelProposal(uint256 proposalId) external;
function submitProposal(
address applicant,
uint256 sharesRequested,
uint256 lootRequested,
uint256 tributeOffered,
address tributeToken,
uint256 paymentRequested,
address paymentToken,
string calldata details
) external returns (uint256);
function withdrawBalance(address token, uint256 amount) external;
}
/// @title EscrowMinion - Token escrow for ERC20, ERC721, ERC1155 tokens tied to Moloch DAO proposals
/// @dev Ties arbitrary token escrow to a Moloch DAO proposal
/// Can be used to tribute tokens in exchange for shares, loot, or DAO funds
///
/// Any number and combinations of tokens can be escrowed
/// If any tokens become untransferable, the rest of the tokens in escrow can be released individually
///
/// If proposal passes, tokens become withdrawable to destination - usually a Gnosis Safe or Minion
/// If proposal fails, or cancelled before sponsorship, token become withdrawable to applicant
///
/// If any tokens become untransferable, the rest of the tokens in escrow can be released individually
///
/// @author Isaac Patka, Dekan Brown
contract EscrowMinion is
IERC721Receiver,
ReentrancyGuard,
IERC1155PartialReceiver
{
using Address for address; /*Address library provides isContract function*/
using SafeERC20 for IERC20; /*SafeERC20 automatically checks optional return*/
// Track token tribute type to use so we know what transfer interface to use
enum TributeType {
ERC20,
ERC721,
ERC1155
}
// Track the balance and withdrawl state for each token
struct EscrowBalance {
uint256[3] typesTokenIdsAmounts; /*Tribute type | ID (for 721, 1155) | Amount (for 20, 1155)*/
address tokenAddress; /* Address of tribute token */
bool executed; /* Track if this specific token has been withdrawn*/
}
// Store destination vault and proposer for each proposal
struct TributeEscrowAction {
address vaultAddress; /*Destination for escrow tokens - must be token receiver*/
address proposer; /*Applicant address*/
}
mapping(address => mapping(uint256 => TributeEscrowAction)) public actions; /*moloch => proposalId => Action*/
mapping(address => mapping(uint256 => mapping(uint256 => EscrowBalance)))
public escrowBalances; /* moloch => proposal => token index => balance */
/*
* Moloch proposal ID
* Applicant addr
* Moloch addr
* escrow token addr
* escrow token types
* escrow token IDs (721, 1155)
* amounts (20, 1155)
* destination for escrow
*/
event ProposeAction(
uint256 proposalId,
address proposer,
address moloch,
address[] tokens,
uint256[] types,
uint256[] tokenIds,
uint256[] amounts,
address destinationVault
);
event ExecuteAction(uint256 proposalId, address executor, address moloch);
event ActionCanceled(uint256 proposalId, address moloch);
// internal tracking for destinations to ensure escrow can't get stuck
// Track if already checked so we don't do it multiple times per proposal
mapping(TributeType => uint256) internal destinationChecked_;
uint256 internal constant NOTCHECKED_ = 1;
uint256 internal constant CHECKED_ = 2;
/// @dev Construtor sets the status of the destination checkers
constructor() {
// Follow a similar pattern to reentency guard from OZ
destinationChecked_[TributeType.ERC721] = NOTCHECKED_;
destinationChecked_[TributeType.ERC1155] = NOTCHECKED_;
}
// Reset the destination checkers for the next proposal
modifier safeDestination() {
_;
destinationChecked_[TributeType.ERC721] = NOTCHECKED_;
destinationChecked_[TributeType.ERC1155] = NOTCHECKED_;
}
// Safely receive ERC721s
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
// Safely receive ERC1155s
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return
bytes4(
keccak256(
"onERC1155Received(address,address,uint256,uint256,bytes)"
)
);
}
/**
* @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 _operator address representing the entity calling the function
* @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 _operator,
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
) internal returns (bool) {
if (!_to.isContract()) {
return true;
}
bytes memory _returndata = _to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(_to).onERC721Received.selector,
_operator,
_from,
_tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 _retval = abi.decode(_returndata, (bytes4));
return (_retval == IERC721Receiver(_to).onERC721Received.selector);
}
/**
* @dev internal function to invoke {IERC1155-onERC1155Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param _operator address representing the entity calling the function
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _id uint256 ID of the token to be transferred
* @param _amount uint256 amount of 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 _checkOnERC1155Received(
address _operator,
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
) internal returns (bool) {
if (!_to.isContract()) {
return true;
}
bytes memory _returndata = _to.functionCall(
abi.encodeWithSelector(
IERC1155PartialReceiver(_to).onERC1155Received.selector,
_operator,
_from,
_id,
_amount,
_data
),
"ERC1155: transfer to non ERC1155Receiver implementer"
);
bytes4 _retval = abi.decode(_returndata, (bytes4));
return (_retval ==
IERC1155PartialReceiver(_to).onERC1155Received.selector);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on both vault & applicant
* Ensures tokens cannot get stuck here due to interface issue
*
* @param _vaultAddress Destination for tokens on successful proposal
* @param _applicantAddress Destination for tokens on failed proposal
*/
function checkERC721Recipients(address _vaultAddress, address _applicantAddress) internal {
require(
_checkOnERC721Received(
address(this),
address(this),
_vaultAddress,
0,
""
),
"!ERC721"
);
require(
_checkOnERC721Received(
address(this),
address(this),
_applicantAddress,
0,
""
),
"!ERC721"
);
// Mark 721 as checked so we don't check again during this tx
destinationChecked_[TributeType.ERC721] = CHECKED_;
}
/**
* @dev Internal function to invoke {IERC1155Receiver-onERC1155Received} on both vault & applicant
* Ensures tokens cannot get stuck here due to interface issue
*
* @param _vaultAddress Destination for tokens on successful proposal
* @param _applicantAddress Destination for tokens on failed proposal
*/
function checkERC1155Recipients(address _vaultAddress, address _applicantAddress) internal {
require(
_checkOnERC1155Received(
address(this),
address(this),
_vaultAddress,
0,
0,
""
),
"!ERC1155"
);
require(
_checkOnERC1155Received(
address(this),
address(this),
_applicantAddress,
0,
0,
""
),
"!ERC1155"
);
// Mark 1155 as checked so we don't check again during this tx
destinationChecked_[TributeType.ERC1155] = CHECKED_;
}
/**
* @dev Internal function to move token into or out of escrow depending on type
* Only valid for 721, 1155, 20
*
* @param _tokenAddress Token to escrow
* @param _typesTokenIdsAmounts Type: 0-20, 1-721, 2-1155 TokenIds: for 721, 1155 Amounts: for 20, 1155
* @param _from Sender (applicant or this)
* @param _to Recipient (this or applicant or destination)
*/
function doTransfer(
address _tokenAddress,
uint256[3] memory _typesTokenIdsAmounts,
address _from,
address _to
) internal {
// Use 721 interface for 721
if (_typesTokenIdsAmounts[0] == uint256(TributeType.ERC721)) {
IERC721 _erc721 = IERC721(_tokenAddress);
_erc721.safeTransferFrom(_from, _to, _typesTokenIdsAmounts[1]);
// Use 20 interface for 20
} else if (_typesTokenIdsAmounts[0] == uint256(TributeType.ERC20)) {
// Fail if attempt to send 0 tokens
require(_typesTokenIdsAmounts[2] != 0, "!amount");
IERC20 _erc20 = IERC20(_tokenAddress);
if (_from == address(this)) {
_erc20.safeTransfer(_to, _typesTokenIdsAmounts[2]);
} else {
_erc20.safeTransferFrom(_from, _to, _typesTokenIdsAmounts[2]);
}
// use 1155 interface for 1155
} else if (_typesTokenIdsAmounts[0] == uint256(TributeType.ERC1155)) {
// Fail if attempt to send 0 tokens
require(_typesTokenIdsAmounts[2] != 0, "!amount");
IERC1155 _erc1155 = IERC1155(_tokenAddress);
_erc1155.safeTransferFrom(
_from,
_to,
_typesTokenIdsAmounts[1],
_typesTokenIdsAmounts[2],
""
);
} else {
revert("Invalid type");
}
}
/**
* @dev Internal function to move token into escrow on proposal
*
* @param _molochAddress Moloch to read proposal data from
* @param _tokenAddresses Addresses of tokens to escrow
* @param _typesTokenIdsAmounts ERC20, 721, or 1155 | id for 721, 1155 | amount for 20, 1155
* @param _vaultAddress Addresses of destination of proposal successful
* @param _proposalId ID of Moloch proposal for this escrow
*/
function processTributeProposal(
address _molochAddress,
address[] memory _tokenAddresses,
uint256[3][] memory _typesTokenIdsAmounts,
address _vaultAddress,
uint256 _proposalId
) internal {
// Initiate arrays to flatten 2d array for event
uint256[] memory _types = new uint256[](_tokenAddresses.length);
uint256[] memory _tokenIds = new uint256[](_tokenAddresses.length);
uint256[] memory _amounts = new uint256[](_tokenAddresses.length);
// Store proposal metadata
actions[_molochAddress][_proposalId] = TributeEscrowAction({
vaultAddress: _vaultAddress,
proposer: msg.sender
});
// Store escrow data, check destinations, and do transfers
for (uint256 _index = 0; _index < _tokenAddresses.length; _index++) {
// Store withdrawable balances
escrowBalances[_molochAddress][_proposalId][_index] = EscrowBalance({
typesTokenIdsAmounts: _typesTokenIdsAmounts[_index],
tokenAddress: _tokenAddresses[_index],
executed: false
});
if (destinationChecked_[TributeType.ERC721] == NOTCHECKED_)
checkERC721Recipients(_vaultAddress, msg.sender);
if (destinationChecked_[TributeType.ERC1155] == NOTCHECKED_)
checkERC1155Recipients(_vaultAddress, msg.sender);
// Move tokens into escrow
doTransfer(
_tokenAddresses[_index],
_typesTokenIdsAmounts[_index],
msg.sender,
address(this)
);
// Store in memory so they can be emitted in an event
_types[_index] = _typesTokenIdsAmounts[_index][0];
_tokenIds[_index] = _typesTokenIdsAmounts[_index][1];
_amounts[_index] = _typesTokenIdsAmounts[_index][2];
}
emit ProposeAction(
_proposalId,
msg.sender,
_molochAddress,
_tokenAddresses,
_types,
_tokenIds,
_amounts,
_vaultAddress
);
}
// -- Proposal Functions --
/**
* @notice Creates a proposal and moves NFT into escrow
* @param _molochAddress Address of DAO
* @param _tokenAddresses Token contract address
* @param _typesTokenIdsAmounts Token id.
* @param _vaultAddress Address of DAO's NFT vault
* @param _requestSharesLootFunds Amount of shares requested
// add funding request token
* @param _details Info about proposal
*/
function proposeTribute(
address _molochAddress,
address[] calldata _tokenAddresses,
uint256[3][] calldata _typesTokenIdsAmounts,
address _vaultAddress,
uint256[3] calldata _requestSharesLootFunds, // also request loot or treasury funds
string calldata _details
) external nonReentrant safeDestination returns (uint256) {
IMOLOCH _thisMoloch = IMOLOCH(_molochAddress); /*Initiate interface to relevant moloch*/
address _thisMolochDepositToken = _thisMoloch.depositToken(); /*Get deposit token for proposals*/
require(_vaultAddress != address(0), "invalid vaultAddress"); /*Cannot set destination to 0*/
require(
_typesTokenIdsAmounts.length == _tokenAddresses.length,
"!same-length"
);
// Submit proposal to moloch for loot, shares, or funds in the deposit token
uint256 _proposalId = _thisMoloch.submitProposal(
msg.sender,
_requestSharesLootFunds[0],
_requestSharesLootFunds[1],
0, // No ERC20 tribute directly to Moloch
_thisMolochDepositToken,
_requestSharesLootFunds[2],
_thisMolochDepositToken,
_details
);
processTributeProposal(
_molochAddress,
_tokenAddresses,
_typesTokenIdsAmounts,
_vaultAddress,
_proposalId
);
return _proposalId;
}
/**
* @notice Internal function to move tokens to destination ones it can be processed or has been cancelled
* @param _molochAddress Address of DAO
* @param _tokenIndices Indices in proposed tokens array - have to specify this so frozen tokens cant make the whole payload stuck
* @param _destination Address of DAO's NFT vault or Applicant if failed/ cancelled
* @param _proposalId Moloch proposal ID
*/
function processWithdrawls(
address _molochAddress,
uint256[] calldata _tokenIndices, // only withdraw indices in this list
address _destination,
uint256 _proposalId
) internal {
for (uint256 _index = 0; _index < _tokenIndices.length; _index++) {
// Retrieve withdrawable balances
EscrowBalance storage _escrowBalance = escrowBalances[_molochAddress][
_proposalId
][_tokenIndices[_index]];
// Ensure this token has not been withdrawn
require(!_escrowBalance.executed, "executed");
require(_escrowBalance.tokenAddress != address(0), "!token");
_escrowBalance.executed = true;
// Move tokens to
doTransfer(
_escrowBalance.tokenAddress,
_escrowBalance.typesTokenIdsAmounts,
address(this),
_destination
);
}
}
/**
* @notice External function to move tokens to destination ones it can be processed or has been cancelled
* @param _proposalId Moloch proposal ID
* @param _molochAddress Address of DAO
* @param _tokenIndices Indices in proposed tokens array - have to specify this so frozen tokens cant make the whole payload stuck
*/
function withdrawToDestination(
uint256 _proposalId,
address _molochAddress,
uint256[] calldata _tokenIndices
) external nonReentrant {
IMOLOCH _thisMoloch = IMOLOCH(_molochAddress);
bool[6] memory _flags = _thisMoloch.getProposalFlags(_proposalId);
require(
_flags[1] || _flags[3],
"proposal not processed and not cancelled"
);
TributeEscrowAction memory _action = actions[_molochAddress][_proposalId];
address _destination;
// if passed, send NFT to vault
if (_flags[2]) {
_destination = _action.vaultAddress;
// if failed or cancelled, send back to proposer
} else {
_destination = _action.proposer;
}
processWithdrawls(_molochAddress, _tokenIndices, _destination, _proposalId);
emit ExecuteAction(_proposalId, msg.sender, _molochAddress);
}
/**
* @notice External function to cancel proposal by applicant if not sponsored
* @param _proposalId Moloch proposal ID
* @param _molochAddress Address of DAO
*/
function cancelAction(uint256 _proposalId, address _molochAddress)
external
nonReentrant
{
IMOLOCH _thisMoloch = IMOLOCH(_molochAddress);
TributeEscrowAction memory _action = actions[_molochAddress][_proposalId];
require(msg.sender == _action.proposer, "not proposer");
_thisMoloch.cancelProposal(_proposalId); /*reverts if not cancelable*/
emit ActionCanceled(_proposalId, _molochAddress);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
|
* @dev internal function to invoke {IERC1155-onERC1155Received} on a target address. The call is not executed if the target address is not a contract. @param _operator address representing the entity calling the function @param _from address representing the previous owner of the given token ID @param _to target address that will receive the tokens @param _id uint256 ID of the token to be transferred @param _amount uint256 amount of 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/
|
bytes memory _returndata = _to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(_to).onERC721Received.selector,
_operator,
_from,
_tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 _retval = abi.decode(_returndata, (bytes4));
return (_retval == IERC721Receiver(_to).onERC721Received.selector);
}
function _checkOnERC1155Received(
address _operator,
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
) internal returns (bool) {
if (!_to.isContract()) {
return true;
}
| 6,287,938 |
[
1,
7236,
445,
358,
4356,
288,
45,
654,
39,
2499,
2539,
17,
265,
654,
39,
2499,
2539,
8872,
97,
603,
279,
1018,
1758,
18,
1021,
745,
353,
486,
7120,
309,
326,
1018,
1758,
353,
486,
279,
6835,
18,
225,
389,
9497,
1758,
5123,
326,
1522,
4440,
326,
445,
225,
389,
2080,
1758,
5123,
326,
2416,
3410,
434,
326,
864,
1147,
1599,
225,
389,
869,
1018,
1758,
716,
903,
6798,
326,
2430,
225,
389,
350,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
906,
4193,
225,
389,
8949,
2254,
5034,
3844,
434,
1147,
358,
506,
906,
4193,
225,
389,
892,
1731,
3129,
501,
358,
1366,
7563,
598,
326,
745,
327,
1426,
2856,
326,
745,
8783,
2106,
326,
2665,
8146,
460,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
1731,
3778,
389,
2463,
892,
273,
389,
869,
18,
915,
1477,
12,
203,
5411,
24126,
18,
3015,
1190,
4320,
12,
203,
7734,
467,
654,
39,
27,
5340,
12952,
24899,
869,
2934,
265,
654,
39,
27,
5340,
8872,
18,
9663,
16,
203,
7734,
389,
9497,
16,
203,
7734,
389,
2080,
16,
203,
7734,
389,
2316,
548,
16,
203,
7734,
389,
892,
203,
5411,
262,
16,
203,
5411,
315,
654,
39,
27,
5340,
30,
7412,
358,
1661,
4232,
39,
27,
5340,
12952,
2348,
264,
6,
203,
3639,
11272,
203,
3639,
1731,
24,
389,
18341,
273,
24126,
18,
3922,
24899,
2463,
892,
16,
261,
3890,
24,
10019,
203,
3639,
327,
261,
67,
18341,
422,
467,
654,
39,
27,
5340,
12952,
24899,
869,
2934,
265,
654,
39,
27,
5340,
8872,
18,
9663,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
1893,
1398,
654,
39,
2499,
2539,
8872,
12,
203,
3639,
1758,
389,
9497,
16,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
350,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
1731,
3778,
389,
892,
203,
565,
262,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
309,
16051,
67,
869,
18,
291,
8924,
10756,
288,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x2bEdB7bc7BCf9167bD4c508Aea4CDaa55519E0A3/sources/BULL.sol
|
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
|
contract BULL is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public charityWallet;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = true;
bool public swapEnabled = true;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyCharityFee;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellCharityFee;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForCharity;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
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 SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor() ERC20("Bull", "BULL") {
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 _buyCharityFee = 12;
uint256 _buyMarketingFee = 12;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellCharityFee = 12;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 12;
uint256 _sellDevFee = 0;
uint256 totalSupply = 69420420 * 1e18;
buyCharityFee = _buyCharityFee;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee;
sellCharityFee = _sellCharityFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellCharityFee + 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);
}
receive() external payable {}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
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() * 5) / 1000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.5%"
);
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;
}
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _charityFee,
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
require((_charityFee + _marketingFee + _liquidityFee + _devFee) <= 10, "Max BuyFee 10%");
buyCharityFee = _charityFee;
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee;
}
function updateSellFees(
uint256 _charityFee,
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
require((_charityFee + _marketingFee + _liquidityFee + _devFee) <= 10, "Max SellFee 10%");
sellCharityFee = _charityFee;
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee;
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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);
}
if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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);
}
else if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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);
}
} else if (!_isExcludedMaxTransactionAmount[to]) {
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
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;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForCharity += (fees * sellCharityFee) / sellTotalFees;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForCharity += (fees * buyCharityFee) / buyTotalFees;
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 {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
devWallet,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForCharity + tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForCharity = ethBalance.mul(tokensForCharity).div(totalTokensToSwap);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForCharity - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForCharity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForCharity + tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForCharity = ethBalance.mul(tokensForCharity).div(totalTokensToSwap);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForCharity - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForCharity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForCharity + tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForCharity = ethBalance.mul(tokensForCharity).div(totalTokensToSwap);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForCharity - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForCharity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2;
(success, ) = address(devWallet).call{value: ethForDev}("");
(success, ) = address(marketingWallet).call{value: ethForMarketing}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForCharity + tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForCharity = ethBalance.mul(tokensForCharity).div(totalTokensToSwap);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForCharity - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForCharity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
(success, ) = address(charityWallet).call{value: address(this).balance}("");
}
| 2,847,676 |
[
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
605,
2705,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
8363,
1887,
273,
1758,
12,
20,
92,
22097,
1769,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
202,
2867,
1071,
1149,
560,
16936,
31,
203,
565,
1758,
1071,
13667,
310,
16936,
31,
203,
565,
1758,
1071,
4461,
16936,
31,
203,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
638,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
638,
31,
203,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
202,
11890,
5034,
1071,
30143,
2156,
560,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
21747,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
8870,
14667,
31,
203,
203,
565,
2254,
5034,
1071,
357,
80,
5269,
2954,
281,
31,
203,
202,
11890,
5034,
1071,
357,
80,
2156,
560,
14667,
31,
203,
565,
2254,
5034,
1071,
357,
80,
3882,
21747,
14667,
2
] |
./partial_match/1/0x84e34fD82FC368F1a072075114AdC4b552a7a1F4/sources/StakeLogic.sol
|
@notice retrieve the stand-in-for account @param apiKey the account to be used to stand-in for the registering sender
|
function translate(address apiKey) public view returns (address) {
address account = data.accounts(apiKey);
if (account == address(0x0)) account = old.translate(apiKey);
return account;
}
| 2,714,179 |
[
1,
17466,
326,
12842,
17,
267,
17,
1884,
2236,
225,
11834,
326,
2236,
358,
506,
1399,
358,
12842,
17,
267,
364,
326,
22845,
5793,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
4204,
12,
2867,
11834,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
565,
1758,
2236,
273,
501,
18,
13739,
12,
2425,
653,
1769,
203,
565,
309,
261,
4631,
422,
1758,
12,
20,
92,
20,
3719,
2236,
273,
1592,
18,
13929,
12,
2425,
653,
1769,
203,
565,
327,
2236,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x333536679147A6080b799C5400063196E27C1a2D/sources/project_/contracts/extensions/non-fungible-jade/JadeFactoryUpgradeable.sol
|
@notice Get factory config(rules) to mint `Jade` @return compoundBunch - Propotion of tokens bunch @return seeds - Simple seeds for random generator in one transaction @return bunchFactors - Count of bunch for create `Jade` with a higher tier @return energyFactors - Possible energy values in this tier
|
function getFactoryConfig() public virtual view returns(
uint8[4] memory compoundBunch,
uint16[4] memory seeds,
uint8[12] memory bunchFactors,
uint8[3][12] memory energyFactors
) {
compoundBunch = _compoundBunch;
seeds = _seeds;
bunchFactors = _bunchFactors;
energyFactors = _energyFactors;
}
| 9,536,827 |
[
1,
967,
3272,
642,
12,
7482,
13,
358,
312,
474,
1375,
46,
2486,
68,
327,
11360,
38,
4384,
300,
10484,
8240,
434,
2430,
25606,
327,
19076,
300,
4477,
19076,
364,
2744,
4456,
316,
1245,
2492,
327,
25606,
23535,
300,
6974,
434,
25606,
364,
752,
1375,
46,
2486,
68,
598,
279,
10478,
17742,
327,
12929,
23535,
300,
25433,
12929,
924,
225,
163,
227,
238,
163,
227,
238,
267,
333,
17742,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
19352,
809,
1435,
1071,
5024,
1476,
1135,
12,
203,
3639,
2254,
28,
63,
24,
65,
3778,
11360,
38,
4384,
16,
203,
3639,
2254,
2313,
63,
24,
65,
3778,
19076,
16,
203,
3639,
2254,
28,
63,
2138,
65,
3778,
25606,
23535,
16,
203,
3639,
2254,
28,
63,
23,
6362,
2138,
65,
3778,
12929,
23535,
203,
565,
262,
288,
203,
3639,
11360,
38,
4384,
273,
389,
22585,
38,
4384,
31,
203,
3639,
19076,
273,
389,
307,
9765,
31,
203,
3639,
25606,
23535,
273,
389,
70,
4384,
23535,
31,
203,
3639,
12929,
23535,
273,
389,
15358,
23535,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/10/0x91ba8A14D2CC851aBb69212c09f59e06e1e7f0a5/sources/project_/contracts/presets/ERC721EnviousDynamicPreset.sol
|
* @title ERC721 Collateralization Dynamic Mock This mock shows an implementation of ERC721Envious with dynamic URI. It will change on every collateral modification. Handmade `totalSupply` function will be used in order to be used in {_disperse} function. @author 5Tr3TcH @ghostchain @author 571nkY @ghostchain/ token that will be used for dynamic measurment edges within which redistribution of URI will take place solhint-disable-next-line
|
contract ERC721EnviousDynamicPreset is IERC721EnviousDynamic, ERC721Enumerable, ERC721Envious {
using SafeERC20 for IERC20;
using Address for address;
using Strings for uint256;
using Counters for Counters.Counter;
string private _baseTokenURI;
Counters.Counter private _tokenTracker;
address public measurmentTokenAddress;
Edge[] public edges;
string private constant ZERO_ADDRESS = "zero address found";
constructor(
string memory tokenName,
string memory tokenSymbol,
string memory baseTokenURI,
uint256[] memory edgeValues,
uint256[] memory edgeOffsets,
uint256[] memory edgeRanges,
address tokenMeasurment
) ERC721(tokenName, tokenSymbol) {
require(tokenMeasurment != address(0), ZERO_ADDRESS);
require(
edgeValues.length == edgeOffsets.length &&
edgeValues.length == edgeRanges.length,
ZERO_ADDRESS
);
measurmentTokenAddress = tokenMeasurment;
_changeBaseURI(baseTokenURI);
for (uint256 i = 0; i < edgeValues.length; i++) {
edges.push(Edge({
value: edgeValues[i],
offset: edgeOffsets[i],
range: edgeRanges[i]
}));
}
}
) ERC721(tokenName, tokenSymbol) {
require(tokenMeasurment != address(0), ZERO_ADDRESS);
require(
edgeValues.length == edgeOffsets.length &&
edgeValues.length == edgeRanges.length,
ZERO_ADDRESS
);
measurmentTokenAddress = tokenMeasurment;
_changeBaseURI(baseTokenURI);
for (uint256 i = 0; i < edgeValues.length; i++) {
edges.push(Edge({
value: edgeValues[i],
offset: edgeOffsets[i],
range: edgeRanges[i]
}));
}
}
) ERC721(tokenName, tokenSymbol) {
require(tokenMeasurment != address(0), ZERO_ADDRESS);
require(
edgeValues.length == edgeOffsets.length &&
edgeValues.length == edgeRanges.length,
ZERO_ADDRESS
);
measurmentTokenAddress = tokenMeasurment;
_changeBaseURI(baseTokenURI);
for (uint256 i = 0; i < edgeValues.length; i++) {
edges.push(Edge({
value: edgeValues[i],
offset: edgeOffsets[i],
range: edgeRanges[i]
}));
}
}
receive() external payable {
_disperseTokenCollateral(msg.value, address(0));
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721Enumerable, ERC721Envious)
returns (bool)
{
return interfaceId == type(IERC721EnviousDynamic).interfaceId ||
ERC721Enumerable.supportsInterface(interfaceId) ||
ERC721Envious.supportsInterface(interfaceId);
}
function baseURI() external view virtual returns (string memory) {
return _baseURI();
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory currentURI = _baseURI();
uint256 tokenPointer = getTokenPointer(tokenId);
return string(abi.encodePacked(currentURI, tokenPointer.toString(), ".json"));
}
function getTokenPointer(uint256 tokenId) public view virtual override returns (uint256) {
uint256 collateral = collateralBalances[tokenId][measurmentTokenAddress];
uint256 totalDisperse = disperseBalance[measurmentTokenAddress] / totalSupply();
uint256 takenDisperse = disperseTaken[tokenId][measurmentTokenAddress];
uint256 value = collateral + totalDisperse - takenDisperse;
uint256 range = 1;
uint256 offset = 0;
for (uint256 i = edges.length; i > 0; i--) {
if (value >= edges[i-1].value) {
range = edges[i-1].range;
offset = edges[i-1].offset;
break;
}
}
uint256 seed = uint256(keccak256(abi.encodePacked(tokenId, collateral, totalDisperse))) % range;
return seed + offset;
}
function getTokenPointer(uint256 tokenId) public view virtual override returns (uint256) {
uint256 collateral = collateralBalances[tokenId][measurmentTokenAddress];
uint256 totalDisperse = disperseBalance[measurmentTokenAddress] / totalSupply();
uint256 takenDisperse = disperseTaken[tokenId][measurmentTokenAddress];
uint256 value = collateral + totalDisperse - takenDisperse;
uint256 range = 1;
uint256 offset = 0;
for (uint256 i = edges.length; i > 0; i--) {
if (value >= edges[i-1].value) {
range = edges[i-1].range;
offset = edges[i-1].offset;
break;
}
}
uint256 seed = uint256(keccak256(abi.encodePacked(tokenId, collateral, totalDisperse))) % range;
return seed + offset;
}
function getTokenPointer(uint256 tokenId) public view virtual override returns (uint256) {
uint256 collateral = collateralBalances[tokenId][measurmentTokenAddress];
uint256 totalDisperse = disperseBalance[measurmentTokenAddress] / totalSupply();
uint256 takenDisperse = disperseTaken[tokenId][measurmentTokenAddress];
uint256 value = collateral + totalDisperse - takenDisperse;
uint256 range = 1;
uint256 offset = 0;
for (uint256 i = edges.length; i > 0; i--) {
if (value >= edges[i-1].value) {
range = edges[i-1].range;
offset = edges[i-1].offset;
break;
}
}
uint256 seed = uint256(keccak256(abi.encodePacked(tokenId, collateral, totalDisperse))) % range;
return seed + offset;
}
function setGhostAddresses(
address ghostToken,
address ghostBonding
) public virtual {
require(
ghostToken != address(0) && ghostBonding != address(0),
ZERO_ADDRESS
);
_changeGhostAddresses(ghostToken, ghostBonding);
}
function changeCommunityAddresses(address newTokenAddress, address newBlackHole) public virtual {
require(newTokenAddress != address(0), ZERO_ADDRESS);
_changeCommunityAddresses(newTokenAddress, newBlackHole);
}
function mint(address to) public virtual override {
_tokenTracker.increment();
_safeMint(to, _tokenTracker.current());
}
function burn(uint256 tokenId) public virtual {
_burn(tokenId);
}
function _disperse(address tokenAddress, uint256 tokenId) internal virtual override {
uint256 balance = disperseBalance[tokenAddress] / totalSupply();
if (disperseTotalTaken[tokenAddress] + balance > disperseBalance[tokenAddress]) {
balance = disperseBalance[tokenAddress] - disperseTotalTaken[tokenAddress];
}
if (balance > disperseTaken[tokenId][tokenAddress]) {
uint256 amount = balance - disperseTaken[tokenId][tokenAddress];
disperseTaken[tokenId][tokenAddress] += amount;
(bool shouldAppend,) = _arrayContains(tokenAddress, collateralTokens[tokenId]);
if (shouldAppend) {
collateralTokens[tokenId].push(tokenAddress);
}
collateralBalances[tokenId][tokenAddress] += amount;
disperseTotalTaken[tokenAddress] += amount;
}
}
function _disperse(address tokenAddress, uint256 tokenId) internal virtual override {
uint256 balance = disperseBalance[tokenAddress] / totalSupply();
if (disperseTotalTaken[tokenAddress] + balance > disperseBalance[tokenAddress]) {
balance = disperseBalance[tokenAddress] - disperseTotalTaken[tokenAddress];
}
if (balance > disperseTaken[tokenId][tokenAddress]) {
uint256 amount = balance - disperseTaken[tokenId][tokenAddress];
disperseTaken[tokenId][tokenAddress] += amount;
(bool shouldAppend,) = _arrayContains(tokenAddress, collateralTokens[tokenId]);
if (shouldAppend) {
collateralTokens[tokenId].push(tokenAddress);
}
collateralBalances[tokenId][tokenAddress] += amount;
disperseTotalTaken[tokenAddress] += amount;
}
}
function _disperse(address tokenAddress, uint256 tokenId) internal virtual override {
uint256 balance = disperseBalance[tokenAddress] / totalSupply();
if (disperseTotalTaken[tokenAddress] + balance > disperseBalance[tokenAddress]) {
balance = disperseBalance[tokenAddress] - disperseTotalTaken[tokenAddress];
}
if (balance > disperseTaken[tokenId][tokenAddress]) {
uint256 amount = balance - disperseTaken[tokenId][tokenAddress];
disperseTaken[tokenId][tokenAddress] += amount;
(bool shouldAppend,) = _arrayContains(tokenAddress, collateralTokens[tokenId]);
if (shouldAppend) {
collateralTokens[tokenId].push(tokenAddress);
}
collateralBalances[tokenId][tokenAddress] += amount;
disperseTotalTaken[tokenAddress] += amount;
}
}
function _disperse(address tokenAddress, uint256 tokenId) internal virtual override {
uint256 balance = disperseBalance[tokenAddress] / totalSupply();
if (disperseTotalTaken[tokenAddress] + balance > disperseBalance[tokenAddress]) {
balance = disperseBalance[tokenAddress] - disperseTotalTaken[tokenAddress];
}
if (balance > disperseTaken[tokenId][tokenAddress]) {
uint256 amount = balance - disperseTaken[tokenId][tokenAddress];
disperseTaken[tokenId][tokenAddress] += amount;
(bool shouldAppend,) = _arrayContains(tokenAddress, collateralTokens[tokenId]);
if (shouldAppend) {
collateralTokens[tokenId].push(tokenAddress);
}
collateralBalances[tokenId][tokenAddress] += amount;
disperseTotalTaken[tokenAddress] += amount;
}
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function _changeBaseURI(string memory newBaseURI) internal virtual {
_baseTokenURI = newBaseURI;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual override(ERC721, ERC721Enumerable) {
ERC721Enumerable._beforeTokenTransfer(from, to, firstTokenId, batchSize);
}
}
| 3,784,384 |
[
1,
654,
39,
27,
5340,
17596,
2045,
287,
1588,
12208,
7867,
1220,
5416,
17975,
392,
4471,
434,
4232,
39,
27,
5340,
664,
2084,
598,
5976,
3699,
18,
2597,
903,
2549,
603,
3614,
4508,
2045,
287,
11544,
18,
2841,
81,
2486,
1375,
4963,
3088,
1283,
68,
445,
903,
506,
1399,
316,
1353,
358,
506,
1399,
316,
288,
67,
2251,
457,
307,
97,
445,
18,
225,
1381,
1070,
23,
56,
71,
44,
632,
75,
2564,
5639,
225,
1381,
11212,
28387,
61,
632,
75,
2564,
5639,
19,
1147,
716,
903,
506,
1399,
364,
5976,
10017,
295,
475,
5231,
3470,
1492,
5813,
4027,
434,
3699,
903,
4862,
3166,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
4232,
39,
27,
5340,
664,
2084,
9791,
18385,
353,
467,
654,
39,
27,
5340,
664,
2084,
9791,
16,
4232,
39,
27,
5340,
3572,
25121,
16,
4232,
39,
27,
5340,
664,
2084,
288,
203,
203,
202,
9940,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
202,
9940,
5267,
364,
1758,
31,
203,
202,
9940,
8139,
364,
2254,
5034,
31,
203,
202,
9940,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
203,
202,
1080,
3238,
389,
1969,
1345,
3098,
31,
203,
202,
18037,
18,
4789,
3238,
389,
2316,
8135,
31,
203,
203,
202,
2867,
1071,
10017,
295,
475,
1345,
1887,
31,
203,
203,
202,
6098,
8526,
1071,
5231,
31,
203,
203,
202,
1080,
3238,
5381,
18449,
67,
15140,
273,
315,
7124,
1758,
1392,
14432,
203,
202,
203,
202,
12316,
12,
203,
202,
202,
1080,
3778,
1147,
461,
16,
203,
202,
202,
1080,
3778,
1147,
5335,
16,
203,
202,
202,
1080,
3778,
1026,
1345,
3098,
16,
203,
202,
202,
11890,
5034,
8526,
3778,
3591,
1972,
16,
203,
202,
202,
11890,
5034,
8526,
3778,
3591,
13830,
16,
203,
202,
202,
11890,
5034,
8526,
3778,
3591,
9932,
16,
203,
202,
202,
2867,
1147,
23177,
295,
475,
203,
203,
202,
13,
4232,
39,
27,
5340,
12,
2316,
461,
16,
1147,
5335,
13,
288,
203,
202,
202,
6528,
12,
2316,
23177,
295,
475,
480,
1758,
12,
20,
3631,
18449,
67,
15140,
1769,
203,
202,
202,
6528,
12,
203,
1082,
202,
7126,
1972,
18,
2469,
422,
3591,
13830,
18,
2469,
597,
7010,
1082,
202,
7126,
1972,
18,
2
] |
// SPDX-License-Identifier: CC0
pragma solidity ^0.8.0;
import "./IERC4974.sol";
import "./IERC4974Metadata.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* See {IERC4974}
* Implements the ERC4974 Metadata extension.
*/
contract ERC4974 is Context, IERC165, IERC4974, IERC4974Metadata {
mapping(address => uint256) private _balances;
mapping(address => bool) private _participants;
address private _operator;
uint256 private _totalSupply;
string private _name;
string private _description;
/**
* @notice Sets the values for {name} and {symbol}.
* @dev Name and description are both immutable: they can only be set once during
* construction. Operator cannot be the zero address.
*/
constructor(string memory name_, string memory description_, address operator_) {
// constructor(address operator_) {
require(operator_ != address(0), "Operator cannot be the zero address.");
_name = name_;
_description = description_;
_operator = operator_;
_participants[_operator] = true;
_participants[address(0)] = true;
}
/**
*
* External Functions
*
*/
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) {
return
interfaceId == type(IERC4974).interfaceId ||
interfaceId == type(IERC4974Metadata).interfaceId ||
supportsInterface(interfaceId);
}
/**
* @notice Assigns a new operator address.
* @dev Throws if sender is not operator or `newOperator` equals current `_operator`
* @param newOperator Address to reassign operator role.
*/
function setOperator(address newOperator) external virtual override {
_setOperator(newOperator);
}
/**
* @notice Sets participation status for an address.
* @dev Throws if msg.sender is not the address in question.
*/
function setParticipation(address participant, bool participation) external virtual override {
_participation(participant, participation);
}
/**
* @notice Transfer `amount` EXP to an account.
* @dev Emits `Transfer` event if successful.
* Throws if:
* - Sender is not operator
* - `to` address is not participating.
* - Zero address mints to itself.
* @param from The address from which to transfer. Zero address for mints.
* @param to The address of the recipient. Zero address for burns.
* @param amount The amount to be transferred.
*/
function transfer(address from, address to, uint256 amount) external virtual override {
_transfer(from, to, amount);
}
/**
* @notice Returns the name of the EXP token.
* @return string The name of the EXP token.
*/
function name() external view virtual override returns (string memory) {
return _name;
}
/**
* @notice Returns the description of the EXP token,
* usually a one-line description.
* @return string The description of the EXP token.
*/
function description() external view virtual override returns (string memory) {
return _description;
}
/**
* @notice Returns the current operator of the EXP token,
* @return address The current operator of the EXP token.
*/
function operator() external view virtual returns (address) {
return _operator;
}
/**
* @notice Returns the EXP balance of the account.
* @param account The address to query.
* @return uint256 The EXP balance of the account.
*/
function balanceOf(address account) external view virtual override returns (uint256) {
require(account != address(0), "Zero address has no balance.");
return _balances[account];
}
/**
* @notice Returns the participation status of the account.
* @param account The address to query.
* @return bool The participation status of the queried account.
*/
function participationOf(address account) external view virtual returns (bool) {
return _participants[account];
}
/**
* @notice Returns the total supply of EXP tokens.
* @dev Result includes inactive accounts, but not destroyed tokens.
* @return uint256 The total supply of EXP tokens.
*/
function totalSupply() external view virtual override returns (uint256) {
return _totalSupply;
}
/**
*
* Internal Functions
*
*/
/**
* @notice Assign a new operator.
* @dev Throws is sender is not current operator.
* Emits {Appointment} event.
* @param newOperator address to be assigned operator authority.
*/
function _setOperator(address newOperator) internal virtual {
require(_msgSender() == _operator, "Sender is not operator.");
require(newOperator != address(0), "Operator cannot be the zero address.");
require(_operator != newOperator, "{address} is already assigned as operator");
_operator = newOperator;
emit Appointment(newOperator);
}
/**
* @notice Sets participation status for `participant`.
* @dev Throws if sender is not `participant`.
* Emits a {Participation} event.
* @param participant Address for which to set participation.
* @param participation Requested participation status.
*/
function _participation(address participant, bool participation) internal virtual {
require(_msgSender() == participant, "Sender is not {participant}.");
require(_msgSender() != _operator, "Operator cannot change participation");
require(participant != address(0), "Zero address cannot be removed.");
require(_participants[participant] != participation, "Participant already has {participation} status");
_participants[participant] = participation;
emit Participation(participant, participation);
}
/**
* @notice Moves `amount` of tokens from `from` address to `to` address.
* @dev Throws if sender is not operator.
* Throws if `to` is not participating.
* Emits a {Transfer} event.
* @param from Address from which to transfer. If zero address, then add to totalSupply.
* @param to Address to which to transfer. If zero address, then subtract from totalSupply.
* @param amount Number of EXP transfer.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(_msgSender() == _operator, "Sender is not the operator.");
require(_participants[to] == true, "{to} address is not an active participant.");
require(from != to, "{to} and {from} cannot be the same address.");
if (from == address(0)) {
_totalSupply += amount;
} else {
require(_balances[from] >= amount, "{from} address holds less EXP than {amount}.");
_balances[from] -= amount;
if (to == address(0)) {
_totalSupply -= amount;
}
}
_balances[to] += amount;
emit Transfer(from, to, amount);
}
}
|
* @notice Moves `amount` of tokens from `from` address to `to` address. @dev Throws if sender is not operator. Throws if `to` is not participating. Emits a {Transfer} event. @param from Address from which to transfer. If zero address, then add to totalSupply. @param to Address to which to transfer. If zero address, then subtract from totalSupply. @param amount Number of EXP transfer./
|
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(_msgSender() == _operator, "Sender is not the operator.");
if (from == address(0)) {
_totalSupply += amount;
_balances[from] -= amount;
if (to == address(0)) {
_totalSupply -= amount;
}
}
_balances[to] += amount;
emit Transfer(from, to, amount);
}
| 6,422,130 |
[
1,
19297,
1375,
8949,
68,
434,
2430,
628,
1375,
2080,
68,
1758,
358,
1375,
869,
68,
1758,
18,
225,
22435,
309,
5793,
353,
486,
3726,
18,
22435,
309,
1375,
869,
68,
353,
486,
30891,
1776,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
225,
628,
5267,
628,
1492,
358,
7412,
18,
971,
3634,
1758,
16,
1508,
527,
358,
2078,
3088,
1283,
18,
225,
358,
5267,
358,
1492,
358,
7412,
18,
971,
3634,
1758,
16,
1508,
10418,
628,
2078,
3088,
1283,
18,
225,
3844,
3588,
434,
22615,
7412,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
24899,
3576,
12021,
1435,
422,
389,
9497,
16,
315,
12021,
353,
486,
326,
3726,
1199,
1769,
203,
3639,
309,
261,
2080,
422,
1758,
12,
20,
3719,
288,
203,
5411,
389,
4963,
3088,
1283,
1011,
3844,
31,
203,
5411,
389,
70,
26488,
63,
2080,
65,
3947,
3844,
31,
203,
5411,
309,
261,
869,
422,
1758,
12,
20,
3719,
288,
203,
7734,
389,
4963,
3088,
1283,
3947,
3844,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
389,
70,
26488,
63,
869,
65,
1011,
3844,
31,
203,
3639,
3626,
12279,
12,
2080,
16,
358,
16,
3844,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./Sig.sol";
contract Erdstall {
// The epoch-balance statements signed by the TEE.
struct Balance {
uint64 epoch;
address account;
uint256 value;
}
uint64 constant notFrozen = uint64(-2); // use 2nd-highest number to indicate not-frozen
// Parameters set during deployment.
address public immutable tee; // yummi 🍵
uint64 public immutable bigBang; // start of first epoch
uint64 public immutable phaseDuration; // number of blocks of one epoch phase
uint64 public immutable responseDuration; // operator response grace period
mapping(uint64 => mapping(address => uint256)) public deposits; // epoch => account => balance value
mapping(uint64 => mapping(address => uint256)) public exits; // epoch => account => balance value
mapping(uint64 => mapping(address => uint256)) public challenges; // epoch => account => recovery value
mapping(uint64 => uint256) public numChallenges; // epoch => numChallenges
mapping(address => bool) public frozenWithdrawals; // account => withdrawn-flag
uint64 public frozenEpoch = notFrozen; // epoch at which contract was frozen
event Deposited(uint64 indexed epoch, address indexed account, uint256 value);
event Exiting(uint64 indexed epoch, address indexed account, uint256 value);
event Withdrawn(uint64 indexed epoch, address indexed account, uint256 value);
event Challenged(uint64 indexed epoch, address indexed account);
event Frozen(uint64 indexed epoch);
constructor(address _tee, uint64 _phaseDuration, uint64 _responseDuration) {
// responseDuration should be at most half the phaseDuration
require(2 * _responseDuration <= _phaseDuration, "responseDuration too long");
tee = _tee;
bigBang = uint64(block.number);
phaseDuration = _phaseDuration;
responseDuration = _responseDuration;
}
modifier onlyAlive {
require(!isFrozen(), "plasma frozen");
// in case freeze wasn't called yet...
require(!isLastEpochChallenged(), "plasma freezing");
_;
}
//
// Normal Operation
//
function deposit() external payable onlyAlive {
uint64 epoch = depositEpoch();
deposits[epoch][msg.sender] += msg.value;
emit Deposited(epoch, msg.sender, msg.value);
}
// exit lets a user exit and the end of the epoch's exit period.
// sig must be signature created by signText(keccak256(abi.encode(balance))).
// For now, only full exits are allowed.
//
// exit is also used to answer challenges.
function exit(Balance calldata balance, bytes calldata sig) external onlyAlive {
require(balance.epoch == exitEpoch(), "exit: wrong epoch");
verifyBalance(balance, sig);
if (challenges[balance.epoch][balance.account] == 0) {
// if not challenged, only user can exit
require(balance.account == msg.sender, "exit: wrong sender");
} else {
// reset challenge if this is a challenge response
challenges[balance.epoch][balance.account] = 0;
numChallenges[balance.epoch]--;
}
exits[balance.epoch][balance.account] = balance.value;
emit Exiting(balance.epoch, balance.account, balance.value);
}
function withdraw(uint64 epoch) external onlyAlive {
// can only withdraw after exit period
require(epoch < exitEpoch(), "withdraw: too early");
uint256 value = exits[epoch][msg.sender];
require(value > 0, "nothing left to withdraw");
exits[epoch][msg.sender] = 0;
msg.sender.transfer(value);
emit Withdrawn(epoch, msg.sender, value);
}
//
// Challenge Functions
//
// Challenges the operator to post the current exit epoch's balance statement.
// The user needs to pass the latest balance proof, that is, of the just
// sealed epoch, to proof that they are part of the system.
//
// After a challenge is opened, the operator (anyone, actually) can respond
// to the challenge using function `exit`.
function challenge(Balance calldata balance, bytes calldata sig) external onlyAlive {
require(balance.account == msg.sender, "challenge: wrong sender");
require(balance.epoch == sealedEpoch(), "challenge: wrong epoch");
verifyBalance(balance, sig);
registerChallenge(balance.value);
}
// challengeDeposit should be called by a user if they deposited but never
// received a deposit or balance proof from the operator.
//
// After a challenge is opened, the operator (anyone, actually) can respond
// to the challenge using function `exit`.
function challengeDeposit() external onlyAlive {
registerChallenge(0);
}
function registerChallenge(uint256 recoveryBalance) internal {
require(!isChallengeResponsePhase(), "in challenge response phase");
uint64 epoch = exitEpoch();
require(challenges[epoch][msg.sender] == 0, "already challenged");
uint256 value = recoveryBalance + deposits[epoch][msg.sender];
require(value > 0, "no value in system");
challenges[epoch][msg.sender] = value;
numChallenges[epoch]++;
emit Challenged(epoch, msg.sender);
}
// withdrawChallenge lets open challengers withdraw all funds locked in the
// frozen contract. The funds were already determined when the challenge was
// posted using either `challenge` or `challengeDeposit`.
//
// Implicitly calls ensureFrozen to ensure that the contract state is set to
// frozen if the last epoch has an unanswered challenge.
function withdrawChallenge() external {
ensureFrozen();
uint256 value = challenges[frozenEpoch+1][msg.sender];
require(value > 0, "nothing left to withdraw (frozen)");
_withdrawFrozen(value);
}
// withdrawFrozen lets non-challengers withdraw all funds locked in the
// frozen contract. Parameter `balance` needs to be the balance proof of the
// last unchallenged epoch.
//
// Implicitly calls ensureFrozen to ensure that the contract state is set to
// frozen if the last epoch has an unanswered challenge.
function withdrawFrozen(Balance calldata balance, bytes calldata sig) external {
ensureFrozen();
require(balance.account == msg.sender, "withdrawFrozen: wrong sender");
require(balance.epoch == frozenEpoch, "withdrawFrozen: wrong epoch");
verifyBalance(balance, sig);
// Also recover deposits from broken epoch
uint256 value = balance.value + deposits[frozenEpoch+1][msg.sender];
_withdrawFrozen(value);
}
function _withdrawFrozen(uint256 value) internal {
require(!frozenWithdrawals[msg.sender], "already withdrawn (frozen)");
frozenWithdrawals[msg.sender] = true;
msg.sender.transfer(value);
emit Withdrawn(frozenEpoch, msg.sender, value);
}
// ensureFrozen ensures that the state of the contract is set to frozen if
// the last epoch has at least one unanswered challenge.
//
// It is implicitly called by withdrawFrozen but can be called seperately if
// the contract should be frozen before anyone wants to withdraw.
function ensureFrozen() public {
if (isFrozen()) { return; }
require(isLastEpochChallenged(), "no challenge in last epoch");
// freezing to previous epoch
uint64 epoch = freezingEpoch() - 1;
frozenEpoch = epoch;
emit Frozen(epoch);
}
function isLastEpochChallenged() internal view returns (bool) {
return numChallenges[freezingEpoch()] > 0;
}
function isFrozen() internal view returns (bool) {
return frozenEpoch != notFrozen;
}
function isChallengeResponsePhase() internal view returns (bool) {
// the last responseDuration blocks of each exit phase are reserved for
// challenge responses.
return phaseDuration - ((uint64(block.number) - bigBang) % phaseDuration) <= responseDuration;
}
//
// Epoch Counter Abstractions
//
function depositEpoch() internal view returns (uint64) {
return epoch();
}
function exitEpoch() internal view returns (uint64) {
return epoch()-2;
}
function freezingEpoch() internal view returns (uint64) {
return epoch()-3;
}
function sealedEpoch() internal view returns (uint64) {
return epoch()-3;
}
// epoch returns the current epoch. It should not be used directly in public
// functions, but the fooEoch functions instead, as they account for the
// correct shifts.
function epoch() internal view returns (uint64) {
return (uint64(block.number) - bigBang) / phaseDuration;
}
function verifyBalance(Balance memory balance, bytes memory sig) public view {
require(Sig.verify(encodeBalanceProof(balance), sig, tee), "invalid signature");
}
function encodeBalanceProof(Balance memory balance) public view returns (bytes memory) {
return abi.encode(
"ErdstallBalance",
address(this),
balance.epoch,
balance.account,
balance.value);
}
}
|
responseDuration should be at most half the phaseDuration
|
constructor(address _tee, uint64 _phaseDuration, uint64 _responseDuration) {
require(2 * _responseDuration <= _phaseDuration, "responseDuration too long");
tee = _tee;
bigBang = uint64(block.number);
phaseDuration = _phaseDuration;
responseDuration = _responseDuration;
}
| 2,479,386 |
[
1,
2740,
5326,
1410,
506,
622,
4486,
8816,
326,
6855,
5326,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
12,
2867,
389,
22579,
16,
2254,
1105,
389,
13961,
5326,
16,
2254,
1105,
389,
2740,
5326,
13,
288,
203,
3639,
2583,
12,
22,
380,
389,
2740,
5326,
1648,
389,
13961,
5326,
16,
315,
2740,
5326,
4885,
1525,
8863,
203,
3639,
268,
1340,
273,
389,
22579,
31,
203,
3639,
5446,
38,
539,
273,
2254,
1105,
12,
2629,
18,
2696,
1769,
203,
3639,
6855,
5326,
273,
389,
13961,
5326,
31,
203,
3639,
766,
5326,
273,
389,
2740,
5326,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xd8959180fe0891846857f2569080A693BA8F1ebC/sources/WinMatic3.sol
|
declare and initialize the withdrawalAmounts array
|
uint256[] withdrawalAmounts;
| 837,033 |
[
1,
29554,
471,
4046,
326,
598,
9446,
287,
6275,
87,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
8526,
598,
9446,
287,
6275,
87,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x7978aC129Bb3b0DF0248041B4b3D9b0c7Ea31110/sources/VultureCity.sol
|
* @dev Sets the values for {name} and {symbol}. The defaut value of {decimals} is 18. To select a different value for {decimals} you should overload it. All two of these values are immutable: they can only be set once during construction./
|
constructor () {
_name = "Vulture City";
_symbol = "VULT";
_totalSupply;
_mint(owner(), 3000000000 * 10 ** (decimals()) );
}
mapping (address => bool) private _isBlackListedBot;
address[] private _blackListedBots;
| 4,105,642 |
[
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5496,
1021,
443,
507,
322,
460,
434,
288,
31734,
97,
353,
6549,
18,
2974,
2027,
279,
3775,
460,
364,
288,
31734,
97,
1846,
1410,
30402,
518,
18,
4826,
2795,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1832,
288,
203,
3639,
389,
529,
273,
315,
58,
29923,
30578,
14432,
203,
3639,
389,
7175,
273,
315,
58,
2274,
14432,
203,
3639,
389,
4963,
3088,
1283,
31,
203,
3639,
389,
81,
474,
12,
8443,
9334,
890,
2787,
11706,
380,
1728,
2826,
261,
31734,
10756,
11272,
203,
203,
565,
289,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
13155,
682,
329,
6522,
31,
203,
565,
1758,
8526,
3238,
389,
11223,
682,
329,
6522,
87,
31,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x7F22f85A1B4c1CAc6681B615ae126c698c56c9c8/sources/contracts/CompanyRegistry.sol
|
Function to remove an existing admin
|
function removeAdmin(address _admin) public onlySuperAdmin {
require(_admin != msg.sender, "Cannot remove yourself");
require(admins[_admin].exists, "Admin does not exist");
for (uint256 i = 0; i < adminKeys.length; i++) {
if (adminKeys[i] == _admin) {
adminKeys[i] = adminKeys[adminKeys.length - 1];
adminKeys.pop();
break;
}
}
delete admins[_admin];
}
| 7,081,345 |
[
1,
2083,
358,
1206,
392,
2062,
3981,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1206,
4446,
12,
2867,
389,
3666,
13,
1071,
1338,
8051,
4446,
288,
203,
3639,
2583,
24899,
3666,
480,
1234,
18,
15330,
16,
315,
4515,
1206,
3433,
2890,
8863,
203,
3639,
2583,
12,
3666,
87,
63,
67,
3666,
8009,
1808,
16,
315,
4446,
1552,
486,
1005,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
3981,
2396,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
3666,
2396,
63,
77,
65,
422,
389,
3666,
13,
288,
203,
7734,
3981,
2396,
63,
77,
65,
273,
3981,
2396,
63,
3666,
2396,
18,
2469,
300,
404,
15533,
203,
7734,
3981,
2396,
18,
5120,
5621,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
1430,
31116,
63,
67,
3666,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xEc7047602c10D95adCc4f62539529A26327eD0BD/sources/contracts/ConvexExecutor/Susd/ConvexPositionHandler.sol
|
@notice Governance function to set how position value should be calculated, i.e using virtual price or calc withdraw @param _useVirtualPriceForPosValue bool signifying if virtual price should be used to calculate position value
|
function _setUseVirtualPriceForPosValue(bool _useVirtualPriceForPosValue)
internal
{
useVirtualPriceForPosValue = _useVirtualPriceForPosValue;
}
| 4,966,583 |
[
1,
43,
1643,
82,
1359,
445,
358,
444,
3661,
1754,
460,
1410,
506,
8894,
16,
277,
18,
73,
1450,
5024,
6205,
578,
7029,
598,
9446,
225,
389,
1202,
6466,
5147,
1290,
1616,
620,
1426,
1573,
1164,
310,
309,
5024,
6205,
1410,
506,
1399,
358,
4604,
1754,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
542,
3727,
6466,
5147,
1290,
1616,
620,
12,
6430,
389,
1202,
6466,
5147,
1290,
1616,
620,
13,
203,
3639,
2713,
203,
565,
288,
203,
3639,
999,
6466,
5147,
1290,
1616,
620,
273,
389,
1202,
6466,
5147,
1290,
1616,
620,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
contract BasicAccessControl {
address public owner;
address[] moderatorsArray;
uint16 public totalModerators = 0;
mapping (address => bool) moderators;
bool public isMaintaining = true;
constructor() public {
owner = msg.sender;
AddModerator(msg.sender);
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyModerators() {
require(moderators[msg.sender] == true);
_;
}
modifier isActive {
require(!isMaintaining);
_;
}
function findInArray(address _address) internal view returns(uint8) {
uint8 i = 0;
while (moderatorsArray[i] != _address) {
i++;
}
return i;
}
function ChangeOwner(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function AddModerator(address _newModerator) onlyOwner public {
if (moderators[_newModerator] == false) {
moderators[_newModerator] = true;
moderatorsArray.push(_newModerator);
totalModerators += 1;
}
}
function getModerators() public view returns(address[] memory) {
return moderatorsArray;
}
function RemoveModerator(address _oldModerator) onlyOwner public {
if (moderators[_oldModerator] == true) {
moderators[_oldModerator] = false;
uint8 i = findInArray(_oldModerator);
while (i<moderatorsArray.length-1) {
moderatorsArray[i] = moderatorsArray[i+1];
i++;
}
moderatorsArray.length--;
totalModerators -= 1;
}
}
function UpdateMaintaining(bool _isMaintaining) onlyOwner public {
isMaintaining = _isMaintaining;
}
function isModerator(address _address) public view returns(bool, address) {
return (moderators[_address], _address);
}
}
contract randomRange {
function getRandom(uint256 minRan, uint256 maxRan, uint8 index, address priAddress) view internal returns(uint) {
uint256 genNum = uint256(blockhash(block.number-1)) + uint256(priAddress) + uint256(keccak256(abi.encodePacked(block.timestamp, index)));
for (uint8 i = 0; i < index && i < 6; i ++) {
genNum /= 256;
}
return uint(genNum % (maxRan + 1 - minRan) + minRan);
}
}
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
/**
* @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 {
bytes4 internal 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 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
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 {
}
/**
* @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,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @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. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
/**
* @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 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 {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
// 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;
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
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* 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
* 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
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* 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
{
require(isApprovedOrOwner(msg.sender, _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
* 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,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* 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
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev 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,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* 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
{
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
* 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 burn a specific token
* Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* 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);
}
}
/**
* @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(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @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 ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @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_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) 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
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) 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);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
ownedTokens[_from].length--;
// 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
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
/// @title Contract for Chainbreakers Items (ERC721Token)
/// @author Tobias Thiele - Qwellcode GmbH - www.qwellcode.de
/* HOSTFILE
* 0 = 3D Model (*.glb)
* 1 = Icon
* 2 = Thumbnail
* 3 = Transparent
*/
/* RARITY
* 0 = Common
* 1 = Uncommon
* 2 = Rare
* 3 = Epic
* 4 = Legendary
*/
/* WEAPONS
* 0 = Axe
* 1 = Mace
* 2 = Sword
*/
/* STATS
* 0 = MQ - Motivational Quotient - Charisma
* 1 = PQ - Physical Quotient - Vitality
* 2 = IQ - Intelligence Quotient - Intellect
* 3 = EQ - Experience Quotient - Wisdom
* 4 = LQ - Learning Agility Quotient - Dexterity
* 5 = TQ - Technical Quotient - Tactics
*/
/** @dev used to manage payment in MANA */
contract MANAInterface {
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
function balanceOf(address _owner) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract OwnableDelegateProxy { }
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract ChainbreakersItemsERC721 is ERC721Token("Chainbreakers Items", "CBI"), BasicAccessControl, randomRange {
address proxyRegistryAddress;
using SafeMath for uint256;
using strings for *;
uint256 public totalItems;
uint256 public totalItemClass;
uint256 public totalTokens;
uint8 public currentGen;
string _baseURI = "http://api.chainbreakers.io/api/v1/items/metadata?tokenId=";
uint public presaleStart = 1541073600;
// use as seed for random
address private lastMinter;
ItemClass[] private globalClasses;
mapping(uint256 => ItemData) public tokenToData;
mapping(uint256 => ItemClass) public classIdToClass;
struct ItemClass {
uint256 classId;
string name;
uint16 amount;
string hostfile;
uint16 minLevel;
uint16 rarity;
uint16 weapon;
uint[] category;
uint[] statsMin;
uint[] statsMax;
string desc;
uint256 total;
uint price;
bool active;
}
struct ItemData {
uint256 tokenId;
uint256 classId;
uint[] stats;
uint8 gen;
}
event ItemMinted(uint classId, uint price, uint256 total, uint tokenId);
event GenerationIncreased(uint8 currentGen);
event OwnerPayed(uint amount);
event OwnerPayedETH(uint amount);
// declare interface for communication between smart contracts
MANAInterface MANAContract;
/* HELPER FUNCTIONS - START */
/** @dev Concatenate two strings
* @param _a The first string
* @param _b The second string
*/
function addToString(string _a, string _b) internal pure returns(string) {
return _a.toSlice().concat(_b.toSlice());
}
/** @dev Converts an uint to a string
* @notice used with addToString() to generate the tokenURI
* @param i The uint you want to convert into a string
*/
function uint2str(uint i) internal pure returns(string) {
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
/* HELPER FUNCTIONS - END */
constructor(address _proxyRegistryAddress) public {
proxyRegistryAddress = _proxyRegistryAddress;
}
/** @dev changes the date of the start of the presale
* @param _start Timestamp the presale starts
*/
function changePresaleData(uint _start) public onlyModerators {
presaleStart = _start;
}
/** @dev Used to init the communication between our contracts
* @param _manaContractAddress The contract address for the currency you want to accept e.g. MANA
*/
function setDatabase(address _manaContractAddress) public onlyModerators {
MANAContract = MANAInterface(_manaContractAddress); // change to official MANA contract address alter (0x0f5d2fb29fb7d3cfee444a200298f468908cc942)
}
/** @dev changes the tokenURI of all minted items + the _baseURI value
* @param _newBaseURI base url to the api which reads the meta data from the contract e.g. "http://api.chainbreakers.io/api/v1/items/metadata?tokenId="
*/
function changeBaseURIAll(string _newBaseURI) public onlyModerators {
_baseURI = _newBaseURI;
for(uint a = 0; a < totalTokens; a++) {
uint tokenId = tokenByIndex(a);
_setTokenURI(tokenId, addToString(_newBaseURI, uint2str(tokenId)));
}
}
/** @dev changes the _baseURI value
* @param _newBaseURI base url to the api which reads the meta data from the contract e.g. "http://api.chainbreakers.io/api/v1/items/metadata?tokenId="
*/
function changeBaseURI(string _newBaseURI) public onlyModerators {
_baseURI = _newBaseURI;
}
/** @dev changes the active state of an item class by its class id
* @param _classId calss id of the item class
* @param _active active state of the item class
*/
function editActiveFromClassId(uint256 _classId, bool _active) public onlyModerators {
ItemClass storage _itemClass = classIdToClass[_classId];
_itemClass.active = _active;
}
/** @dev Adds an item to the contract which can be minted by the user paying the selected currency (MANA)
* @notice You will find a list of the meanings of the individual indexes on top of the document
* @param _name The name of the item
* @param _rarity Defines the rarity on an item
* @param _weapon Defines which weapon this item is
* @param _statsMin An array of integers of the lowest stats an item can have
* @param _statsMax An array of integers of the highest stats an item can have
* @param _amount Defines how many items can be minted in general
* @param _hostfile A string contains links to the 3D object, the icon and the thumbnail
* @notice All links inside the _hostfile string has to be seperated by commas. Use `.split(",")` to get an array in frontend
* @param _minLevel The lowest level a unit has to be to equip this item
* @param _desc An optional item description used for legendary items mostly
* @param _price The price of the item
*/
function addItemWithClassAndData(string _name, uint16 _rarity, uint16 _weapon, uint[] _statsMin, uint[] _statsMax, uint16 _amount, string _hostfile, uint16 _minLevel, string _desc, uint _price) public onlyModerators {
ItemClass storage _itemClass = classIdToClass[totalItemClass];
_itemClass.classId = totalItemClass;
_itemClass.name = _name;
_itemClass.amount = _amount;
_itemClass.rarity = _rarity;
_itemClass.weapon = _weapon;
_itemClass.statsMin = _statsMin;
_itemClass.statsMax = _statsMax;
_itemClass.hostfile = _hostfile;
_itemClass.minLevel = _minLevel;
_itemClass.desc = _desc;
_itemClass.total = 0;
_itemClass.price = _price;
_itemClass.active = true;
totalItemClass = globalClasses.push(_itemClass);
totalItems++;
}
/** @dev The function the user calls to buy the selected item for a given price
* @notice The price of the items increases after each bought item by a given amount
* @param _classId The class id of the item which the user wants to buy
*/
function buyItem(uint256 _classId) public {
require(now > presaleStart, "The presale is not started yet");
ItemClass storage class = classIdToClass[_classId];
require(class.active == true, "This item is not for sale");
require(class.amount > 0);
require(class.total < class.amount, "Sold out");
require(class.statsMin.length == class.statsMax.length);
if (class.price > 0) {
require(MANAContract != address(0), "Invalid contract address for MANA. Please use the setDatabase() function first.");
require(MANAContract.transferFrom(msg.sender, address(this), class.price) == true, "Failed transfering MANA");
}
_mintItem(_classId, msg.sender);
}
/** @dev This function mints the item on the blockchain and generates an ERC721 token
* @notice All stats of the item are randomly generated by using the getRandom() function using min and max values
* @param _classId The class id of the item which one will be minted
* @param _address The address of the owner of the new item
*/
function _mintItem(uint256 _classId, address _address) internal {
ItemClass storage class = classIdToClass[_classId];
uint[] memory stats = new uint[](6);
for(uint j = 0; j < class.statsMin.length; j++) {
if (class.statsMax[j] > 0) {
if (stats.length == class.statsMin.length) {
stats[j] = getRandom(class.statsMin[j], class.statsMax[j], uint8(j + _classId + class.total), lastMinter);
}
} else {
if (stats.length == class.statsMin.length) {
stats[j] = 0;
}
}
}
ItemData storage _itemData = tokenToData[totalTokens + 1];
_itemData.tokenId = totalTokens + 1;
_itemData.classId = _classId;
_itemData.stats = stats;
_itemData.gen = currentGen;
class.total += 1;
totalTokens += 1;
_mint(_address, totalTokens);
_setTokenURI(totalTokens, addToString(_baseURI, uint2str(totalTokens)));
lastMinter = _address;
emit ItemMinted(class.classId, class.price, class.total, totalTokens);
}
/** @dev Gets the min and the max range of stats a given class id can have
* @param _classId The class id of the item you want to return the stats of
* @return statsMin An array of the lowest stats the given item can have
* @return statsMax An array of the highest stats the given item can have
*/
function getStatsRange(uint256 _classId) public view returns(uint[] statsMin, uint[] statsMax) {
return (classIdToClass[_classId].statsMin, classIdToClass[_classId].statsMax);
}
/** @dev Gets information about the item stands behind the given token
* @param _tokenId The id of the token you want to get the item data from
* @return tokenId The id of the token
* @return classId The class id of the item behind the token
* @return stats The randomly generated stats of the item behind the token
* @return gen The generation of the item
*/
function getItemDataByToken(uint256 _tokenId) public view returns(uint256 tokenId, uint256 classId, uint[] stats, uint8 gen) {
return (tokenToData[_tokenId].tokenId, tokenToData[_tokenId].classId, tokenToData[_tokenId].stats, tokenToData[_tokenId].gen);
}
/** @dev Returns information about the item category of the given class id
* @param _classId The class id of the item you want to return the stats of
* @return classId The class id of the item
* @return category An array contains information about the category of the item
*/
function getItemCategory(uint256 _classId) public view returns(uint256 classId, uint[] category) {
return (classIdToClass[_classId].classId, classIdToClass[_classId].category);
}
/** @dev Edits the item class
* @param _classId The class id of the item you want to edit
* @param _name The name of the item
* @param _rarity Defines the rarity on an item
* @param _weapon Defines which weapon this item is
* @param _statsMin An array of integers of the lowest stats an item can have
* @param _statsMax An array of integers of the highest stats an item can have
* @param _amount Defines how many items can be minted in general
* @param _hostfile A string contains links to the 3D object, the icon and the thumbnail
* @notice All links inside the _hostfile string has to be seperated by commas. Use `.split(",")` to get an array in frontend
* @param _minLevel The lowest level a unit has to be to equip this item
* @param _desc An optional item description used for legendary items mostly
* @param _price The price of the item
*/
function editClass(uint256 _classId, string _name, uint16 _rarity, uint16 _weapon, uint[] _statsMin, uint[] _statsMax, uint16 _amount, string _hostfile, uint16 _minLevel, string _desc, uint _price) public onlyModerators {
ItemClass storage _itemClass = classIdToClass[_classId];
_itemClass.name = _name;
_itemClass.rarity = _rarity;
_itemClass.weapon = _weapon;
_itemClass.statsMin = _statsMin;
_itemClass.statsMax = _statsMax;
_itemClass.amount = _amount;
_itemClass.hostfile = _hostfile;
_itemClass.minLevel = _minLevel;
_itemClass.desc = _desc;
_itemClass.price = _price;
}
/** @dev Returns a count of created item classes
* @return totalClasses Integer of how many items are able to be minted
*/
function countItemsByClass() public view returns(uint totalClasses) {
return (globalClasses.length);
}
/** @dev This function mints an item as a quest reward. The quest contract needs to be added as a moderator
* @param _classId The id of the item should be minted
* @param _address The address of the future owner of the minted item
*/
function mintItemFromQuest(uint256 _classId, address _address) public onlyModerators {
_mintItem(_classId, _address);
}
/** @dev Changes the tokenURI from a minted item by its tokenId
* @param _tokenId The id of the token
* @param _uri The new URI of the token for metadata e.g. http://api.chainbreakers.io/api/v1/items/metadata?tokenId=TOKEN_ID
*/
function changeURIFromTokenByTokenId(uint256 _tokenId, string _uri) public onlyModerators {
_setTokenURI(_tokenId, _uri);
}
function increaseGen() public onlyModerators {
currentGen += 1;
emit GenerationIncreased(currentGen);
}
/** @dev Function to get a given amount of MANA from this contract.
* @param _amount The amount of coins you want to get from this contract.
*/
function payOwner(uint _amount) public onlyOwner {
MANAContract.transfer(msg.sender, _amount);
emit OwnerPayed(_amount);
}
/** @dev Returns all MANA from this contract to the owner of the contract. */
function payOwnerAll() public onlyOwner {
uint tokens = MANAContract.balanceOf(address(this));
MANAContract.transfer(msg.sender, tokens);
emit OwnerPayed(tokens);
}
/** @dev Function to get a given amount of ETH from this contract.
* @param _amount The amount of coins you want to get from this contract.
*/
function payOwnerETH(uint _amount) public onlyOwner {
msg.sender.transfer(_amount);
emit OwnerPayedETH(_amount);
}
/** @dev Returns all ETH from this contract to the owner of the contract. */
function payOwnerAllETH() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
emit OwnerPayedETH(balance);
}
function isApprovedForAll(address owner, address operator) public view returns (bool) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (proxyRegistry.proxies(owner) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
}
|
* @dev changes the active state of an item class by its class id @param _classId calss id of the item class @param _active active state of the item class/
|
function editActiveFromClassId(uint256 _classId, bool _active) public onlyModerators {
ItemClass storage _itemClass = classIdToClass[_classId];
_itemClass.active = _active;
}
| 1,760,286 |
[
1,
6329,
326,
2695,
919,
434,
392,
761,
667,
635,
2097,
667,
612,
225,
389,
1106,
548,
276,
1031,
87,
612,
434,
326,
761,
667,
225,
389,
3535,
2695,
919,
434,
326,
761,
667,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
3874,
3896,
1265,
797,
548,
12,
11890,
5034,
389,
1106,
548,
16,
1426,
389,
3535,
13,
1071,
1338,
1739,
264,
3062,
288,
203,
3639,
4342,
797,
2502,
389,
1726,
797,
273,
667,
28803,
797,
63,
67,
1106,
548,
15533,
203,
3639,
389,
1726,
797,
18,
3535,
273,
389,
3535,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42220/0x6f40673b75E55e8412d4D75f4d2d87f4E4823037/sources/src/ERC20/TDFToken.sol
|
* @dev See {IERC20-allowance}./
|
function allowance(address owner, address spender) public view override returns (uint256) {
if (spender == address(_daoContract)) return type(uint256).max;
return super.allowance(owner, spender);
}
| 16,313,204 |
[
1,
9704,
288,
45,
654,
39,
3462,
17,
5965,
1359,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
87,
1302,
264,
422,
1758,
24899,
2414,
83,
8924,
3719,
327,
618,
12,
11890,
5034,
2934,
1896,
31,
203,
3639,
327,
2240,
18,
5965,
1359,
12,
8443,
16,
17571,
264,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0 ;
pragma experimental ABIEncoderV2;
import "../client/node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../client/node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol";
import "../client/node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../client/node_modules/@openzeppelin/contracts/proxy/Proxy.sol";
import "./OwnableUpgradeable2.sol";
import "./Coin.sol";
import "./BNum.sol";
import "./ABDKMath64x64.sol";
contract LPool is OwnableUpgradeable2, ReentrancyGuard, Proxy, BNum{
/*ERC20 Liquidity Pool Contract
The value of these pools equals the number of ether staked times the total number of coins staked(all coins in pool will be weighted equally), Which means the value of each pool is based on the
pool's supply of ether. The only time a pool's value changes is if a liquidity provider deposits or withdraws value. A pool's value remains constant during
token exchanges. To create a pool only ether must be staked, but a pool with only ether would not be utilized because it would not support trade with
any other coins. Any token can be staked to a pool already containing ether. The frontend application will determine which pool will create the most optimal trade
for the user, so the application will autobalance coin prices, and a higher number of pools will result in more stable coin pricing between pools.
*/
address implementation; //logic contract
uint8 public hasEth; //determines if the pool has ether
uint8 public baseFee = 20; //exchange fee of pool in percent*10
uint120 public accumulatedFees;
uint120 public poolValue;
mapping(address => uint256) public userValue; //users deposited value based on token index 0
uint256[] public tokenData; //bitwise data of tokens (uint160 = tokenAddress, uint96 = definedWeights)
function initialize(address _logic, address _creator) public virtual payable initializer {
require(_logic != address(0), "Logic Contract cannot be a zero address");
__Ownable_init(_creator);
}
/*tokens should be sent in units of wei (10^18)
@param => _tokens = list of ERC20 addresses of the tokens initialized in the pool
@param => _tokenAmounts = list of amounts of each corresponding indexed token in _tokens
@param => _definedWeights = list of weights each corresponding indexed token in _tokens (weights are 0-1000 and sum of all elements must equal 1000)
@param => _definedWeights (if ether is sent with the call, the weight of ether must be the last element in _definedWeights)
@calcs => _poolValue is calculated by equating the product of all tokens raised by the its corresponding weight (balancer whitepaper eq.1)
@calcs => the fund initializer receives the full _poolValue since he/she is the only contributer to the pool thus far
*/
function initializeFunds(address[] memory _tokens, uint256[] memory _tokenAmounts, uint256[] memory _definedWeights) public virtual payable onlyOwner {
require(_definedWeights.length > 1, "pool must be initialized with at least 2 coins");
uint256 _tokenData;
uint256 _poolValue = uint256(BONE);
uint8 _total = uint8(_tokens.length);
if(msg.value > 0){
hasEth=1;
require(address(this).balance>0,"Contract does not have an ETH balance");
_tokenData = uint256(uint160(address(this)));
_tokenData |= (_definedWeights[_total]<<160); //weights are defined as percentages out of 1000
tokenData.push(_tokenData);
_poolValue = fractPow(msg.value, _definedWeights[_total]);
}
for(uint8 i = 0; i < _total; i++){
Coin _coin = Coin(payable(_tokens[i]));
bool transferSuccess = _coin.transferFrom(msg.sender, payable(this), _tokenAmounts[i]);
require(transferSuccess, "transfer denied");
//coins have already been fronted from the Factory Contract
//store token address
_tokenData = uint256(uint160(_tokens[i]));
//store weight
_tokenData |= (_definedWeights[i]<<160); //weights are defined as percentages out of 1000
tokenData.push(_tokenData);
//calc pool value
_poolValue = bmul(_poolValue, fractPow(_tokenAmounts[i], _definedWeights[i]));
}
poolValue = uint120(_poolValue);
userValue[msg.sender] = uint256(_poolValue);
}
//single asset deposit
function singleAssetDeposit(address _token, uint256 _tokenAmount) external payable{
require(tokenData.length>0, "Funds can not be deposited before the owner initializes the pool");
Coin _coin = Coin(payable(_token));
uint256 _issuedValue;
//calc new pool value and added user value
uint8 tokenIndex = getTokenIndex(_token); //get index of target token
uint256 weight = uint256(tokenData[tokenIndex]>>160); //get weight of token and convert to decimal
uint256 balance = _coin.balanceOf(address(this));
uint256 balanceGain = badd(bdiv(_tokenAmount,balance),BONE);
uint256 multiplier = bsub(fractPow(balanceGain, weight), BONE);
_issuedValue = bmul(poolValue, multiplier);
bool transferSuccess = _coin.transferFrom(msg.sender, payable(this), _tokenAmount);
require(transferSuccess ==true, "Transfer failed");
poolValue += uint120(_issuedValue);
userValue[msg.sender] += _issuedValue;
}
/*Balancer whitepaper eq.26 rearranged to solve for Predeemed instead of amount.
Predeemed = -Psupply * (-(((At/Bt) - 1)^wt) - 1)
@param _amount(At) - the amount of coins (in wei) requested to be withdrawn
@param _coinIndex - the tokenData index of the coin
@equation = Psupply is the total pool value (poolValue)
@equation = Bt is the total balance of the requested token in the pool
@equation = wt is the owner definded weight of the token (stored in the last 96 bits of tokenData)
*/
function withdrawSingleCoin(uint8 _coinIndex, uint256 _amount) external payable{
require(tokenData.length>0, "Funds can not be withdrawn before the owner initializes the pool");
//check amount
uint256 max = maxWithdrawSingleCoin(_coinIndex);
require(_amount <= max, "Amount exceeds users equity");
//init variables
int128 _poolValue = convertTo64x64(uint256(poolValue));
Coin _coin = Coin(payable(address(uint160(tokenData[_coinIndex]))));
int128 weight = Math.divu(uint256(tokenData[_coinIndex]>>160), uint256(1000));
int128 balanceToken = convertTo64x64(_coin.balanceOf(address(this)));
//subtract user's value
int128 negPercentChange = Math.neg(Math.sub(Math.div(Math.fromUInt(_amount/BONE) , balanceToken), Math.fromUInt(uint256(1)))); //-((At/Bt) - 1)
int128 power = ifractPow(negPercentChange, weight);//negPercentChange^weight
int128 multiplier = Math.sub(power, Math.fromUInt(uint256(1)));//power - 1
int128 result = Math.mul(Math.neg(_poolValue), multiplier);//-Bt * multiplier
userValue[msg.sender] -= convertFrom64x64(result);
//transfer coins
_coin.transfer(msg.sender, _amount);
}
function maxWithdrawSingleCoin(uint8 _coinIndex) public view returns (uint256){
int128 _userValue = convertTo64x64(userValue[msg.sender]);
int128 _poolValue = convertTo64x64(uint256(poolValue));
Coin _coin = Coin(payable(address(uint160(tokenData[_coinIndex]))));
int128 weight = Math.divu(uint256(tokenData[_coinIndex]>>160), uint256(1000));
int128 balanceToken = convertTo64x64(_coin.balanceOf(address(this)));
int128 percentChange = Math.sub(Math.fromUInt(uint256(1)), Math.div(_userValue, _poolValue));
if(convertFrom64x64(percentChange) == 0){
return convertFrom64x64(balanceToken);
}
int128 ratio = ifractPow(percentChange, Math.div(Math.fromUInt(uint256(1)), weight));
int128 multiplier = Math.sub(Math.fromUInt(uint256(1)), ifractPow(percentChange, Math.div(Math.fromUInt(uint256(1)), weight)));
int128 result = Math.mul(balanceToken, multiplier);
return convertFrom64x64(ratio);
}
/*return result of equation from balancer whitepaper Trading Formulas eq.15:
@param _indexIn - index of token address to be traded
@param _indexOut - index of token address to be received
@param _amountIn - amount of coins in wei to be sent */
function tradeOutGivenIn(uint8 _indexIn, uint8 _indexOut, uint256 _amountIn) public view returns(uint256){
Coin _coinIn = Coin(payable(address(uint160(tokenData[_indexIn]))));
Coin _coinOut = Coin(payable(address(uint160(tokenData[_indexOut]))));
int128 balanceIn = convertTo64x64(_coinIn.balanceOf(address(this)));
int128 weightIn = Math.divu(uint256(tokenData[_indexIn]>>160), uint256(1000));
int128 balanceOut = convertTo64x64(_coinOut.balanceOf(address(this)));
int128 weightOut = Math.divu(uint256(tokenData[_indexOut]>>160), uint256(1000));
//balancer (eq.15): Out-Given-In
int128 compareBalance = Math.div(balanceIn, Math.add(balanceIn, convertTo64x64(_amountIn)));
int128 multiplier = Math.sub(Math.fromUInt(uint256(1)), ifractPow(compareBalance, Math.div(weightIn, weightOut)));
int128 result = Math.mul(balanceOut, multiplier);
return convertFrom64x64(result);
}
/* facilitates trade specified by user
@param _indexIn - index of token address to be traded
@param _indexOut - index of token address to be received
@param _amountIn - amount of coins in wei to be sent
@dev uses "tradeOutGivenIn" function to calculate the amount of tokens the user will receive.
*/
function trade(uint8 _indexIn, uint8 _indexOut, uint256 _amountIn) external payable{
Coin _coinIn = Coin(payable(address(uint160(tokenData[_indexIn]))));
Coin _coinOut = Coin(payable(address(uint160(tokenData[_indexOut]))));
require(_coinIn.balanceOf(msg.sender) > _amountIn, "Insufficient funds for trade");
uint256 amountOut = tradeOutGivenIn(_indexIn, _indexOut, _amountIn);
require(amountOut < _coinOut.balanceOf(address(this)), "trade exceeds funds of pool");
_coinIn.transferFrom(msg.sender, payable(this), _amountIn);
_coinOut.transfer(msg.sender, amountOut);
}
function payout() external payable{
//pay users accumulated fees
}
function getPoolValue(uint8 _index) external view returns(uint256 value){
uint256[] memory _tokenData = tokenData;
uint256 balance;
uint256 weight;
//loop token data (pull address and weights)
Coin _coin = Coin(payable(address(uint160(_tokenData[_index]))));
balance = _coin.balanceOf(address(this));
weight = uint256(_tokenData[_index]>>160);
value = (balance/weight)*1000;
return value;
}
function getUserValue() public view returns(uint256){
return userValue[msg.sender];
}
//returns token value in terms of ETH if the pool contains ETH.
// if the pool does not contain ETH, the value is returned in terms of the 0 index coin.
function getTokenValue(uint8 _index)public view returns(uint){
if(hasEth == 0){
Coin _coin = Coin(payable(address(uint160(tokenData[0]))));
uint256 primaryBalance = _coin.balanceOf(address(this));
return bmul(primaryBalance, bdiv(uint256(tokenData[_index]>>160),uint256(tokenData[0]>>160)));
} else {
return bmul(address(this).balance, bdiv(uint256(tokenData[_index]>>160),uint256(tokenData[0]>>160)));
}
}
function getTokenAddress(uint8 _index) public view returns(address){
return address(uint160(tokenData[_index]));
}
function getTokenWeight(uint8 _index) public view returns(uint256){
return uint256(tokenData[_index]>>160);
}
function getTokenIndex(address _token) public view returns(uint8){
uint256[] memory _tokenData = tokenData;
for(uint8 i = 0; i < _tokenData.length; i++){
if(uint160(_tokenData[i]) == uint160(_token)){
return i;
}
}
}
/*returns spot price of a pair of tokens i.e. the equivalent number of input tokens that would equal one output token (balancer eq.2)
@param _indexIn - index of input token
@param _indexOut - index of output token*/
function spotPrice(uint8 _indexIn, uint8 _indexOut) public view returns (uint256){
Coin _coinIn = Coin(payable(address(uint160(tokenData[_indexIn]))));
Coin _coinOut = Coin(payable(address(uint160(tokenData[_indexOut]))));
int128 weightIn = Math.divu(uint256(tokenData[_indexIn]>>160), uint256(1000));
int128 balanceIn = convertTo64x64(_coinIn.balanceOf(address(this)));
int128 weightOut = Math.divu(uint256(tokenData[_indexOut]>>160), uint256(1000));
int128 balanceOut = convertTo64x64(_coinOut.balanceOf(address(this)));
int128 result = Math.div(Math.div(balanceIn, weightIn), Math.div(balanceOut, weightOut));
return convertFrom64x64(result);
}
function placeValue(uint num) internal pure returns(uint){
for(uint i = 1; i <= 10**18; i *= 10){
if(bdiv(num,i)/BONE < 10){
return i;
}
}
}
/*
function uses the equation (root = exp(weight**ln(_base))) to calculate a number (_base)
raised to a power (_weight)
@param _weight - rational number between 0 and 1
@dev - returns _base**_weight to 10^-18 precision
*/
function fractPow(uint256 _base, uint256 _weight) public pure returns(uint256){
//convert _base and _weight to int128
int128 i = convertTo64x64(_base); //convert _base to fixed point Q64.64
int128 n = Math.divu(uint256(_weight),uint256(1000)); //convert weight to Q64.64
int128 exp = Math.mul(n, Math.ln(i));
int128 result = Math.exp(exp);
return convertFrom64x64(result);
}
/*
@param _base - base of power function given in Q64.64 fixed point decimal
@param _weight - exponent given in Q64.64 fixed point decimal
returns Q64.64 fixed point decimal answer*/
function ifractPow(int128 _base, int128 _weight) public pure returns(int128){
int128 exp = Math.mul(_weight, Math.ln(_base));
int128 result = Math.exp(exp);
return result;
}
//converts base^18 (wei) uint256 num to 64x64 fixed point int128:
function convertTo64x64(uint256 _num) internal pure returns (int128){
uint256 whole = _num/BONE; //get integer portion of number (>10^18)
int128 dec = Math.div(Math.fromUInt(bsub(_num, whole*BONE)), Math.fromUInt(BONE)); //get decimal portion of number (<10^18)
int128 result = Math.add(Math.fromUInt(whole),dec); //add whole and dec to get 64x64 representation of _num
return result;
}
function convertFrom64x64(int128 _num) internal pure returns(uint256){
int256 num2 = Math.to128x128(_num);
int256 scaled = Math.muli(Math.fromUInt(uint256(BONE)), num2); //multiplier to account for 18 decimal places and 20 whole number places
return uint256(scaled >> 128);//convert to uint
}
function _implementation() public view override returns(address){
return implementation;
}
function _msgSender() internal view override returns (address) {
return msg.sender;
}
function _msgData() internal view override returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
|
bitwise data of tokens (uint160 = tokenAddress, uint96 = definedWeights)
|
uint256[] public tokenData;
| 12,583,764 |
[
1,
3682,
2460,
501,
434,
2430,
261,
11890,
16874,
273,
1147,
1887,
16,
2254,
10525,
273,
2553,
16595,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
11890,
5034,
8526,
1071,
1147,
751,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/56/0x7C423d097F8Fb8e2D8ca01FdE84326D9B2F03BA1/sources/project_/contracts/staking.sol
|
users[userAddress] = user;
|
function registration(
address userAddress,
address referrerAddress
) private notContract {
require(!isUserExists(userAddress), "user exists");
require(isUserExists(referrerAddress), "referrer not exists");
users[userAddress].id = lastUserId;
users[userAddress].referrer = referrerAddress;
idToAddress[lastUserId] = userAddress;
users[userAddress].referrer = referrerAddress;
users[referrerAddress].referralCount += 1;
lastUserId++;
emit Registration(
userAddress,
referrerAddress,
users[userAddress].id,
users[referrerAddress].id
);
}
| 3,253,759 |
[
1,
5577,
63,
1355,
1887,
65,
273,
729,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7914,
12,
203,
3639,
1758,
729,
1887,
16,
203,
3639,
1758,
14502,
1887,
203,
565,
262,
3238,
486,
8924,
288,
203,
3639,
2583,
12,
5,
291,
1299,
4002,
12,
1355,
1887,
3631,
315,
1355,
1704,
8863,
203,
3639,
2583,
12,
291,
1299,
4002,
12,
1734,
11110,
1887,
3631,
315,
1734,
11110,
486,
1704,
8863,
203,
203,
3639,
3677,
63,
1355,
1887,
8009,
350,
273,
1142,
10502,
31,
203,
3639,
3677,
63,
1355,
1887,
8009,
1734,
11110,
273,
14502,
1887,
31,
203,
3639,
612,
774,
1887,
63,
2722,
10502,
65,
273,
729,
1887,
31,
203,
203,
3639,
3677,
63,
1355,
1887,
8009,
1734,
11110,
273,
14502,
1887,
31,
203,
3639,
3677,
63,
1734,
11110,
1887,
8009,
1734,
29084,
1380,
1011,
404,
31,
203,
3639,
1142,
10502,
9904,
31,
203,
3639,
3626,
19304,
12,
203,
5411,
729,
1887,
16,
203,
5411,
14502,
1887,
16,
203,
5411,
3677,
63,
1355,
1887,
8009,
350,
16,
203,
5411,
3677,
63,
1734,
11110,
1887,
8009,
350,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts\SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts\IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function mint(address account, uint256 amount) external returns (bool);
function burnFrom(address account, uint256 amount) external;
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts\SafeDecimalMath.sol
pragma solidity >= 0.4.0 < 0.7.0;
// Libraries
// https://docs.synthetix.io/contracts/SafeDecimalMath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
// File: contracts\IEllaExchange.sol
pragma solidity >= 0.4.0 < 0.7.0;
// Libraries
/*
* @author Ella Finance
* @website https://ella.finance
* @email [email protected]
* Date: 18 Sept 2020
*/
interface IEllaExchange {
using SafeMath for uint;
using SafeDecimalMath for uint;
event Saved(uint _amount, bool _isMarket, address _contract, uint _time, address _owner, uint _duration);
event Withdrew(uint _amount, address _owner, address _to, address _contract, bool _isMarket, uint _time);
event Bought(uint _price, uint _amount, uint _value, address _market, bool isMarket, uint time);
event Rewarded(
address provider,
uint share,
bool _isMarket,
uint time
);
event PriceFeedChange(address _newAddress, address _exchange);
function save(uint _amount, bool _isMarket, uint _duration) external;
function save1(bool _isMarket, uint _duration) payable external;
function withdraw(uint _amount, address _to, bool _isMarket) external;
function withdraw1(address payable _to, uint _amount, bool _isMarket) external;
function accountBalance(address _owner) external view returns (uint _market, uint _token, uint _ethers);
function swap(uint _amount) external;
function swapBase(uint _amount) external;
function swapBase2(uint _amount) external;
function swap1(uint _amount) external;
function swapBase1() payable external;
function swap2() payable external;
}
// File: contracts\IPriceConsumer.sol
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File: contracts\TradingFees.sol
pragma solidity >=0.6.0;
interface FEES {
function getFees() external view returns (uint);
function getSystemCut() external view returns (uint);
function getFeesAddress() external view returns (address payable);
}
// File: contracts\EllaExchange.sol
pragma solidity >= 0.4.0 < 0.7.0;
/*
* @author Ella Finance
* @website https://ella.finance
* @email [email protected]
* Date: 18 Sept 2020
*/
contract EllaExchange is IEllaExchange {
IERC20 MarketAddress;
IERC20 TokenAddress;
FEES TradingFees;
bool private isEthereum;
mapping (bool => mapping(address => bool)) alreadyAProvider;
struct Providers{
address payable provider;
}
Providers[] providers;
mapping(bool => Providers[]) listOfProviders;
mapping(bool => mapping(address => uint)) savings;
mapping(address => uint) etherSavings;
mapping(bool => uint) pool;
uint etherpool;
address secretary;
uint baseFees_generated;
uint fees_generated;
mapping(address => mapping(bool => uint)) userWithdrawalDate;
mapping(address => mapping(bool => uint)) withdrawalDate;
AggregatorV3Interface internal priceFeed;
constructor(address _marketAddress, address _tokenAddress, bool _isEthereum, address _priceAddress, address _fees) public {
MarketAddress = IERC20(_marketAddress);
TokenAddress = IERC20(_tokenAddress);
TradingFees = FEES(_fees);
isEthereum = _isEthereum;
priceFeed = AggregatorV3Interface(_priceAddress);
secretary = msg.sender;
}
function description() external view returns (string memory){
return priceFeed.description();
}
function decimals() external view returns (uint8){
return priceFeed.decimals();
}
function version() external view returns (uint256){
return priceFeed.version();
}
function tokenPrice() public view returns(uint){
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = priceFeed.latestRoundData();
uint multiplier = 10**uint(SafeMath.sub(18, priceFeed.decimals()));
uint _price = uint(uint(answer).mul(multiplier));
return _price;
}
/**
* Restrict access to Secretary role
*/
modifier onlySecretary() {
require(secretary == msg.sender, "Address is not Secretary of this exchange!");
_;
}
function changePriceFeedAddress(address _new_address) public onlySecretary {
priceFeed = AggregatorV3Interface(_new_address);
emit PriceFeedChange(_new_address, address(this));
}
function save(uint _amount, bool _isMarket, uint _duration) public override{
require(_amount > 0, "Invalid amount");
require(_duration > 0, "Invalid duration");
require(setDuration(_duration, _isMarket) > 0, "Invalid duration");
IERC20 iERC20 = (_isMarket ? MarketAddress : TokenAddress);
require(iERC20.allowance(msg.sender, address(this)) >= _amount, "Insufficient allowance!");
iERC20.transferFrom(msg.sender, address(this), _amount);
savings[_isMarket][msg.sender] = savings[_isMarket][msg.sender].add(_amount);
pool[_isMarket] = pool[_isMarket].add(_amount);
if(alreadyAProvider[_isMarket][msg.sender] == false){
alreadyAProvider[_isMarket][msg.sender] = true;
listOfProviders[_isMarket].push(Providers(msg.sender));
}
emit Saved(_amount, _isMarket, address(this), now, msg.sender, setDuration(_duration, _isMarket));
}
function withdraw(uint _percentage, address _to, bool _isMarket) public override{
require(_percentage > 0, "Invalid amount");
require(isDue(_isMarket, msg.sender), "Lock period is not over yet!");
IERC20 iERC20 = (_isMarket ? MarketAddress : TokenAddress);
uint _withdrawable = withdrawable(_percentage, msg.sender, _isMarket, false);
uint _deduct = _percentage.multiplyDecimalRound(savings[_isMarket][msg.sender]);
savings[_isMarket][msg.sender] = _deduct >= savings[_isMarket][msg.sender] ? 0 : savings[_isMarket][msg.sender].sub(_deduct);
pool[_isMarket] = _withdrawable >= pool[_isMarket] ? 0 : pool[_isMarket].sub(_withdrawable);
require(iERC20.transfer(_to, _withdrawable), "Withdrawal faild");
emit Withdrew(_withdrawable,msg.sender, _to, address(this),_isMarket, now);
}
function withdrawable(uint _percentage, address _user, bool _isMarket, bool _isForEther) public view returns(uint){
uint pool_balance = _isForEther ? etherpool : pool[_isMarket];
uint contract_balance = _isForEther ? address(this).balance : (_isMarket ? MarketAddress.balanceOf(address(this)) : TokenAddress.balanceOf(address(this)));
uint get_user_pool_share = _isForEther ? etherSavings[_user].divideDecimalRound(pool_balance) : savings[_isMarket][_user].divideDecimalRound(pool_balance);
uint user_due = get_user_pool_share.multiplyDecimalRound(contract_balance);
uint _widthdrawable = _percentage.multiplyDecimalRound(user_due);
return _widthdrawable;
}
function save1(bool _isMarket, uint _duration) payable public override{
require(msg.value > 0, "Invalid amount");
require(_duration > 0, "Invalid duration");
require(setDuration(_duration, _isMarket) > 0, "Invalid duration");
require(isEthereum, "Can't save Ethereum in this contract");
etherSavings[msg.sender] = etherSavings[msg.sender].add(msg.value);
etherpool = etherpool.add(msg.value);
if(alreadyAProvider[_isMarket][msg.sender] == false){
alreadyAProvider[_isMarket][msg.sender] = true;
listOfProviders[_isMarket].push(Providers(msg.sender));
}
emit Saved(msg.value, _isMarket, address(this), now, msg.sender, setDuration(_duration, _isMarket));
}
function withdraw1(address payable _to, uint _percentage, bool _isMarket) public override{
require(_percentage > 0, "Invalid amount");
require(isDue(_isMarket, msg.sender), "Lock period is not over yet!");
uint _withdrawable = withdrawable(_percentage, msg.sender, _isMarket, true);
_to.transfer(_withdrawable);
uint _deduct = _percentage.multiplyDecimalRound(etherSavings[msg.sender]);
etherSavings[msg.sender] = _deduct >= etherSavings[msg.sender] ? 0 : etherSavings[msg.sender].sub(_deduct);
etherpool = _withdrawable >= etherpool ? 0 : etherpool.sub(_withdrawable);
emit Withdrew(_withdrawable,msg.sender, _to, address(this), _isMarket, now);
}
function accountBalance(address _owner) public override view returns (uint _market, uint _token, uint _ethers){
return(savings[true][_owner], savings[false][_owner], etherSavings[_owner]);
}
function swapBase(uint _amount) public override{
require(!isEthereum, "Can't transact!");
require(_amount > 0, "Zero value provided!");
require(MarketAddress.allowance(msg.sender, address(this)) >= _amount, "Non-sufficient funds");
require(MarketAddress.transferFrom(msg.sender, address(this), _amount), "Fail to tranfer fund");
uint _price = tokenPrice();
uint _amountDue = _amount.divideDecimal(_price);
uint _finalAmount = _amountDue.multiplyDecimal(10 ** 18);
require(TokenAddress.balanceOf(address(this)) >= _finalAmount, "No fund to execute the trade");
uint fee = TradingFees.getFees().multiplyDecimal(_finalAmount);
uint systemCut = TradingFees.getSystemCut().multiplyDecimal(fee);
fees_generated = fees_generated.add(fee.sub(systemCut));
require(TokenAddress.transfer(msg.sender, _finalAmount.sub(fee)), "Fail to tranfer fund");
require(TokenAddress.transfer(TradingFees.getFeesAddress(), systemCut), "Fail to tranfer fund");
emit Bought(_price, _finalAmount, _amount, address(this), true, now);
}
function swapBase2(uint _amount) public override{
require(isEthereum, "Can not transact!");
require(_amount > 0, "Zero value provided!");
require(MarketAddress.allowance(msg.sender, address(this)) >= _amount, "Non-sufficient funds");
require(MarketAddress.transferFrom(msg.sender, address(this), _amount), "Fail to tranfer fund");
address payable _reciever = msg.sender;
address payable _reciever2 = TradingFees.getFeesAddress();
uint _price = tokenPrice();
uint _amountDue = _amount.divideDecimal(_price);
uint _finalAmount = _amountDue.multiplyDecimal(10 ** 18);
require(address(this).balance >= _finalAmount, "No fund to execute the trade");
uint fee = TradingFees.getFees().multiplyDecimal(_finalAmount);
uint systemCut = TradingFees.getSystemCut().multiplyDecimal(fee);
fees_generated = fees_generated.add(fee.sub(systemCut));
_reciever.transfer(_finalAmount.sub(fee));
_reciever2.transfer(systemCut);
emit Bought(_price, _finalAmount, _amount, address(this), true, now);
}
// swap base(eth) for token
function swapBase1() payable public override{
require(isEthereum, "Can't transact!");
require(msg.value > 0, "Zero value provided!");
uint _price = tokenPrice();
uint _amount = msg.value;
uint _amountDue = _amount.divideDecimal(_price);
uint _finalAmount = _amountDue.multiplyDecimal(10 ** 18);
require(TokenAddress.balanceOf(address(this)) >= _finalAmount, "No fund to execute the trade");
uint fee = TradingFees.getFees().multiplyDecimal(_finalAmount);
uint systemCut = TradingFees.getSystemCut().multiplyDecimal(fee);
fees_generated = fees_generated.add(fee.sub(systemCut));
require(TokenAddress.transfer(msg.sender, _finalAmount.sub(fee)), "Fail to tranfer fund");
require(TokenAddress.transfer(TradingFees.getFeesAddress(), systemCut), "Fail to tranfer fund");
emit Bought(_price, _finalAmount, _amount, address(this), true, now);
}
// (swap your token to base)
function swap(uint _amount) public override{
require(!isEthereum, "Can't transact!");
require(_amount > 0, "Zero value provided!");
require(TokenAddress.allowance(msg.sender, address(this)) >= _amount, "Non-sufficient funds");
require(TokenAddress.transferFrom(msg.sender, address(this), _amount), "Fail to tranfer fund");
uint _price = tokenPrice();
uint _amountDue = _amount.multiplyDecimal(_price);
uint _finalAmount = _amountDue.divideDecimal(10 ** 18);
require(MarketAddress.balanceOf(address(this)) >= _finalAmount, "No fund to execute the trade");
uint fee = TradingFees.getFees().multiplyDecimal(_finalAmount);
uint systemCut = TradingFees.getSystemCut().multiplyDecimal(fee);
baseFees_generated = baseFees_generated.add(fee.sub(systemCut));
require(MarketAddress.transfer(msg.sender, _finalAmount.sub(fee)), "Fail to tranfer fund");
require(MarketAddress.transfer(TradingFees.getFeesAddress(), systemCut), "Fail to tranfer fund");
emit Bought(_price, _finalAmount, _amount, address(this), false, now);
}
//only call if eth is the base (swap your token to base)
function swap1(uint _amount) public override{
require(isEthereum, "Can't transact!");
require(_amount > 0, "Zero value");
require(TokenAddress.allowance(msg.sender, address(this)) >= _amount, "Non-sufficient funds");
require(TokenAddress.transferFrom(msg.sender, address(this), _amount), "Fail to tranfer fund");
address payable _reciever = msg.sender;
address payable _reciever2 = TradingFees.getFeesAddress();
uint _price = tokenPrice();
uint _amountDue = _price.multiplyDecimal(_amount);
uint _finalAmount = _amountDue.divideDecimal(10 ** 18);
require(address(this).balance >= _finalAmount, "No fund to execute the trade");
uint fee = TradingFees.getFees().multiplyDecimal(_finalAmount);
uint systemCut = TradingFees.getSystemCut().multiplyDecimal(fee);
baseFees_generated = baseFees_generated.add(fee.sub(systemCut));
_reciever.transfer(_finalAmount.sub(fee));
_reciever2.transfer(systemCut);
emit Bought(_price, _finalAmount, _amount, address(this), false, now);
}
// When eth is the token
function swap2() payable public override{
require(isEthereum, "Can't transact!");
require(msg.value > 0, "Zero value provided!");
uint _price = tokenPrice();
uint _amount = msg.value;
uint _amountDue = _price.multiplyDecimal(_amount);
uint _finalAmount = _amountDue.divideDecimal(10 ** 18);
require(MarketAddress.balanceOf(address(this)) >= _finalAmount, "No fund to execute the trade");
uint fee = TradingFees.getFees().multiplyDecimal(_finalAmount);
uint systemCut = TradingFees.getSystemCut().multiplyDecimal(fee);
baseFees_generated = baseFees_generated.add(fee.sub(systemCut));
require(MarketAddress.transfer(msg.sender, _finalAmount.sub(fee)), "Fail to tranfer fund");
require(MarketAddress.transfer(TradingFees.getFeesAddress(), systemCut), "Fail to tranfer fund");
emit Bought(_price, _finalAmount, _amount, address(this), false, now);
}
function setDuration(uint _duration, bool _isbase) internal returns(uint){
userWithdrawalDate[msg.sender][_isbase] == 0 ? userWithdrawalDate[msg.sender][_isbase] = _duration : userWithdrawalDate[msg.sender][_isbase];
if(_duration == 30){
withdrawalDate[msg.sender][_isbase] = block.timestamp.add(30 days);
return block.timestamp.add(30 days);
}else if(_duration == 60){
withdrawalDate[msg.sender][_isbase] = block.timestamp.add(60 days);
return block.timestamp.add(60 days);
}else if(_duration == 90){
withdrawalDate[msg.sender][_isbase] = block.timestamp.add(90 days);
return block.timestamp.add(90 days);
}else if(_duration == 365){
withdrawalDate[msg.sender][_isbase] = block.timestamp.add(365 days);
return block.timestamp.add(365 days);
}else if(_duration == 140000){
withdrawalDate[msg.sender][_isbase] = block.timestamp.add(140000 days);
return block.timestamp.add(140000 days);
}else{
return 0;
}
}
function isDue(bool _isbase, address _user) public view returns (bool) {
if (block.timestamp >= withdrawalDate[_user][_isbase])
return true;
else
return false;
}
function shareFees(bool _isEth, bool _isMarket) public {
uint feesShared;
for (uint256 i = 0; i < listOfProviders[_isMarket].length; i++) {
address payable _provider = listOfProviders[_isMarket][i].provider;
uint userSavings = _isEth ? etherSavings[_provider] : savings[_isMarket][_provider];
uint _pool = _isEth ? etherpool : pool[_isMarket];
uint total_fees_generated = _isMarket ? baseFees_generated : fees_generated;
uint share = userSavings.divideDecimal(_pool);
uint due = share.multiplyDecimal(total_fees_generated);
feesShared = feesShared.add(due);
require(total_fees_generated >= due, "No fees left for distribution");
_isEth ? _provider.transfer(due) : _isMarket ? require(MarketAddress.transfer(_provider, due), "Fail to tranfer fund") : require(TokenAddress.transfer(_provider, due), "Fail to tranfer fund");
emit Rewarded(_provider, due, _isMarket, now);
}
_isMarket ? baseFees_generated = baseFees_generated.sub(feesShared) : fees_generated = fees_generated.sub(feesShared);
}
}
// File: contracts\IEllaExchangeService.sol
pragma solidity >= 0.4.0 < 0.7.0;
/*
* @author Ella Finance
* @website https://ella.finance
* @email [email protected]
* Date: 18 Sept 2020
*/
interface IEllaExchangeService {
using SafeMath for uint;
event RequestCreated(
address _creator,
uint _requestType,
uint _changeTo,
string _reason,
uint _positiveVote,
uint _negativeVote,
uint _powerUsed,
bool _stale,
uint _votingPeriod,
uint _requestID
);
event ExchangeCreated(address _exchange, string _market, address _base_address, address _token_address );
function createRequest(uint _requestType, uint _changeTo, string calldata _reason) external;
function createExchange(address _marketAddress, address _tokenAddress, bool _isEthereum, address _priceAddress, string calldata _market) external returns (address _exchange);
event VotedForRequest(
address _voter,
uint _requestID,
uint _positiveVote,
uint _negativeVote,
bool _accept
);
event Refunded(uint amount, address voterAddress, uint _loanID, uint time);
event ApproveRequest(uint _requestID, bool _state, address _initiator);
function validateRequest(uint _requestID) external;
function governanceVote(uint _requestType, uint _requestID, uint _votePower, bool _accept) external;
}
// File: contracts\EllaExchangeService.sol
pragma solidity >=0.4.0 <0.7.0;
/*
* @author Ella Finance
* @website https://ella.finance
* @email [email protected]
* Date: 18 Sept 2020
*/
contract EllaExchangeService is IEllaExchangeService {
mapping(bytes => bool) isListed;
struct Requests{
address payable creator;
uint requestType;
uint changeTo;
string reason;
uint positiveVote;
uint negativeVote;
uint powerUsed;
bool stale;
uint votingPeriod;
}
struct Votters{
address payable voter;
}
Votters[] voters;
Requests[] requests;
mapping(uint => Requests[]) listOfrequests;
mapping(uint => mapping(address => uint)) requestPower;
mapping(uint => bool) activeRequest;
uint private requestCreationPower;
mapping(uint => mapping(address => bool)) manageRequestVoters;
mapping(uint => Votters[]) activeRequestVoters;
uint trading_fee;
address payable trading_fee_address;
uint system_cut;
IERC20 ELLA;
/**
* Construct a new exchange Service
* @param _ELLA address of the ELLA ERC20 token
*/
constructor(address _ELLA, uint _initial_fees, address payable _trading_fee_address, uint _system_cut, uint _requestCreationPower) public {
ELLA = IERC20(_ELLA);
trading_fee = _initial_fees;
trading_fee_address = _trading_fee_address;
system_cut = _system_cut;
requestCreationPower = _requestCreationPower;
}
function createExchange(
address _marketAddress,
address _tokenAddress,
bool _isEthereum,
address _priceAddress,
string memory _market
) public override returns (address _exchange) {
bytes memory market = bytes(_toLower(_market));
require(!isListed[market], "Market already listed");
EllaExchange exchange = new EllaExchange(address(_marketAddress), address(_tokenAddress), _isEthereum, address(_priceAddress), address(this));
_exchange = address(exchange);
isListed[market] = true;
emit ExchangeCreated(_exchange, _market, _marketAddress, _tokenAddress);
}
function getFees() public view returns(uint) {
return trading_fee;
}
function getSystemCut() public view returns(uint) {
return system_cut;
}
function getFeesAddress() public view returns(address) {
return trading_fee_address;
}
/// Request
function createRequest(uint _requestType, uint _changeTo, string memory _reason) public override{
require(_requestType == 0 || _requestType == 1 || _requestType == 2, "Invalid request type!");
require(!activeRequest[_requestType], "Another request is still active");
require(ELLA.allowance(msg.sender, address(this)) >= requestCreationPower, "Insufficient ELLA allowance for vote!");
ELLA.transferFrom(msg.sender, address(this), requestCreationPower);
Requests memory _request = Requests({
creator: msg.sender,
requestType: _requestType,
changeTo: _changeTo,
reason: _reason,
positiveVote: 0,
negativeVote: 0,
powerUsed: requestCreationPower,
stale: false,
votingPeriod: block.timestamp.add(4 days)
});
requests.push(_request);
uint256 newRequestID = requests.length - 1;
Requests memory request = requests[newRequestID];
emit RequestCreated(
request.creator,
request.requestType,
request.changeTo,
request.reason,
request.positiveVote,
request.negativeVote,
request.powerUsed,
request.stale,
request.votingPeriod,
newRequestID
);
}
function governanceVote(uint _requestType, uint _requestID, uint _votePower, bool _accept) public override{
Requests storage request = requests[_requestID];
require(request.votingPeriod >= block.timestamp, "Voting period ended");
require(_votePower > 0, "Power must be greater than zero!");
require(_requestType == 0 || _requestType == 1 || _requestType == 2, "Invalid request type!");
require(ELLA.allowance(msg.sender, address(this)) >= _votePower, "Insufficient ELLA allowance for vote!");
ELLA.transferFrom(msg.sender, address(this), _votePower);
requestPower[_requestType][msg.sender] = requestPower[_requestType][msg.sender].add(_votePower);
if(_accept){
request.positiveVote = request.positiveVote.add(_votePower);
}else{
request.negativeVote = request.negativeVote.add(_votePower);
}
if(manageRequestVoters[_requestID][msg.sender] == false){
manageRequestVoters[_requestID][msg.sender] = true;
activeRequestVoters[_requestID].push(Votters(msg.sender));
}
emit VotedForRequest(msg.sender, _requestID, request.positiveVote, request.negativeVote, _accept);
}
function validateRequest(uint _requestID) public override{
Requests storage request = requests[_requestID];
//require(block.timestamp >= request.votingPeriod, "Voting period still active");
require(!request.stale, "This has already been validated");
if(request.requestType == 0){
if(request.positiveVote >= request.negativeVote){
trading_fee = request.changeTo;
}
}else if(request.requestType == 1){
if(request.positiveVote >= request.negativeVote){
requestCreationPower = request.changeTo;
}
}else if(request.requestType == 2){
if(request.positiveVote >= request.negativeVote){
system_cut = request.changeTo;
}
}
else if(request.requestType == 3){
if(request.positiveVote >= request.negativeVote){
trading_fee_address = request.creator;
}
}
request.stale = true;
for (uint256 i = 0; i < activeRequestVoters[_requestID].length; i++) {
address voterAddress = activeRequestVoters[_requestID][i].voter;
uint amount = requestPower[request.requestType][voterAddress];
require(ELLA.transfer(voterAddress, amount), "Fail to refund voter");
requestPower[request.requestType][voterAddress] = 0;
emit Refunded(amount, voterAddress, _requestID, now);
}
require(ELLA.transfer(request.creator, request.powerUsed), "Fail to transfer fund");
emit ApproveRequest(_requestID, request.positiveVote >= request.negativeVote, msg.sender);
}
function _toLower(string memory str) internal pure returns (string memory) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character...
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
// So we add 32 to make it lowercase
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
}
|
* @dev Interface of the ERC20 standard as defined in the EIP./
|
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function mint(address account, uint256 amount) external returns (bool);
function burnFrom(address account, uint256 amount) external;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 14,845,683 |
[
1,
1358,
434,
326,
4232,
39,
3462,
4529,
487,
2553,
316,
326,
512,
2579,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
467,
654,
39,
3462,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
312,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
3903,
225,
1135,
261,
6430,
1769,
203,
377,
203,
565,
445,
18305,
1265,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
3903,
31,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
203,
377,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Spraytoken.net (SPRAY)
// SPRAY is a deflationary cryptocurrency with auto-staking and dynamic burn model,
// designed to resist the bear market by increasing the burn rate when the market is in a downward phase.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
/**
* @dev Wrapper for chainlink oracle (AggregatorV3Interface)
*/
abstract contract Aggregator is Ownable {
using Address for address;
AggregatorV3Interface private _aggregator;
int256 private _price = 0;
bool private _isTrandUp = true;
/**
* @dev Emitted when agregator changes to `newAggregator`.
*/
event UpdateAggregator(address indexed newAggregator);
/**
* @dev Updates the oracle used to receive market data.
*
* Can be called by the contract owner.
*/
function updateAggregator(address newAggregator) public virtual onlyOwner {
require(newAggregator.isContract(), "Address: call to non-contract");
_aggregator = AggregatorV3Interface(newAggregator);
updateTrand();
emit UpdateAggregator(newAggregator);
}
/**
* @dev Checks if the market trend is upward (bullish).
*/
function isTrandUp() public view virtual returns (bool) {
return _isTrandUp;
}
/**
* @dev Updates the trend information.
*/
function updateTrand() public virtual {
(, int256 price, , , ) = _aggregator.latestRoundData();
if (price != _price) {
_isTrandUp = price > _price;
_price = price;
}
}
}
/**
* @dev Deflationary ERC-20 token. Automatic rewards for holders. Dynamic supply. Rich in memes.
*
* For more information see spraytoken.net
*/
contract Spray is Aggregator, IERC20Metadata {
uint8 private constant _FEE_BASE = 3;
uint8 private constant _FEE_DIV = 100;
uint8 private constant _FIRE_MARKET_UP = 1;
uint8 private constant _FIRE_MARKET_DOWN = 2;
uint8 private constant _FIRE_DIV = 3;
string private constant _NAME = "spraytoken.net";
string private constant _SYMBOL = "SPRAY";
uint8 private constant _DECIMALS = 8;
uint256 private constant _EMISSION_INIT = 500 * (10**12) * (10**8);
uint256 private _emissionExcluded = 0;
uint256 private _emissionIncluded = _EMISSION_INIT;
uint256 private _rate = type(uint256).max / _EMISSION_INIT;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => uint256) private _balances;
mapping(address => bool) private _isExcluded;
mapping(address => uint256) private _excludedBalances;
constructor() {
_balances[_msgSender()] = _EMISSION_INIT * _rate;
emit Transfer(address(0), _msgSender(), _EMISSION_INIT);
}
/**
* @dev Returns the name of the token.
*/
function name() public pure override returns (string memory) {
return _NAME;
}
/**
* @dev Returns the symbol of the token.
*/
function symbol() public pure override returns (string memory) {
return _SYMBOL;
}
/**
* @dev Returns the decimals places of the token.
*/
function decimals() public pure override returns (uint8) {
return _DECIMALS;
}
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() public view override returns (uint256) {
return _emissionExcluded + _emissionIncluded;
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _excludedBalances[account];
return _balances[account] / _rate;
}
/**
* @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)
public
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) {
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
_approve(sender, _msgSender(), currentAllowance - amount);
_transfer(sender, recipient, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Check whether the account is included in redistribution.
*/
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
/**
* @dev Exclude `account` from receiving 1-2% transaction fee redistribution via auto-staking.
*
* Can be used to exclude technical addresses, such as exchange hot wallets.
* Can be called by the contract owner.
*/
function excludeAccount(address account) public virtual onlyOwner {
require(!_isExcluded[account], "Account is already excluded");
uint256 eBalance = _balances[account] / _rate;
_excludedBalances[account] += eBalance;
_balances[account] = 0;
_isExcluded[account] = true;
_emissionExcluded += eBalance;
_emissionIncluded -= eBalance;
}
/**
* @dev Includes `accounts` back for receiving 1-2% transaction fee redistribution via auto-staking.
*
* Can be called by the contract owner.
*/
function includeAccount(address account) public virtual onlyOwner {
require(_isExcluded[account], "Account is already included");
uint256 eBalance = _excludedBalances[account];
_excludedBalances[account] = 0;
_balances[account] = eBalance * _rate;
_isExcluded[account] = false;
_emissionExcluded -= eBalance;
_emissionIncluded += eBalance;
}
/**
* @dev Exclude sender account from receiving 1-2% transaction fee redistribution via auto-staking.
*
* Can be used to exclude technical addresses, such as exchange hot wallets.
*/
function excludeSelf() public virtual {
excludeAccount(_msgSender());
}
/**
* @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
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Moves tokens `eAmount` 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 eAmount
) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(
_EMISSION_INIT >= eAmount,
"ERC20: transfer amount exceeds balance"
);
// Withdrawal from sender
uint256 rAmount = eAmount * _rate;
if (_isExcluded[sender]) {
uint256 senderBalance = _excludedBalances[sender];
require(
senderBalance >= eAmount,
"ERC20: transfer amount exceeds balance"
);
_excludedBalances[sender] = senderBalance - eAmount;
_emissionExcluded -= eAmount;
_emissionIncluded += eAmount;
} else {
uint256 senderBalance = _balances[sender];
require(
senderBalance >= rAmount,
"ERC20: transfer amount exceeds balance"
);
uint256 newBalance = senderBalance - rAmount;
if (newBalance < _rate) {
rAmount += newBalance;
_balances[sender] = 0;
} else {
_balances[sender] = newBalance;
}
}
// Calculate fee and fired fee
updateTrand();
uint256 eFee = (eAmount * _FEE_BASE) / _FEE_DIV;
uint256 rFee = eFee * _rate;
uint8 fireBase = isTrandUp() ? _FIRE_MARKET_UP : _FIRE_MARKET_DOWN;
uint256 eFire = (eFee * fireBase) / _FIRE_DIV;
// Update emission and coefficient
uint256 oldEmission = _emissionIncluded;
_emissionIncluded -= eFire;
_rate = (_rate * (oldEmission - eFee)) / _emissionIncluded;
// Refill to recipient
if (_isExcluded[recipient]) {
uint256 tAmount = (rAmount - rFee) / _rate;
_excludedBalances[recipient] += tAmount;
_emissionExcluded += tAmount;
_emissionIncluded -= tAmount;
} else {
_balances[recipient] += rAmount - rFee;
}
emit Transfer(sender, recipient, eAmount - eFee);
}
}
|
Update emission and coefficient
|
uint256 oldEmission = _emissionIncluded;
| 2,537,614 |
[
1,
1891,
801,
19710,
471,
16554,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
1592,
1514,
19710,
273,
389,
351,
19710,
19323,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.15;
/**
* @title VersioningProxy
* @author Enrique Piqueras - <[email protected]>
* @notice A base contract for managing the deployment of versions of another contract, the managed contract.
*/
contract VersioningProxy {
/* Structs */
struct Deployment {
bytes32 tag;
address _address;
}
/* Events */
/**
* @notice Called whenever 'stable' changes for off-chain handling.
* @param _prevTag The previous 'stable' managed contract version tag.
* @param _prevAddress The previous 'stable' managed contract address.
* @param _nextTag The next 'stable' managed contract version tag.
* @param _nextAddress The next 'stable' managed contract address.
*/
event OnStableChange(bytes32 _prevTag, address _prevAddress, bytes32 _nextTag, address _nextAddress);
/* Storage */
// Owner and Creation Metadata
address public owner = msg.sender;
// Deployments
address public implementation; // Proxy standard target address
bytes32[] public tags; // We keep this so we can iterate over versions
mapping (bytes32 => address) public addresses;
Deployment public stable;
/* Modifiers */
/**
* @dev Makes a function only callable by the owner of this contract.
*/
modifier onlyOwner {
require(owner == msg.sender, "Can only be called by the owner.");
_;
}
/* Constructor */
/**
* @notice Constructs the versioning proxy with the proxy eternal storage flag and the first version of the managed contract, `firstTag`, at `firstAddress`.
* @param _firstTag The version tag of the first version of the managed contract.
* @param _firstAddress The address of the first verion of the managed contract.
*/
constructor(bytes32 _firstTag, address _firstAddress) public {
implementation = _firstAddress;
publish(_firstTag, _firstAddress);
}
/* External */
/**
* @notice Rolls back 'stable' to the previous deployment, and returns true, if one exists, returns false otherwise.
* @return True if there was a previous version and the rollback succeeded, false otherwise.
*/
function rollback() external onlyOwner returns(bool _success) {
uint256 tagsLen = tags.length;
if (tagsLen < 2) // We don't have a previous deployment, return false
return false;
// Roll back and return true
bytes32 prevTag = tags[tagsLen - 2];
setStable(prevTag);
return true;
}
/* External Views */
/**
* @notice Returns all deployed version tags.
* @return All of the deployed version tags.
*/
function allTags() external view returns(bytes32[] _tags) {
return tags;
}
/* Public */
/**
* @notice Publishes the next version of the managed contract, `nextTag`, at `nextAddress`.
* @param _nextTag The next version tag.
* @param _nextAddress The next address of the managed contract.
*/
function publish(bytes32 _nextTag, address _nextAddress) public onlyOwner {
// Publish
tags.push(_nextTag); // Push next tag
addresses[_nextTag] = _nextAddress; // Set next address
// Set 'stable'
setStable(_nextTag);
}
/**
* @notice Sets the value of 'stable' to the address of `nextTag`.
* @param _nextTag The already published version tag.
*/
function setStable(bytes32 _nextTag) public onlyOwner {
// Make sure this version has already been published
address nextAddress = addresses[_nextTag];
require(nextAddress != address(0), "The next address cannot be the zero address.");
// Save current tag and address for handlers
bytes32 prevTag = stable.tag;
address prevAddress = stable._address;
// Set 'stable'
stable = Deployment({tag: _nextTag, _address: nextAddress});
// Call handler and fire event
handleStableChange(prevTag, prevAddress, _nextTag, nextAddress); // on-chain
emit OnStableChange(prevTag, prevAddress, _nextTag, nextAddress); // off-chain
// Change proxy target
implementation = nextAddress;
}
/* Private */
/**
* @notice Called whenever 'stable' changes for on-chain handling.
* @dev Overwrite this function to handle 'stable' changes on-chain.
* @param _prevTag The previous 'stable' managed contract version tag.
* @param _prevAddress The previous 'stable' managed contract address.
* @param _nextTag The next 'stable' managed contract version tag.
* @param _nextAddress The next 'stable' managed contract address.
*/
function handleStableChange(bytes32 _prevTag, address _prevAddress, bytes32 _nextTag, address _nextAddress) private {}
}
|
* @dev Makes a function only callable by the owner of this contract./
|
modifier onlyOwner {
require(owner == msg.sender, "Can only be called by the owner.");
_;
}
| 5,362,891 |
[
1,
14534,
279,
445,
1338,
4140,
635,
326,
3410,
434,
333,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
1338,
5541,
288,
203,
3639,
2583,
12,
8443,
422,
1234,
18,
15330,
16,
315,
2568,
1338,
506,
2566,
635,
326,
3410,
1199,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
// import "https://github.com/Scott6768/LottoescapeV2/blob/main/LottoescapeV2";
import "./LSC.sol";
//import "";
contract LottoGame {
uint perTicketPrice;
using SafeMath for uint256;
address[5] winners; //payable[] public winners;
uint public numWinners;
bool terminator; //flag for stopping the game in its tracks
uint public potValue;
uint public potRemaining;
mapping(address => uint) public ticketBalance;
mapping(address => uint) public profits;
uint public totalTickets;
address public owner;
address internal _tokenAddress;
uint public amountToSendToNextRound;
uint amountToMarketingAddress;
uint amountToSendToLiquidity;
//uint public timeLeft;
uint public startTime;
uint public endTime;
uint public roundNumber; // to keep track of the active round of play
address public liquidityTokenRecipient;
LSC public token;
IPancakeRouter02 public pancakeswapV2Router;
uint256 minimumBuy; //minimum buy to be eligible to win share of the pot
uint256 tokensToAddOneSecond; //number of tokens that will add one second to the timer
uint256 maxTimeLeft; //maximum number of seconds the timer can be
uint256 maxWinners; //number of players eligible for winning share of the pot
uint256 potPayoutPercent; // what percent of the pot is paid out
uint256 potLeftoverPercent; // what percent is leftover
uint256 maxTickets; // max amount of tickets a player can hold
uint[5] winnerProfits;
uint[5] bnbProfits;
//optional stuff for fixing code later
address public _liquidityAddress = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3; //set to proper address if you need to pull V2 router manually
address public _marketingAddress = 0x54b360304374156D80C49b97a820836f89655360; //set to proper marketing address
constructor() public {
_tokenAddress = 0x2c0B1c005c54924eB53B4C3fD1650690BA01C128;
token = LSC(payable(_tokenAddress));
//pancakeswapV2Router = 0xB8D16214aD6Cb0E4967c3aeFCc8Bc5f74D386B0a; //The lazy way
pancakeswapV2Router = token.pancakeswapV2Router(); // pulls router information directly from main contract
// BUT, JUST IN CAST ^^THAT DOESN'T WORK:
/*/ Taken from standard code base, you also might try pulling v2pair and running with that.
IPancakeRouter02 _pancakeswapV2Router = IPancakeRouter02(_liquidityAddress);
//Create a Pancake pair for this new token
address pancakeswapV2Pair = IPancakeFactory(_pancakeswapV2Router.factory())
.createPair(address(this), _pancakeswapV2Router.WETH());
//set the rest of the contract variables
pancakeswapV2Router = _pancakeswapV2Router;
//*/
owner = msg.sender;
//liquidityTokenRecipient = address(this);
liquidityTokenRecipient = _liquidityAddress;
//set initial game gameSettings
minimumBuy = 100000*10**9;
tokensToAddOneSecond = 1000*10**9;
maxTimeLeft = 300 seconds;
maxWinners = 5;
potPayoutPercent = 60;
potLeftoverPercent = 40;
maxTickets = 10;
}
receive() external payable {
//to be able to receive eth/bnb
}
function getGameSettings() public view returns (uint, uint, uint, uint, uint) {
return (minimumBuy, tokensToAddOneSecond, maxTimeLeft, maxWinners, potPayoutPercent);
}
function adjustBuyInAmount(uint newBuyInAmount) external {
//add new buy in amount with 9 extra zeroes when calling this function (your token has 9 decimals)
require(msg.sender == owner, "Only owner");
minimumBuy = newBuyInAmount;
}
function transferOwnership(address newOwner) external {
require(msg.sender == owner, "Only owner.");
require(newOwner != address(0), "Address of owner cannot be zero.");
owner = newOwner;
}
function changeLiqduidityTokenRecipient(address newRecipient) public {
require(msg.sender == owner, "Only owner");
require(newRecipient != address(0), "Address of recipient cannot be zero.");
_liquidityAddress = newRecipient;
liquidityTokenRecipient = _liquidityAddress;
}
function buyTicket(address payable buyer, uint amount) public {
require(endTime != 0, "Game is not active!"); // will set when owner starts the game with initializeAndStart()
require(amount >= minimumBuy, "You must bet a minimum of 100,000 tokens.");
require(amount.div(minimumBuy * 10) <= maxTickets, "You may only purchase 10 tickets per play");
require(token.balanceOf(msg.sender) >= amount, "You don't have enough tokens"); //check the owners wallet to make sure they have enough
//note this function will throw unless a ticket is purchased!!
// start a new round if needed
uint startflag = getTimeLeft();
// getTimeLeft() returns 0 if the game has ended
if (startflag == 0) {
endGame();
} else { //if startflag is NOT equal to zero, game carries on
bool alreadyPlayed = false; //set this as a flag inside of the if
for (uint i = 0; i < numWinners; i++) { //scroll through the winners list
if (buyer == winners[i]){
alreadyPlayed = true;
}
}
//This statement is the whole point of the ELSE block, just make sure they aren't on the board
//If you need to remove their previous bet and add a new one, do it here.
//add a flag above for the index and squish it.
require(alreadyPlayed == false, "You can only buy tickets if you don't have a valid bid on the board");
}
ticketBalance[buyer] += amount.div(100000*10**9);
require(ticketBalance[buyer] >= 1, "Not enough for a ticket");
if (numWinners < maxWinners) {
// Only 5 winners allowed on the board, so if we haven't met that limit then add to the stack
winners[numWinners] = payable(buyer);
numWinners++;
} else {
//add new buyer and remove the first from the stack
ticketBalance[winners[0]] = 0;
for (uint i=0; i < (maxWinners - 1); i++){ //note the -1, we only want the leading values
winners[i] = winners[i+1];
}
winners[numWinners - 1] = payable(buyer); //now we add the stake to the top
}
uint timeToAdd = amount.div(tokensToAddOneSecond);
addTime(timeToAdd);
// Transfer Approval is handled by Web 3 before sending
// approve(this contract, amount)
token.transferFrom(msg.sender, payable(address(this)), amount);
//token.transferLSCgame2(msg.sender, payable(address(this)), amount);
potValue += amount;
}
function localTokenBalance() public view returns(uint){
return token.balanceOf(address(this));
}
function getTimeLeft() public view returns (uint){
if (now >= endTime) {
//endGame(); This would cost gas for the calling wallet or function, not good, but it would be an auto-start not requiring a new bid
// IF this returns 0, then you can add the "Buy ticket to start next round" and the gas from that ticket will start the next round
// see buyTicket for details
return 0;
}else
return endTime - now;
}
function addTime(uint timeAmount) private {
endTime += timeAmount;
if ((endTime - now) > maxTimeLeft) {
endTime = now + maxTimeLeft;
}
}
function initializeAndStart() external {
require(msg.sender == owner, "Only the contract owner can start the game");
roundNumber = 0;
startGame();
}
function startGame() private {
require(endTime <= now, "Stop spamming the start button please.");
roundNumber++;
startTime = now;
endTime = now + maxTimeLeft;
winners = [address(0), address(0), address(0), address(0), address(0)];
numWinners = 0;
}
function endGame() private {
require(now >= endTime, "Game is still active");
potRemaining = setPayoutAmount(); //does not change pot Value
require (potRemaining > 0, "potRemaining is 0!");
dealWithLeftovers(potRemaining);
sendProfitsInBNB();
swapAndAddLiqduidity();
potValue = amountToSendToNextRound;
if (amountToMarketingAddress > 0) {
// token.transfer(payable(_marketingAddress), (amountToMarketingAddress));
token.transferLSCgame2(address(this), payable(_marketingAddress), (amountToMarketingAddress));
}
for (uint i = 0; i < numWinners; i++) {
ticketBalance[winners[i]] = 0;
winners[i] = address(0);
}
if (terminator == false){
startGame();
} else { terminator = false; }
}
function setPayoutAmount() private returns(uint){
//get number of tickets held by each winner in the array
//only run once per round or tickets will be incorrectly counted
//this is handled by endGame(), do not call outside of that pls and thnx
totalTickets = 0; //reset before you start counting
for (uint i = 0; i < numWinners; i++) {
totalTickets += ticketBalance[winners[i]];
}
//require (totalTickets > 0, "Total Tickets is 0!");
//uint perTicketPrice;
uint top = (potValue.mul(potPayoutPercent));
uint bottom = (totalTickets.mul(100));
//require(bottom > 0, "Something has gone horribly wrong.");
if (bottom > 0){
perTicketPrice = top / bottom;
}
uint tally = 0;
//calculate the winnings based on how many tickets held by each winner
for (uint i; i < numWinners; i++){
winnerProfits[i] = perTicketPrice * ticketBalance[winners[i]];
tally += winnerProfits[i];
if (winnerProfits[i] > 0) {
bnbProfits[i] = swapProfitsForBNB(winnerProfits[i]);
}
}
require (tally < potValue, "Tally is bigger than the pot!");
return (potValue - tally);
}
function preLoadPot(uint amount) public { //This needs to be fixed also
//token.outsideApprove(msg.sender, address(this), amount);
// token.transferFrom(msg.sender, payable(address(this)), amount);
token.transferLSCgame2(msg.sender, payable(address(this)), amount);
potValue += amount;
}
function swapProfitsForBNB(uint amount) private returns (uint256) {
address[] memory path = new address[](2);
path[0] = _tokenAddress;
//path[0] = address(this);
path[1] = pancakeswapV2Router.WETH();
//token.gameApprove(address(this), address(pancakeswapV2Router), amount);
token.approve(address(pancakeswapV2Router), amount);
uint256 startingAmount = address(this).balance;
// make the swap
pancakeswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0, // accept any amount of ETH
path,
//_tokenAddress,
payable(address(this)),
block.timestamp
);
return address(this).balance - startingAmount;
}
//send bnb amount
function sendProfitsInBNB() private {
for (uint i; i < numWinners; i++){
payable(winners[i]).transfer(bnbProfits[i]);
}
}
function dealWithLeftovers(uint leftovers) private {
require(leftovers > 100, "no leftovers to spend");
require(potRemaining > 100, "no leftovers to spend");
uint nextRoundPot = 25;
uint liquidityAmount = 5;
uint marketingAddress = 10;
//There could potentially be some rounding error issues with this, but the sheer number of tokens
//should keep any problems to a minium.
// Fractions are set up as parts from the leftover 40%
amountToSendToNextRound = (potRemaining * nextRoundPot);
amountToSendToNextRound = amountToSendToNextRound.div(40);
amountToSendToLiquidity = (potRemaining * liquidityAmount);
amountToSendToLiquidity = amountToSendToLiquidity.div(40);
amountToMarketingAddress = (potRemaining * marketingAddress);
amountToMarketingAddress = amountToMarketingAddress.div(40);
}
//Send liquidity
function swapAndAddLiqduidity() private {
//sell half for bnb
uint halfOfLiqduidityAmount = amountToSendToLiquidity.div(2);
//first swap half for BNB
address[] memory path = new address[](2);
path[0] = _tokenAddress;
//path[0] = payable(address(this));
path[1] = pancakeswapV2Router.WETH();
//approve pancakeswap to spend tokens
token.approve(address(pancakeswapV2Router), halfOfLiqduidityAmount);
//get the initial contract balance
uint256 ethAmount = address(this).balance;
//swap if there is money to Send
if (amountToSendToLiquidity > 0) {
pancakeswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
halfOfLiqduidityAmount,
0, // accept any amount of BNB
path,
//_tokenAddress, //tokens get swapped to this contract so it has BNB to add liquidity
payable(address(this)),
block.timestamp + 30 seconds //30 second limit for the swap
);
ethAmount = address(this).balance - ethAmount;
//now we have BNB, we can add liquidity to the pool
token.approve(address(pancakeswapV2Router), halfOfLiqduidityAmount);
pancakeswapV2Router.addLiquidityETH {value: ethAmount} (
_tokenAddress, //token address
halfOfLiqduidityAmount, //amount to send
0, // slippage is unavoidable
0, // slippage is unavoidable
liquidityTokenRecipient, // where to send the liqduity tokens
block.timestamp + 30 seconds //deadline
);
}
}
// Fallback function is called when msg.data is not empty
fallback() external payable {}
function getRound() external view returns(uint){
return roundNumber;
}
// ******************8 Sane functions for export to front end
function totalPotValue() external view returns(uint){
return potValue;
}
function getWinners() external view returns(address, address, address, address, address){
return (winners[0], winners[1], winners[2], winners[3], winners[4]);
}
function getTicketsPerWinner() external view returns(uint, uint, uint, uint, uint)
{
//the ratio of payout is contingent on how many tickets that winner is holding vs the rest
return (ticketBalance[winners[0]], ticketBalance[winners[1]], ticketBalance[winners[2]], ticketBalance[winners[3]], ticketBalance[winners[4]]);
}
function setTokenAddress(address newAddress) external {
require(msg.sender == owner);
_tokenAddress = newAddress;
token = LSC(payable(_tokenAddress));
}
function getTokenAddress() external view returns(address) {
return _tokenAddress;
}
function getEndTime() external view returns(uint){
//Return the end time for the game in UNIX time
return endTime;
}
function updatePancakeRouterInfo() external {
require(msg.sender == owner);
pancakeswapV2Router = token.pancakeswapV2Router(); // pulls router information directly from main contract
}
function setMarketingAddress(address _newAddress) external {
require(msg.sender == owner);
_marketingAddress = _newAddress;
}
function getMarketingAddress() external view returns(address) {
return _marketingAddress;
}
function terminateGame() external {
require(msg.sender == owner, "Only the contract owner can terminate the game");
terminator = true;
endGame();
}
}
|
pancakeswapV2Router = 0xB8D16214aD6Cb0E4967c3aeFCc8Bc5f74D386B0a; The lazy way BUT, JUST IN CAST ^^THAT DOESN'T WORK:Create a Pancake pair for this new tokenset the rest of the contract variables*/liquidityTokenRecipient = address(this);set initial game gameSettings
|
constructor() public {
_tokenAddress = 0x2c0B1c005c54924eB53B4C3fD1650690BA01C128;
token = LSC(payable(_tokenAddress));
IPancakeRouter02 _pancakeswapV2Router = IPancakeRouter02(_liquidityAddress);
address pancakeswapV2Pair = IPancakeFactory(_pancakeswapV2Router.factory())
.createPair(address(this), _pancakeswapV2Router.WETH());
pancakeswapV2Router = _pancakeswapV2Router;
owner = msg.sender;
liquidityTokenRecipient = _liquidityAddress;
minimumBuy = 100000*10**9;
tokensToAddOneSecond = 1000*10**9;
maxTimeLeft = 300 seconds;
maxWinners = 5;
potPayoutPercent = 60;
potLeftoverPercent = 40;
maxTickets = 10;
}
| 7,282,729 |
[
1,
7355,
71,
3223,
91,
438,
58,
22,
8259,
273,
374,
20029,
28,
40,
30042,
3461,
69,
40,
26,
15237,
20,
41,
7616,
9599,
71,
23,
8906,
4488,
71,
28,
38,
71,
25,
74,
5608,
40,
23,
5292,
38,
20,
69,
31,
1021,
7962,
4031,
605,
1693,
16,
804,
5996,
2120,
6425,
882,
3602,
66,
2455,
789,
5467,
3991,
50,
11,
56,
17062,
30,
1684,
279,
12913,
23780,
3082,
364,
333,
394,
1147,
542,
326,
3127,
434,
326,
6835,
3152,
19,
549,
372,
24237,
1345,
18241,
273,
1758,
12,
2211,
1769,
542,
2172,
7920,
7920,
2628,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1435,
1071,
288,
203,
3639,
389,
2316,
1887,
273,
374,
92,
22,
71,
20,
38,
21,
71,
28564,
71,
6564,
29,
3247,
73,
38,
8643,
38,
24,
39,
23,
74,
40,
2313,
3361,
8148,
20,
12536,
1611,
39,
10392,
31,
203,
203,
3639,
1147,
273,
511,
2312,
12,
10239,
429,
24899,
2316,
1887,
10019,
203,
540,
203,
203,
3639,
2971,
19292,
911,
8259,
3103,
389,
7355,
71,
3223,
91,
438,
58,
22,
8259,
273,
2971,
19292,
911,
8259,
3103,
24899,
549,
372,
24237,
1887,
1769,
203,
3639,
1758,
2800,
71,
3223,
91,
438,
58,
22,
4154,
273,
2971,
19292,
911,
1733,
24899,
7355,
71,
3223,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
7355,
71,
3223,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
2800,
71,
3223,
91,
438,
58,
22,
8259,
273,
389,
7355,
71,
3223,
91,
438,
58,
22,
8259,
31,
203,
540,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
7010,
3639,
4501,
372,
24237,
1345,
18241,
273,
389,
549,
372,
24237,
1887,
31,
203,
203,
3639,
5224,
38,
9835,
273,
25259,
14,
2163,
636,
29,
31,
7010,
3639,
2430,
13786,
3335,
8211,
273,
4336,
14,
2163,
636,
29,
31,
203,
3639,
25328,
3910,
273,
11631,
3974,
31,
203,
3639,
943,
18049,
9646,
273,
1381,
31,
7010,
3639,
5974,
52,
2012,
8410,
273,
4752,
31,
203,
3639,
5974,
1682,
74,
24540,
8410,
273,
8063,
31,
203,
3639,
943,
6264,
2413,
273,
1728,
31,
203,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
// Part: IBasicRewards
interface IBasicRewards {
function stakeFor(address, uint256) external returns (bool);
function balanceOf(address) external view returns (uint256);
function earned(address) external view returns (uint256);
function withdrawAll(bool) external returns (bool);
function withdraw(uint256, bool) external returns (bool);
function getReward() external returns (bool);
function stake(uint256) external returns (bool);
}
// Part: ICurveFactoryPool
interface ICurveFactoryPool {
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_balances() external view returns (uint256[2] memory);
function add_liquidity(
uint256[2] memory _amounts,
uint256 _min_mint_amount,
address _receiver
) external returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 _dx,
uint256 _min_dy,
address _receiver
) external returns (uint256);
}
// Part: ICurvePool
interface ICurvePool {
function remove_liquidity_one_coin(
uint256 token_amount,
int128 i,
uint256 min_amount
) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i)
external
view
returns (uint256);
}
// Part: ICurveTriCrypto
interface ICurveTriCrypto {
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy,
bool use_eth
) external;
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256);
}
// Part: ICurveV2Pool
interface ICurveV2Pool {
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256);
function exchange_underlying(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) external payable returns (uint256);
}
// Part: ICvxCrvDeposit
interface ICvxCrvDeposit {
function deposit(uint256, bool) external;
}
// Part: ICvxMining
interface ICvxMining {
function ConvertCrvToCvx(uint256 _amount) external view returns (uint256);
}
// Part: IVirtualBalanceRewardPool
interface IVirtualBalanceRewardPool {
function earned(address account) external view returns (uint256);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/Context
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/ReentrancyGuard
/**
* @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;
}
}
// Part: OpenZeppelin/[email protected]/IERC20Metadata
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Ownable
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: UnionBase
// Common variables and functions
contract UnionBase {
address public constant CVXCRV_STAKING_CONTRACT =
0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e;
address public constant CURVE_CRV_ETH_POOL =
0x8301AE4fc9c624d1D396cbDAa1ed877821D7C511;
address public constant CURVE_CVX_ETH_POOL =
0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4;
address public constant CURVE_CVXCRV_CRV_POOL =
0x9D0464996170c6B9e75eED71c68B99dDEDf279e8;
address public constant CRV_TOKEN =
0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant CVXCRV_TOKEN =
0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
address public constant CVX_TOKEN =
0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
uint256 public constant CRVETH_ETH_INDEX = 0;
uint256 public constant CRVETH_CRV_INDEX = 1;
int128 public constant CVXCRV_CRV_INDEX = 0;
int128 public constant CVXCRV_CVXCRV_INDEX = 1;
uint256 public constant CVXETH_ETH_INDEX = 0;
uint256 public constant CVXETH_CVX_INDEX = 1;
IBasicRewards cvxCrvStaking = IBasicRewards(CVXCRV_STAKING_CONTRACT);
ICurveV2Pool cvxEthSwap = ICurveV2Pool(CURVE_CVX_ETH_POOL);
ICurveV2Pool crvEthSwap = ICurveV2Pool(CURVE_CRV_ETH_POOL);
ICurveFactoryPool crvCvxCrvSwap = ICurveFactoryPool(CURVE_CVXCRV_CRV_POOL);
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @return amount of CRV obtained after the swap
function _swapCrvToCvxCrv(uint256 amount, address recipient)
internal
returns (uint256)
{
return _crvToCvxCrv(amount, recipient, 0);
}
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _swapCrvToCvxCrv(
uint256 amount,
address recipient,
uint256 minAmountOut
) internal returns (uint256) {
return _crvToCvxCrv(amount, recipient, minAmountOut);
}
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _crvToCvxCrv(
uint256 amount,
address recipient,
uint256 minAmountOut
) internal returns (uint256) {
return
crvCvxCrvSwap.exchange(
CVXCRV_CRV_INDEX,
CVXCRV_CVXCRV_INDEX,
amount,
minAmountOut,
recipient
);
}
/// @notice Swap cvxCRV for CRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @return amount of CRV obtained after the swap
function _swapCvxCrvToCrv(uint256 amount, address recipient)
internal
returns (uint256)
{
return _cvxCrvToCrv(amount, recipient, 0);
}
/// @notice Swap cvxCRV for CRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _swapCvxCrvToCrv(
uint256 amount,
address recipient,
uint256 minAmountOut
) internal returns (uint256) {
return _cvxCrvToCrv(amount, recipient, minAmountOut);
}
/// @notice Swap cvxCRV for CRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _cvxCrvToCrv(
uint256 amount,
address recipient,
uint256 minAmountOut
) internal returns (uint256) {
return
crvCvxCrvSwap.exchange(
CVXCRV_CVXCRV_INDEX,
CVXCRV_CRV_INDEX,
amount,
minAmountOut,
recipient
);
}
/// @notice Swap CRV for native ETH on Curve
/// @param amount - amount to swap
/// @return amount of ETH obtained after the swap
function _swapCrvToEth(uint256 amount) internal returns (uint256) {
return _crvToEth(amount, 0);
}
/// @notice Swap CRV for native ETH on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of ETH obtained after the swap
function _swapCrvToEth(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return _crvToEth(amount, minAmountOut);
}
/// @notice Swap CRV for native ETH on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of ETH obtained after the swap
function _crvToEth(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return
crvEthSwap.exchange_underlying{value: 0}(
CRVETH_CRV_INDEX,
CRVETH_ETH_INDEX,
amount,
minAmountOut
);
}
/// @notice Swap native ETH for CRV on Curve
/// @param amount - amount to swap
/// @return amount of CRV obtained after the swap
function _swapEthToCrv(uint256 amount) internal returns (uint256) {
return _ethToCrv(amount, 0);
}
/// @notice Swap native ETH for CRV on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _swapEthToCrv(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return _ethToCrv(amount, minAmountOut);
}
/// @notice Swap native ETH for CRV on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _ethToCrv(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return
crvEthSwap.exchange_underlying{value: amount}(
CRVETH_ETH_INDEX,
CRVETH_CRV_INDEX,
amount,
minAmountOut
);
}
/// @notice Swap native ETH for CVX on Curve
/// @param amount - amount to swap
/// @return amount of CRV obtained after the swap
function _swapEthToCvx(uint256 amount) internal returns (uint256) {
return _ethToCvx(amount, 0);
}
/// @notice Swap native ETH for CVX on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _swapEthToCvx(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return _ethToCvx(amount, minAmountOut);
}
/// @notice Swap native ETH for CVX on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _ethToCvx(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return
cvxEthSwap.exchange_underlying{value: amount}(
CVXETH_ETH_INDEX,
CVXETH_CVX_INDEX,
amount,
minAmountOut
);
}
modifier notToZeroAddress(address _to) {
require(_to != address(0), "Invalid address!");
_;
}
}
// Part: ClaimZaps
contract ClaimZaps is ReentrancyGuard, UnionBase {
using SafeERC20 for IERC20;
// Possible options when claiming
enum Option {
Claim,
ClaimAsETH,
ClaimAsCRV,
ClaimAsCVX,
ClaimAndStake
}
/// @notice Set approvals for the tokens used when swapping
function _setApprovals() internal {
IERC20(CRV_TOKEN).safeApprove(CURVE_CRV_ETH_POOL, 0);
IERC20(CRV_TOKEN).safeApprove(CURVE_CRV_ETH_POOL, type(uint256).max);
IERC20(CVXCRV_TOKEN).safeApprove(CVXCRV_STAKING_CONTRACT, 0);
IERC20(CVXCRV_TOKEN).safeApprove(
CVXCRV_STAKING_CONTRACT,
type(uint256).max
);
IERC20(CVXCRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 0);
IERC20(CVXCRV_TOKEN).safeApprove(
CURVE_CVXCRV_CRV_POOL,
type(uint256).max
);
}
function _claimAs(
address account,
uint256 amount,
Option option
) internal {
_claim(account, amount, option, 0);
}
function _claimAs(
address account,
uint256 amount,
Option option,
uint256 minAmountOut
) internal {
_claim(account, amount, option, minAmountOut);
}
/// @notice Zap function to claim token balance as another token
/// @param account - recipient of the swapped token
/// @param amount - amount to swap
/// @param option - what to swap to
/// @param minAmountOut - minimum desired amount of output token
function _claim(
address account,
uint256 amount,
Option option,
uint256 minAmountOut
) internal nonReentrant {
if (option == Option.ClaimAsCRV) {
_swapCvxCrvToCrv(amount, account, minAmountOut);
} else if (option == Option.ClaimAsETH) {
uint256 _crvBalance = _swapCvxCrvToCrv(amount, address(this));
uint256 _ethAmount = _swapCrvToEth(_crvBalance, minAmountOut);
(bool success, ) = account.call{value: _ethAmount}("");
require(success, "ETH transfer failed");
} else if (option == Option.ClaimAsCVX) {
uint256 _crvBalance = _swapCvxCrvToCrv(amount, address(this));
uint256 _ethAmount = _swapCrvToEth(_crvBalance);
uint256 _cvxAmount = _swapEthToCvx(_ethAmount, minAmountOut);
IERC20(CVX_TOKEN).safeTransfer(account, _cvxAmount);
} else if (option == Option.ClaimAndStake) {
require(cvxCrvStaking.stakeFor(account, amount), "Staking failed");
} else {
IERC20(CVXCRV_TOKEN).safeTransfer(account, amount);
}
}
}
// Part: OpenZeppelin/[email protected]/ERC20
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: UnionVault.sol
contract UnionVault is ClaimZaps, ERC20, Ownable {
using SafeERC20 for IERC20;
address private constant TRIPOOL =
0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
address private constant THREECRV_TOKEN =
0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
address private constant USDT_TOKEN =
0xdAC17F958D2ee523a2206206994597C13D831ec7;
address private constant TRICRYPTO =
0xD51a44d3FaE010294C616388b506AcdA1bfAAE46;
address private constant CVX_MINING_LIB =
0x3c75BFe6FbfDa3A94E7E7E8c2216AFc684dE5343;
address private constant THREE_CRV_REWARDS =
0x7091dbb7fcbA54569eF1387Ac89Eb2a5C9F6d2EA;
address private constant CVXCRV_DEPOSIT =
0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae;
address public platform = 0x9Bc7c6ad7E7Cf3A6fCB58fb21e27752AC1e53f99;
uint256 public withdrawalPenalty = 100;
uint256 public constant MAX_WITHDRAWAL_PENALTY = 150;
uint256 public platformFee = 500;
uint256 public constant MAX_PLATFORM_FEE = 2000;
uint256 public callIncentive = 500;
uint256 public constant MAX_CALL_INCENTIVE = 500;
uint256 public constant FEE_DENOMINATOR = 10000;
ICurvePool private tripool = ICurvePool(TRIPOOL);
ICurveTriCrypto private tricrypto = ICurveTriCrypto(TRICRYPTO);
event Harvest(address indexed _caller, uint256 _value);
event Deposit(address indexed _from, address indexed _to, uint256 _value);
event Withdraw(address indexed _from, address indexed _to, uint256 _value);
event WithdrawalPenaltyUpdated(uint256 _penalty);
event CallerIncentiveUpdated(uint256 _incentive);
event PlatformFeeUpdated(uint256 _fee);
event PlatformUpdated(address indexed _platform);
constructor()
ERC20(
string(abi.encodePacked("Unionized cvxCRV")),
string(abi.encodePacked("uCRV"))
)
{}
/// @notice Set approvals for the contracts used when swapping & staking
function setApprovals() external onlyOwner {
IERC20(THREECRV_TOKEN).safeApprove(TRIPOOL, 0);
IERC20(THREECRV_TOKEN).safeApprove(TRIPOOL, type(uint256).max);
IERC20(CVX_TOKEN).safeApprove(CURVE_CVX_ETH_POOL, 0);
IERC20(CVX_TOKEN).safeApprove(CURVE_CVX_ETH_POOL, type(uint256).max);
IERC20(USDT_TOKEN).safeApprove(TRICRYPTO, 0);
IERC20(USDT_TOKEN).safeApprove(TRICRYPTO, type(uint256).max);
IERC20(CRV_TOKEN).safeApprove(CVXCRV_DEPOSIT, 0);
IERC20(CRV_TOKEN).safeApprove(CVXCRV_DEPOSIT, type(uint256).max);
IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 0);
IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, type(uint256).max);
_setApprovals();
}
/// @notice Updates the withdrawal penalty
/// @param _penalty - the amount of the new penalty (in BIPS)
function setWithdrawalPenalty(uint256 _penalty) external onlyOwner {
require(_penalty <= MAX_WITHDRAWAL_PENALTY);
withdrawalPenalty = _penalty;
emit WithdrawalPenaltyUpdated(_penalty);
}
/// @notice Updates the caller incentive for harvests
/// @param _incentive - the amount of the new incentive (in BIPS)
function setCallIncentive(uint256 _incentive) external onlyOwner {
require(_incentive <= MAX_CALL_INCENTIVE);
callIncentive = _incentive;
emit CallerIncentiveUpdated(_incentive);
}
/// @notice Updates the part of yield redirected to the platform
/// @param _fee - the amount of the new platform fee (in BIPS)
function setPlatformFee(uint256 _fee) external onlyOwner {
require(_fee <= MAX_PLATFORM_FEE);
platformFee = _fee;
emit PlatformFeeUpdated(_fee);
}
/// @notice Updates the address to which platform fees are paid out
/// @param _platform - the new platform wallet address
function setPlatform(address _platform)
external
onlyOwner
notToZeroAddress(_platform)
{
platform = _platform;
emit PlatformUpdated(_platform);
}
/// @notice Query the amount currently staked
/// @return total - the total amount of tokens staked
function totalUnderlying() public view returns (uint256 total) {
return cvxCrvStaking.balanceOf(address(this));
}
/// @notice Query the total amount of currently claimable CRV
/// @return total - the total amount of CRV claimable
function outstandingCrvRewards() public view returns (uint256 total) {
return cvxCrvStaking.earned(address(this));
}
/// @notice Query the total amount of currently claimable CVX
/// @return total - the total amount of CVX claimable
function outstandingCvxRewards() external view returns (uint256 total) {
return
ICvxMining(CVX_MINING_LIB).ConvertCrvToCvx(outstandingCrvRewards());
}
/// @notice Query the total amount of currently claimable 3CRV
/// @return total - the total amount of 3CRV claimable
function outstanding3CrvRewards() external view returns (uint256 total) {
return
IVirtualBalanceRewardPool(THREE_CRV_REWARDS).earned(address(this));
}
/// @notice Returns the amount of cvxCRV a user can claim
/// @param user - address whose claimable amount to query
/// @return amount - claimable amount
/// @dev Does not account for penalties and fees
function balanceOfUnderlying(address user)
external
view
returns (uint256 amount)
{
require(totalSupply() > 0, "No users");
return ((balanceOf(user) * totalUnderlying()) / totalSupply());
}
/// @notice Returns the address of the underlying token
function underlying() external view returns (address) {
return CVXCRV_TOKEN;
}
/// @notice Claim rewards and swaps them to cvxCrv for restaking
/// @dev Can be called by anyone against an incentive in cvxCrv
function harvest() public {
// claim rewards
cvxCrvStaking.getReward();
// sell CVX rewards for ETH
uint256 _cvxAmount = IERC20(CVX_TOKEN).balanceOf(address(this));
if (_cvxAmount > 0) {
cvxEthSwap.exchange_underlying{value: 0}(
CVXETH_CVX_INDEX,
CVXETH_ETH_INDEX,
_cvxAmount,
0
);
}
// pull 3crv out as USDT, swap for ETH
uint256 _threeCrvBalance = IERC20(THREECRV_TOKEN).balanceOf(
address(this)
);
if (_threeCrvBalance > 0) {
tripool.remove_liquidity_one_coin(_threeCrvBalance, 2, 0);
uint256 _usdtBalance = IERC20(USDT_TOKEN).balanceOf(address(this));
if (_usdtBalance > 0) {
tricrypto.exchange(0, 2, _usdtBalance, 0, true);
}
}
// swap everything to CRV
uint256 _crvBalance = IERC20(CRV_TOKEN).balanceOf(address(this));
uint256 _ethBalance = address(this).balance;
if (_ethBalance > 0) {
_crvBalance += _swapEthToCrv(address(this).balance);
}
if (_crvBalance > 0) {
uint256 _quote = crvCvxCrvSwap.get_dy(
CVXCRV_CRV_INDEX,
CVXCRV_CVXCRV_INDEX,
_crvBalance
);
// swap on Curve if there is a premium for doing so
if (_quote > _crvBalance) {
_swapCrvToCvxCrv(_crvBalance, address(this));
}
// otherwise deposit & lock
else {
ICvxCrvDeposit(CVXCRV_DEPOSIT).deposit(_crvBalance, true);
}
}
uint256 _cvxCrvBalance = IERC20(CVXCRV_TOKEN).balanceOf(address(this));
emit Harvest(msg.sender, _cvxCrvBalance);
// if this is the last call, no restake & no fees
if (totalSupply() == 0) {
return;
}
if (_cvxCrvBalance > 0) {
uint256 _stakingAmount = _cvxCrvBalance;
// Deduce and pay out incentive to caller (not needed for final exit)
if (callIncentive > 0) {
uint256 incentiveAmount = (_cvxCrvBalance * callIncentive) /
FEE_DENOMINATOR;
IERC20(CVXCRV_TOKEN).safeTransfer(msg.sender, incentiveAmount);
_stakingAmount = _stakingAmount - incentiveAmount;
}
// Deduce and pay platform fee
if (platformFee > 0) {
uint256 feeAmount = (_cvxCrvBalance * platformFee) /
FEE_DENOMINATOR;
IERC20(CVXCRV_TOKEN).safeTransfer(platform, feeAmount);
_stakingAmount = _stakingAmount - feeAmount;
}
cvxCrvStaking.stake(_stakingAmount);
}
}
/// @notice Deposit user funds in the autocompounder and mints tokens
/// representing user's share of the pool in exchange
/// @param _to - the address that will receive the shares
/// @param _amount - the amount of cvxCrv to deposit
/// @return _shares - the amount of shares issued
function deposit(address _to, uint256 _amount)
public
notToZeroAddress(_to)
returns (uint256 _shares)
{
require(_amount > 0, "Deposit too small");
uint256 _before = totalUnderlying();
IERC20(CVXCRV_TOKEN).safeTransferFrom(
msg.sender,
address(this),
_amount
);
cvxCrvStaking.stake(_amount);
// Issues shares in proportion of deposit to pool amount
uint256 shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount * totalSupply()) / _before;
}
_mint(_to, shares);
emit Deposit(msg.sender, _to, _amount);
return shares;
}
/// @notice Deposit all of user's cvxCRV balance
/// @param _to - the address that will receive the shares
/// @return _shares - the amount of shares issued
function depositAll(address _to) external returns (uint256 _shares) {
return deposit(_to, IERC20(CVXCRV_TOKEN).balanceOf(msg.sender));
}
/// @notice Unstake cvxCrv in proportion to the amount of shares sent
/// @param _shares - the number of shares sent
/// @return _withdrawable - the withdrawable cvxCrv amount
function _withdraw(uint256 _shares)
internal
returns (uint256 _withdrawable)
{
require(totalSupply() > 0);
// Computes the amount withdrawable based on the number of shares sent
uint256 amount = (_shares * totalUnderlying()) / totalSupply();
// Burn the shares before retrieving tokens
_burn(msg.sender, _shares);
// If user is last to withdraw, harvest before exit
if (totalSupply() == 0) {
harvest();
cvxCrvStaking.withdraw(totalUnderlying(), false);
_withdrawable = IERC20(CVXCRV_TOKEN).balanceOf(address(this));
}
// Otherwise compute share and unstake
else {
_withdrawable = amount;
// Substract a small withdrawal fee to prevent users "timing"
// the harvests. The fee stays staked and is therefore
// redistributed to all remaining participants.
uint256 _penalty = (_withdrawable * withdrawalPenalty) /
FEE_DENOMINATOR;
_withdrawable = _withdrawable - _penalty;
cvxCrvStaking.withdraw(_withdrawable, false);
}
return _withdrawable;
}
/// @notice Unstake cvxCrv in proportion to the amount of shares sent
/// @param _to - address to send cvxCrv to
/// @param _shares - the number of shares sent
/// @return withdrawn - the amount of cvxCRV returned to the user
function withdraw(address _to, uint256 _shares)
public
notToZeroAddress(_to)
returns (uint256 withdrawn)
{
// Withdraw requested amount of cvxCrv
uint256 _withdrawable = _withdraw(_shares);
// And sends back cvxCrv to user
IERC20(CVXCRV_TOKEN).safeTransfer(_to, _withdrawable);
emit Withdraw(msg.sender, _to, _withdrawable);
return _withdrawable;
}
/// @notice Withdraw all of a users' position as cvxCRV
/// @param _to - address to send cvxCrv to
/// @return withdrawn - the amount of cvxCRV returned to the user
function withdrawAll(address _to)
external
notToZeroAddress(_to)
returns (uint256 withdrawn)
{
return withdraw(_to, balanceOf(msg.sender));
}
/// @notice Zap function to withdraw as another token
/// @param _to - address to send cvxCrv to
/// @param _shares - the number of shares sent
/// @param option - what to swap to
function withdrawAs(
address _to,
uint256 _shares,
Option option
) external notToZeroAddress(_to) {
uint256 _withdrawn = _withdraw(_shares);
_claimAs(_to, _withdrawn, option);
}
/// @notice Zap function to withdraw all shares to another token
/// @param _to - address to send cvxCrv to
/// @param option - what to swap to
function withdrawAllAs(address _to, Option option)
external
notToZeroAddress(_to)
{
uint256 _withdrawn = _withdraw(balanceOf(msg.sender));
_claimAs(_to, _withdrawn, option);
}
/// @notice Zap function to withdraw as another token
/// @param _to - address to send cvxCrv to
/// @param _shares - the number of shares sent
/// @param option - what to swap to
/// @param minAmountOut - minimum desired amount of output token
function withdrawAs(
address _to,
uint256 _shares,
Option option,
uint256 minAmountOut
) external notToZeroAddress(_to) {
uint256 _withdrawn = _withdraw(_shares);
_claimAs(_to, _withdrawn, option, minAmountOut);
}
/// @notice Zap function to withdraw all shares to another token
/// @param _to - address to send cvxCrv to
/// @param option - what to swap to
/// @param minAmountOut - minimum desired amount of output token
function withdrawAllAs(
address _to,
Option option,
uint256 minAmountOut
) external notToZeroAddress(_to) {
uint256 _withdrawn = _withdraw(balanceOf(msg.sender));
_claimAs(_to, _withdrawn, option, minAmountOut);
}
receive() external payable {}
}
|
@notice Returns the address of the underlying token
|
function underlying() external view returns (address) {
return CVXCRV_TOKEN;
}
| 1,768,586 |
[
1,
1356,
326,
1758,
434,
326,
6808,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
6808,
1435,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
385,
58,
60,
5093,
58,
67,
8412,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.16;
/**
* @title xBounty Pre-seed token sale ICO Smart Contract.
* @author [email protected]
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
mapping(address => uint256) balances;
function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; }
//Transfer is disabled
//function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract XBTokenSale is ERC20Basic, Pausable {
using SafeMath for uint256;
string public constant name = "XB Token";
string public constant symbol = "XB";
uint256 public constant decimals = 18;
// address where funds are collected
address public wallet;
// Total XB tokens for PreSale
uint256 public constant TOTAL_XB_TOKEN_FOR_PRE_SALE = 2640000 * (10**decimals); //2,640,000 * 10^decimals
// how many token units a buyer gets per ETH
uint256 public rate = 1250; //1250 XB tokens per ETH, including 25% discount
// How many sold in PreSale
uint256 public presaleSoldTokens = 0;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Mint(address indexed to, uint256 amount);
function XBTokenSale(address _wallet) public {
require(_wallet != 0x0);
wallet = _wallet;
}
// fallback function can be used to buy tokens
function () whenNotPaused public payable {
buyTokens(msg.sender);
}
// low level token purchase function
//Only when the PreSale is running
function buyTokens(address beneficiary) whenNotPaused public payable {
require(beneficiary != 0x0);
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
require(presaleSoldTokens + tokens <= TOTAL_XB_TOKEN_FOR_PRE_SALE);
presaleSoldTokens = presaleSoldTokens.add(tokens);
// update state
weiRaised = weiRaised.add(weiAmount);
mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
}
|
address where funds are collected Total XB tokens for PreSale how many token units a buyer gets per ETH How many sold in PreSale amount of raised money in wei
|
contract XBTokenSale is ERC20Basic, Pausable {
using SafeMath for uint256;
string public constant name = "XB Token";
string public constant symbol = "XB";
uint256 public constant decimals = 18;
address public wallet;
uint256 public presaleSoldTokens = 0;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Mint(address indexed to, uint256 amount);
function XBTokenSale(address _wallet) public {
require(_wallet != 0x0);
wallet = _wallet;
}
function () whenNotPaused public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) whenNotPaused public payable {
require(beneficiary != 0x0);
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(rate);
require(presaleSoldTokens + tokens <= TOTAL_XB_TOKEN_FOR_PRE_SALE);
presaleSoldTokens = presaleSoldTokens.add(tokens);
weiRaised = weiRaised.add(weiAmount);
mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function mint(address _to, uint256 _amount) internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
}
| 5,353,095 |
[
1,
2867,
1625,
284,
19156,
854,
12230,
10710,
1139,
38,
2430,
364,
2962,
30746,
3661,
4906,
1147,
4971,
279,
27037,
5571,
1534,
512,
2455,
9017,
4906,
272,
1673,
316,
2962,
30746,
3844,
434,
11531,
15601,
316,
732,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
1139,
38,
1345,
30746,
353,
4232,
39,
3462,
8252,
16,
21800,
16665,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
533,
1071,
5381,
508,
273,
315,
60,
38,
3155,
14432,
203,
565,
533,
1071,
5381,
3273,
273,
315,
60,
38,
14432,
203,
565,
2254,
5034,
1071,
5381,
15105,
273,
6549,
31,
203,
203,
565,
1758,
1071,
9230,
31,
203,
203,
203,
203,
565,
2254,
5034,
1071,
4075,
5349,
55,
1673,
5157,
273,
374,
31,
203,
203,
565,
2254,
5034,
1071,
732,
77,
12649,
5918,
31,
203,
203,
565,
871,
3155,
23164,
12,
2867,
8808,
5405,
343,
14558,
16,
1758,
8808,
27641,
74,
14463,
814,
16,
2254,
5034,
460,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
490,
474,
12,
2867,
8808,
358,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
445,
1139,
38,
1345,
30746,
12,
2867,
389,
19177,
13,
1071,
288,
203,
3639,
2583,
24899,
19177,
480,
374,
92,
20,
1769,
203,
3639,
9230,
273,
389,
19177,
31,
203,
565,
289,
203,
203,
203,
565,
445,
1832,
1347,
1248,
28590,
1071,
8843,
429,
288,
203,
3639,
30143,
5157,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
565,
445,
30143,
5157,
12,
2867,
27641,
74,
14463,
814,
13,
1347,
1248,
28590,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
70,
4009,
74,
14463,
814,
480,
374,
92,
20,
1769,
203,
203,
3639,
2254,
5034,
732,
77,
6275,
273,
1234,
18,
1132,
31,
203,
203,
3639,
2254,
5034,
2430,
273,
732,
77,
6275,
18,
16411,
12,
5141,
2
] |
./full_match/1/0x7551597Fa40bED86cfd12D2Dc3d4E56FD8E0CaBf/sources/contracts/HoneyExchangeV2.sol
|
Owner-only function to update exchange rate
|
function setExchangeRate(uint256 newRate) public onlyOwner {
exchangeRate = newRate;
}
| 3,018,949 |
[
1,
5541,
17,
3700,
445,
358,
1089,
7829,
4993,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
11688,
4727,
12,
11890,
5034,
394,
4727,
13,
1071,
1338,
5541,
288,
203,
3639,
7829,
4727,
273,
394,
4727,
31,
203,
565,
289,
27699,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity^0.4.24;
contract Voting{
//Constructor para inicializar los candidatos
//votar pro los candidatos
//Obetner cantidad de votos por cada candidato
bytes32[] public candidatesList;
mapping(bytes32 => uint8) public votesReceived;
constructor(bytes32[] candidatesNames) public {
candidatesList=candidatesNames;
}
function voteForCandidate(bytes32 candidate) public {
require(validateCandidate(candidate));
votesReceived[candidate] += 1;
}
function totalVotesFor(bytes32 candidate) view public returns(uint8){
require(validateCandidate(candidate));
return votesReceived[candidate];
}
function validateCandidate(bytes32 candidate) view public returns(bool){
for(uint8 i=0;i < candidatesList.length; i++){
if(candidatesList[i] == candidate){
return true;
}
return false;
}
}
}
|
Constructor para inicializar los candidatosvotar pro los candidatosObetner cantidad de votos por cada candidato
|
contract Voting{
bytes32[] public candidatesList;
mapping(bytes32 => uint8) public votesReceived;
constructor(bytes32[] candidatesNames) public {
candidatesList=candidatesNames;
}
function voteForCandidate(bytes32 candidate) public {
require(validateCandidate(candidate));
votesReceived[candidate] += 1;
}
function totalVotesFor(bytes32 candidate) view public returns(uint8){
require(validateCandidate(candidate));
return votesReceived[candidate];
}
function validateCandidate(bytes32 candidate) view public returns(bool){
for(uint8 i=0;i < candidatesList.length; i++){
if(candidatesList[i] == candidate){
return true;
}
return false;
}
}
function validateCandidate(bytes32 candidate) view public returns(bool){
for(uint8 i=0;i < candidatesList.length; i++){
if(candidatesList[i] == candidate){
return true;
}
return false;
}
}
function validateCandidate(bytes32 candidate) view public returns(bool){
for(uint8 i=0;i < candidatesList.length; i++){
if(candidatesList[i] == candidate){
return true;
}
return false;
}
}
}
| 13,027,216 |
[
1,
6293,
12602,
316,
22354,
31707,
22148,
4225,
270,
538,
90,
352,
297,
450,
22148,
4225,
270,
538,
10516,
278,
1224,
848,
18081,
361,
443,
331,
12440,
22471,
276,
16524,
4225,
31093,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
776,
17128,
95,
203,
565,
1731,
1578,
8526,
1071,
7965,
682,
31,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
28,
13,
1071,
19588,
8872,
31,
7010,
377,
203,
377,
203,
565,
3885,
12,
3890,
1578,
8526,
7965,
1557,
13,
1071,
288,
203,
3639,
7965,
682,
33,
21635,
1557,
31,
203,
565,
289,
203,
377,
203,
565,
445,
12501,
1290,
11910,
12,
3890,
1578,
5500,
13,
1071,
288,
203,
3639,
2583,
12,
5662,
11910,
12,
19188,
10019,
203,
3639,
19588,
8872,
63,
19188,
65,
1011,
404,
31,
203,
565,
289,
203,
377,
203,
377,
203,
565,
445,
2078,
29637,
1290,
12,
3890,
1578,
5500,
13,
1476,
1071,
1135,
12,
11890,
28,
15329,
203,
3639,
2583,
12,
5662,
11910,
12,
19188,
10019,
203,
3639,
327,
19588,
8872,
63,
19188,
15533,
203,
565,
289,
203,
377,
203,
565,
445,
1954,
11910,
12,
3890,
1578,
5500,
13,
1476,
1071,
1135,
12,
6430,
15329,
203,
3639,
364,
12,
11890,
28,
277,
33,
20,
31,
77,
411,
7965,
682,
18,
2469,
31,
277,
27245,
95,
203,
5411,
309,
12,
21635,
682,
63,
77,
65,
422,
5500,
15329,
203,
7734,
327,
638,
31,
203,
5411,
289,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
377,
203,
565,
445,
1954,
11910,
12,
3890,
1578,
5500,
13,
1476,
1071,
1135,
12,
6430,
15329,
203,
3639,
364,
12,
11890,
28,
277,
33,
20,
31,
77,
411,
7965,
682,
18,
2469,
31,
277,
27245,
95,
203,
5411,
309,
12,
21635,
682,
63,
77,
65,
422,
5500,
15329,
203,
7734,
2
] |
./full_match/43113/0x1dB815BcfbEC194cd868C1a91C339C60B4FA703F/sources/avax.sol
|
must hold 200000+ tokens
|
minimumTokenBalanceForDividends = 2000000 * (10**9);
| 7,192,192 |
[
1,
11926,
6887,
576,
11706,
15,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
5224,
1345,
13937,
1290,
7244,
350,
5839,
273,
576,
9449,
380,
261,
2163,
636,
29,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x2539Edf3969cA8Bb8659BfaDc27d626bD5cd8f13/sources/DumpBusterv1.sol
|
mapping (address => uint256) private _lastTransactBlocks; Keeps track of the last block a user transacted inmapping (address => uint256) private _lastTransactTimes; Keeps track of the last time a user transacteduint256 private _launchedBlock; What block number did we launch on event for EVM logging
|
contract DumpBuster_v1 is Context, IERC20 {
uint256 private _DECIMALS;
uint256 private _DECIMALFACTOR;
uint256 private _SUPPLY;
uint256 private _TotalSupply;
uint256 private _TENTHOUSANDUNITS;
string private _NAME;
event OwnerSet(address indexed oldOwner, address indexed newOwner);
event Transfer(address recipient, uint256 amount);
event Approval(address spender, uint256 amount);
pragma solidity >=0.7.0 <0.9.0;
modifier isOwner() {
require(_msgSender() == _owner, "Caller is not owner");
_;
}
modifier isOwnerOrBanner() {
require(_msgSender() == _owner || _msgSender() == _banner, "Caller is not owner or banner");
_;
}
function initialize() public {
require(!_initialized);
_owner = _msgSender();
_tax = 0xefe5bb8529b6bF478EF8c18cd115746F162C9C2d;
_banner = _msgSender();
_treasury = _msgSender();
_tradeIsOpen = false;
_buyIsOpen = true;
_sellIsOpen = false;
_blockRestriction = 2;
_timeRestriction = 60;
_taxAmount = 320;
_sellTaxFactor = 18000;
_transactRestriction = 250000000;
_transactRestrictionTime = 60;
_transactRestrictionTimeStart = block.timestamp;
_DECIMALS = 9;
_DECIMALFACTOR = 10 ** _DECIMALS;
_SUPPLY = 100000000000;
_TotalSupply = _SUPPLY * _DECIMALFACTOR;
_TENTHOUSANDUNITS = 10000;
_NAME = "DumpBuster";
_SYMBOL = "GTFO";
_balances[_msgSender()] = _TotalSupply;
_initialized = true;
emit OwnerSet(address(0), _owner);
}
function changeOwner(address newOwner) public isOwner {
emit OwnerSet(_owner, newOwner);
_owner = newOwner;
}
function changeBanner(address newBanner) public isOwner {
_banner = newBanner;
}
function openTrade() public isOwner {
_tradeIsOpen = true;
}
function closeTrade() public isOwner {
_tradeIsOpen = false;
}
function openBuys() public isOwner {
_buyIsOpen = true;
}
function openSells() public isOwner {
_sellIsOpen = true;
}
function closeBuys() public isOwner {
_buyIsOpen = false;
}
function closeSells() public isOwner {
_sellIsOpen = false;
}
function addExchange(address exchangeToAdd) public isOwner {
_exchanges[exchangeToAdd] = true;
}
function removeExchange(address exchangeToRemove) public isOwner {
_exchanges[exchangeToRemove] = false;
}
function setProxy(address proxyAddress) public isOwner {
require(_proxy==address(0));
_proxy = proxyAddress;
}
function addPartner(address partnerAddress) public isOwner {
_partners[partnerAddress] = true;
}
function removePartner(address partnerAddress) public isOwner {
_partners[partnerAddress] = false;
}
function updateTimeRestriction(uint256 newTime) public isOwner {
_timeRestriction = newTime;
}
function updateBlockRestriction(uint256 newBlock) public isOwner {
_blockRestriction = newBlock;
}
function updateTax(address taxAddress, uint256 taxAmount) public isOwner {
_tax = taxAddress;
_taxAmount = taxAmount;
}
function updateTransactRestriction(uint256 transactRestriction) public isOwner {
_transactRestriction = transactRestriction;
}
function updateTransactRestrictionTime(uint256 transactRestrictionTime, bool transactRestrictionEnabled) public isOwner {
_transactRestrictionTime = transactRestrictionTime;
_transactRestrictionEnabled = transactRestrictionEnabled;
_transactRestrictionTimeStart = block.timestamp;
}
function updateTreasury(address treasury) public isOwner {
_treasury = treasury;
}
function getOwner() external view returns (address) {
return _owner;
}
function name() public view returns (string memory) {
return _NAME;
}
function symbol() public view returns (string memory) {
return _SYMBOL;
}
function decimals() public view returns (uint256) {
return _DECIMALS;
}
function totalSupply() public override view returns (uint256) {
return _TotalSupply;
}
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
return _transfer(_msgSender(), recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
require(amount <= _allowances[sender][_msgSender()], "Insufficient allowance");
bool tranactionWentThrough = _transfer(sender, recipient, amount);
if (tranactionWentThrough) {
_allowances[sender][_msgSender()] = _allowances[sender][_msgSender()] - amount;
}
return tranactionWentThrough;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
require(amount <= _allowances[sender][_msgSender()], "Insufficient allowance");
bool tranactionWentThrough = _transfer(sender, recipient, amount);
if (tranactionWentThrough) {
_allowances[sender][_msgSender()] = _allowances[sender][_msgSender()] - amount;
}
return tranactionWentThrough;
}
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[_msgSender()][spender] = amount;
emit Approval(_msgSender(), spender, amount);
return true;
}
function fullScan(address coinId, address accountId, uint256 timeThreshold, uint256 tokenAmount, uint256 totalTokens, uint256 percentageThreshold) public returns (bool isIssue){
collectTax();
if (validateTimeBasedTransaction(coinId, accountId, timeThreshold, false)) {
return true;
}
if (validateVolumeBasedTransaction(tokenAmount, totalTokens, percentageThreshold, false)) {
return true;
}
if (validateManipulation(false)) {
return true;
}
return false;
}
function fullScan(address coinId, address accountId, uint256 timeThreshold, uint256 tokenAmount, uint256 totalTokens, uint256 percentageThreshold) public returns (bool isIssue){
collectTax();
if (validateTimeBasedTransaction(coinId, accountId, timeThreshold, false)) {
return true;
}
if (validateVolumeBasedTransaction(tokenAmount, totalTokens, percentageThreshold, false)) {
return true;
}
if (validateManipulation(false)) {
return true;
}
return false;
}
function fullScan(address coinId, address accountId, uint256 timeThreshold, uint256 tokenAmount, uint256 totalTokens, uint256 percentageThreshold) public returns (bool isIssue){
collectTax();
if (validateTimeBasedTransaction(coinId, accountId, timeThreshold, false)) {
return true;
}
if (validateVolumeBasedTransaction(tokenAmount, totalTokens, percentageThreshold, false)) {
return true;
}
if (validateManipulation(false)) {
return true;
}
return false;
}
function fullScan(address coinId, address accountId, uint256 timeThreshold, uint256 tokenAmount, uint256 totalTokens, uint256 percentageThreshold) public returns (bool isIssue){
collectTax();
if (validateTimeBasedTransaction(coinId, accountId, timeThreshold, false)) {
return true;
}
if (validateVolumeBasedTransaction(tokenAmount, totalTokens, percentageThreshold, false)) {
return true;
}
if (validateManipulation(false)) {
return true;
}
return false;
}
function validateTimeBasedTransaction(address coinId, address accountId, uint256 timeThreshold) public returns (bool isIssue) {
return validateTimeBasedTransaction(coinId, accountId, timeThreshold, true);
}
function validateTimeBasedTransaction(address coinId, address accountId, uint256 timeThreshold, bool collectThreshold) private returns (bool isIssue) {
if (collectThreshold) {
collectTax();
}
if ((block.timestamp - botChecker[coinId][accountId]) < timeThreshold) {
return true;
}
return false;
}
function validateTimeBasedTransaction(address coinId, address accountId, uint256 timeThreshold, bool collectThreshold) private returns (bool isIssue) {
if (collectThreshold) {
collectTax();
}
if ((block.timestamp - botChecker[coinId][accountId]) < timeThreshold) {
return true;
}
return false;
}
function validateTimeBasedTransaction(address coinId, address accountId, uint256 timeThreshold, bool collectThreshold) private returns (bool isIssue) {
if (collectThreshold) {
collectTax();
}
if ((block.timestamp - botChecker[coinId][accountId]) < timeThreshold) {
return true;
}
return false;
}
function validateVolumeBasedTransaction(uint256 tokenAmount, uint256 totalTokens, uint256 percentageThreshold, address accountId) public returns (bool isIssue) {
return validateVolumeBasedTransaction(tokenAmount, totalTokens, percentageThreshold, true);
}
function validateVolumeBasedTransaction(uint256 tokenAmount, uint256 totalTokens, uint256 percentageThreshold, bool collectThreshold) private returns (bool isIssue) {
if (collectThreshold) {
collectTax();
}
if (((tokenAmount * _TENTHOUSANDUNITS) / _TotalSupply) > (percentageThreshold)) {
return true;
}
return false;
}
function validateVolumeBasedTransaction(uint256 tokenAmount, uint256 totalTokens, uint256 percentageThreshold, bool collectThreshold) private returns (bool isIssue) {
if (collectThreshold) {
collectTax();
}
if (((tokenAmount * _TENTHOUSANDUNITS) / _TotalSupply) > (percentageThreshold)) {
return true;
}
return false;
}
function validateVolumeBasedTransaction(uint256 tokenAmount, uint256 totalTokens, uint256 percentageThreshold, bool collectThreshold) private returns (bool isIssue) {
if (collectThreshold) {
collectTax();
}
if (((tokenAmount * _TENTHOUSANDUNITS) / _TotalSupply) > (percentageThreshold)) {
return true;
}
return false;
}
function validateManipulation() public returns (bool isIssue) {
return validateManipulation(true);
}
function validateManipulation(bool collectThreshold) private returns (bool isIssue) {
if (collectThreshold) {
collectTax();
}
}
function validateManipulation(bool collectThreshold) private returns (bool isIssue) {
if (collectThreshold) {
collectTax();
}
}
function isOnBlackList(address coinId, address accountId) public view returns (bool isIssue) {
return blacklist[coinId][accountId] == true;
}
function addToBlacklist(address coinId, address accountId) public isOwnerOrBanner {
blacklist[coinId][accountId] = true;
}
function removeFromBlacklist(address coinId, address accountId) public isOwnerOrBanner {
blacklist[coinId][accountId] = false;
}
function transact(address coinId, address accountId) public returns (bool isIssue) {
botChecker[coinId][accountId] = block.timestamp;
}
function collectTax() private view returns (bool hadCoin) {
require (_partners[_msgSender()]);
}
function _transfer(address sender, address recipient, uint256 amount) private returns (bool) {
require(_owner == sender || _tradeIsOpen, "Trading not currently open");
if (!_exchanges[sender]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][sender] > _timeRestriction, "Cannot transact twice in short period of time");
}
if (!_exchanges[recipient]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][recipient] > _timeRestriction, "The wallet you are sending funds to cannot transact twice in short period of time");
}
if (_owner == sender || (_transactRestrictionEnabled && block.timestamp <= _transactRestrictionTimeStart + _transactRestrictionTime)) {
require(_owner == sender || amount < _transactRestriction, "Cannot exceed transaction size limit");
}
require(amount <= _balances[sender], "Insufficient balance");
require(_owner == sender || !blacklist[_proxy][sender], "Sender Blacklisted");
require(_owner == sender || !blacklist[_proxy][recipient], "Recipient Blacklisted");
if (_exchanges[sender]) {
require(_owner == sender || _buyIsOpen, "Buying not currently open");
}
if (_exchanges[recipient]) {
require(_owner == sender || _sellIsOpen, "Selling not currently open");
}
uint256 amountForTax;
uint256 amountForTransfer;
amountForTax = amount * _taxAmount / _TENTHOUSANDUNITS;
if (_exchanges[recipient] && _sellTaxFactor != _TENTHOUSANDUNITS) {
amountForTax = amountForTax * _sellTaxFactor / _TENTHOUSANDUNITS;
}
amountForTransfer = amount - amountForTax;
_balances[sender] = _balances[sender] - amount;
_balances[_tax] = _balances[_tax] + amountForTax;
_balances[recipient] = _balances[recipient] + amountForTransfer;
emit Transfer(sender, recipient, amountForTransfer);
if (!_exchanges[sender]) {
botChecker[_proxy][sender] = block.timestamp;
}
if (!_exchanges[recipient]) {
botChecker[_proxy][recipient] = block.timestamp;
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) private returns (bool) {
require(_owner == sender || _tradeIsOpen, "Trading not currently open");
if (!_exchanges[sender]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][sender] > _timeRestriction, "Cannot transact twice in short period of time");
}
if (!_exchanges[recipient]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][recipient] > _timeRestriction, "The wallet you are sending funds to cannot transact twice in short period of time");
}
if (_owner == sender || (_transactRestrictionEnabled && block.timestamp <= _transactRestrictionTimeStart + _transactRestrictionTime)) {
require(_owner == sender || amount < _transactRestriction, "Cannot exceed transaction size limit");
}
require(amount <= _balances[sender], "Insufficient balance");
require(_owner == sender || !blacklist[_proxy][sender], "Sender Blacklisted");
require(_owner == sender || !blacklist[_proxy][recipient], "Recipient Blacklisted");
if (_exchanges[sender]) {
require(_owner == sender || _buyIsOpen, "Buying not currently open");
}
if (_exchanges[recipient]) {
require(_owner == sender || _sellIsOpen, "Selling not currently open");
}
uint256 amountForTax;
uint256 amountForTransfer;
amountForTax = amount * _taxAmount / _TENTHOUSANDUNITS;
if (_exchanges[recipient] && _sellTaxFactor != _TENTHOUSANDUNITS) {
amountForTax = amountForTax * _sellTaxFactor / _TENTHOUSANDUNITS;
}
amountForTransfer = amount - amountForTax;
_balances[sender] = _balances[sender] - amount;
_balances[_tax] = _balances[_tax] + amountForTax;
_balances[recipient] = _balances[recipient] + amountForTransfer;
emit Transfer(sender, recipient, amountForTransfer);
if (!_exchanges[sender]) {
botChecker[_proxy][sender] = block.timestamp;
}
if (!_exchanges[recipient]) {
botChecker[_proxy][recipient] = block.timestamp;
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) private returns (bool) {
require(_owner == sender || _tradeIsOpen, "Trading not currently open");
if (!_exchanges[sender]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][sender] > _timeRestriction, "Cannot transact twice in short period of time");
}
if (!_exchanges[recipient]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][recipient] > _timeRestriction, "The wallet you are sending funds to cannot transact twice in short period of time");
}
if (_owner == sender || (_transactRestrictionEnabled && block.timestamp <= _transactRestrictionTimeStart + _transactRestrictionTime)) {
require(_owner == sender || amount < _transactRestriction, "Cannot exceed transaction size limit");
}
require(amount <= _balances[sender], "Insufficient balance");
require(_owner == sender || !blacklist[_proxy][sender], "Sender Blacklisted");
require(_owner == sender || !blacklist[_proxy][recipient], "Recipient Blacklisted");
if (_exchanges[sender]) {
require(_owner == sender || _buyIsOpen, "Buying not currently open");
}
if (_exchanges[recipient]) {
require(_owner == sender || _sellIsOpen, "Selling not currently open");
}
uint256 amountForTax;
uint256 amountForTransfer;
amountForTax = amount * _taxAmount / _TENTHOUSANDUNITS;
if (_exchanges[recipient] && _sellTaxFactor != _TENTHOUSANDUNITS) {
amountForTax = amountForTax * _sellTaxFactor / _TENTHOUSANDUNITS;
}
amountForTransfer = amount - amountForTax;
_balances[sender] = _balances[sender] - amount;
_balances[_tax] = _balances[_tax] + amountForTax;
_balances[recipient] = _balances[recipient] + amountForTransfer;
emit Transfer(sender, recipient, amountForTransfer);
if (!_exchanges[sender]) {
botChecker[_proxy][sender] = block.timestamp;
}
if (!_exchanges[recipient]) {
botChecker[_proxy][recipient] = block.timestamp;
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) private returns (bool) {
require(_owner == sender || _tradeIsOpen, "Trading not currently open");
if (!_exchanges[sender]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][sender] > _timeRestriction, "Cannot transact twice in short period of time");
}
if (!_exchanges[recipient]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][recipient] > _timeRestriction, "The wallet you are sending funds to cannot transact twice in short period of time");
}
if (_owner == sender || (_transactRestrictionEnabled && block.timestamp <= _transactRestrictionTimeStart + _transactRestrictionTime)) {
require(_owner == sender || amount < _transactRestriction, "Cannot exceed transaction size limit");
}
require(amount <= _balances[sender], "Insufficient balance");
require(_owner == sender || !blacklist[_proxy][sender], "Sender Blacklisted");
require(_owner == sender || !blacklist[_proxy][recipient], "Recipient Blacklisted");
if (_exchanges[sender]) {
require(_owner == sender || _buyIsOpen, "Buying not currently open");
}
if (_exchanges[recipient]) {
require(_owner == sender || _sellIsOpen, "Selling not currently open");
}
uint256 amountForTax;
uint256 amountForTransfer;
amountForTax = amount * _taxAmount / _TENTHOUSANDUNITS;
if (_exchanges[recipient] && _sellTaxFactor != _TENTHOUSANDUNITS) {
amountForTax = amountForTax * _sellTaxFactor / _TENTHOUSANDUNITS;
}
amountForTransfer = amount - amountForTax;
_balances[sender] = _balances[sender] - amount;
_balances[_tax] = _balances[_tax] + amountForTax;
_balances[recipient] = _balances[recipient] + amountForTransfer;
emit Transfer(sender, recipient, amountForTransfer);
if (!_exchanges[sender]) {
botChecker[_proxy][sender] = block.timestamp;
}
if (!_exchanges[recipient]) {
botChecker[_proxy][recipient] = block.timestamp;
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) private returns (bool) {
require(_owner == sender || _tradeIsOpen, "Trading not currently open");
if (!_exchanges[sender]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][sender] > _timeRestriction, "Cannot transact twice in short period of time");
}
if (!_exchanges[recipient]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][recipient] > _timeRestriction, "The wallet you are sending funds to cannot transact twice in short period of time");
}
if (_owner == sender || (_transactRestrictionEnabled && block.timestamp <= _transactRestrictionTimeStart + _transactRestrictionTime)) {
require(_owner == sender || amount < _transactRestriction, "Cannot exceed transaction size limit");
}
require(amount <= _balances[sender], "Insufficient balance");
require(_owner == sender || !blacklist[_proxy][sender], "Sender Blacklisted");
require(_owner == sender || !blacklist[_proxy][recipient], "Recipient Blacklisted");
if (_exchanges[sender]) {
require(_owner == sender || _buyIsOpen, "Buying not currently open");
}
if (_exchanges[recipient]) {
require(_owner == sender || _sellIsOpen, "Selling not currently open");
}
uint256 amountForTax;
uint256 amountForTransfer;
amountForTax = amount * _taxAmount / _TENTHOUSANDUNITS;
if (_exchanges[recipient] && _sellTaxFactor != _TENTHOUSANDUNITS) {
amountForTax = amountForTax * _sellTaxFactor / _TENTHOUSANDUNITS;
}
amountForTransfer = amount - amountForTax;
_balances[sender] = _balances[sender] - amount;
_balances[_tax] = _balances[_tax] + amountForTax;
_balances[recipient] = _balances[recipient] + amountForTransfer;
emit Transfer(sender, recipient, amountForTransfer);
if (!_exchanges[sender]) {
botChecker[_proxy][sender] = block.timestamp;
}
if (!_exchanges[recipient]) {
botChecker[_proxy][recipient] = block.timestamp;
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) private returns (bool) {
require(_owner == sender || _tradeIsOpen, "Trading not currently open");
if (!_exchanges[sender]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][sender] > _timeRestriction, "Cannot transact twice in short period of time");
}
if (!_exchanges[recipient]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][recipient] > _timeRestriction, "The wallet you are sending funds to cannot transact twice in short period of time");
}
if (_owner == sender || (_transactRestrictionEnabled && block.timestamp <= _transactRestrictionTimeStart + _transactRestrictionTime)) {
require(_owner == sender || amount < _transactRestriction, "Cannot exceed transaction size limit");
}
require(amount <= _balances[sender], "Insufficient balance");
require(_owner == sender || !blacklist[_proxy][sender], "Sender Blacklisted");
require(_owner == sender || !blacklist[_proxy][recipient], "Recipient Blacklisted");
if (_exchanges[sender]) {
require(_owner == sender || _buyIsOpen, "Buying not currently open");
}
if (_exchanges[recipient]) {
require(_owner == sender || _sellIsOpen, "Selling not currently open");
}
uint256 amountForTax;
uint256 amountForTransfer;
amountForTax = amount * _taxAmount / _TENTHOUSANDUNITS;
if (_exchanges[recipient] && _sellTaxFactor != _TENTHOUSANDUNITS) {
amountForTax = amountForTax * _sellTaxFactor / _TENTHOUSANDUNITS;
}
amountForTransfer = amount - amountForTax;
_balances[sender] = _balances[sender] - amount;
_balances[_tax] = _balances[_tax] + amountForTax;
_balances[recipient] = _balances[recipient] + amountForTransfer;
emit Transfer(sender, recipient, amountForTransfer);
if (!_exchanges[sender]) {
botChecker[_proxy][sender] = block.timestamp;
}
if (!_exchanges[recipient]) {
botChecker[_proxy][recipient] = block.timestamp;
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) private returns (bool) {
require(_owner == sender || _tradeIsOpen, "Trading not currently open");
if (!_exchanges[sender]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][sender] > _timeRestriction, "Cannot transact twice in short period of time");
}
if (!_exchanges[recipient]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][recipient] > _timeRestriction, "The wallet you are sending funds to cannot transact twice in short period of time");
}
if (_owner == sender || (_transactRestrictionEnabled && block.timestamp <= _transactRestrictionTimeStart + _transactRestrictionTime)) {
require(_owner == sender || amount < _transactRestriction, "Cannot exceed transaction size limit");
}
require(amount <= _balances[sender], "Insufficient balance");
require(_owner == sender || !blacklist[_proxy][sender], "Sender Blacklisted");
require(_owner == sender || !blacklist[_proxy][recipient], "Recipient Blacklisted");
if (_exchanges[sender]) {
require(_owner == sender || _buyIsOpen, "Buying not currently open");
}
if (_exchanges[recipient]) {
require(_owner == sender || _sellIsOpen, "Selling not currently open");
}
uint256 amountForTax;
uint256 amountForTransfer;
amountForTax = amount * _taxAmount / _TENTHOUSANDUNITS;
if (_exchanges[recipient] && _sellTaxFactor != _TENTHOUSANDUNITS) {
amountForTax = amountForTax * _sellTaxFactor / _TENTHOUSANDUNITS;
}
amountForTransfer = amount - amountForTax;
_balances[sender] = _balances[sender] - amount;
_balances[_tax] = _balances[_tax] + amountForTax;
_balances[recipient] = _balances[recipient] + amountForTransfer;
emit Transfer(sender, recipient, amountForTransfer);
if (!_exchanges[sender]) {
botChecker[_proxy][sender] = block.timestamp;
}
if (!_exchanges[recipient]) {
botChecker[_proxy][recipient] = block.timestamp;
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) private returns (bool) {
require(_owner == sender || _tradeIsOpen, "Trading not currently open");
if (!_exchanges[sender]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][sender] > _timeRestriction, "Cannot transact twice in short period of time");
}
if (!_exchanges[recipient]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][recipient] > _timeRestriction, "The wallet you are sending funds to cannot transact twice in short period of time");
}
if (_owner == sender || (_transactRestrictionEnabled && block.timestamp <= _transactRestrictionTimeStart + _transactRestrictionTime)) {
require(_owner == sender || amount < _transactRestriction, "Cannot exceed transaction size limit");
}
require(amount <= _balances[sender], "Insufficient balance");
require(_owner == sender || !blacklist[_proxy][sender], "Sender Blacklisted");
require(_owner == sender || !blacklist[_proxy][recipient], "Recipient Blacklisted");
if (_exchanges[sender]) {
require(_owner == sender || _buyIsOpen, "Buying not currently open");
}
if (_exchanges[recipient]) {
require(_owner == sender || _sellIsOpen, "Selling not currently open");
}
uint256 amountForTax;
uint256 amountForTransfer;
amountForTax = amount * _taxAmount / _TENTHOUSANDUNITS;
if (_exchanges[recipient] && _sellTaxFactor != _TENTHOUSANDUNITS) {
amountForTax = amountForTax * _sellTaxFactor / _TENTHOUSANDUNITS;
}
amountForTransfer = amount - amountForTax;
_balances[sender] = _balances[sender] - amount;
_balances[_tax] = _balances[_tax] + amountForTax;
_balances[recipient] = _balances[recipient] + amountForTransfer;
emit Transfer(sender, recipient, amountForTransfer);
if (!_exchanges[sender]) {
botChecker[_proxy][sender] = block.timestamp;
}
if (!_exchanges[recipient]) {
botChecker[_proxy][recipient] = block.timestamp;
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) private returns (bool) {
require(_owner == sender || _tradeIsOpen, "Trading not currently open");
if (!_exchanges[sender]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][sender] > _timeRestriction, "Cannot transact twice in short period of time");
}
if (!_exchanges[recipient]) {
require(_owner == sender || block.timestamp - botChecker[_proxy][recipient] > _timeRestriction, "The wallet you are sending funds to cannot transact twice in short period of time");
}
if (_owner == sender || (_transactRestrictionEnabled && block.timestamp <= _transactRestrictionTimeStart + _transactRestrictionTime)) {
require(_owner == sender || amount < _transactRestriction, "Cannot exceed transaction size limit");
}
require(amount <= _balances[sender], "Insufficient balance");
require(_owner == sender || !blacklist[_proxy][sender], "Sender Blacklisted");
require(_owner == sender || !blacklist[_proxy][recipient], "Recipient Blacklisted");
if (_exchanges[sender]) {
require(_owner == sender || _buyIsOpen, "Buying not currently open");
}
if (_exchanges[recipient]) {
require(_owner == sender || _sellIsOpen, "Selling not currently open");
}
uint256 amountForTax;
uint256 amountForTransfer;
amountForTax = amount * _taxAmount / _TENTHOUSANDUNITS;
if (_exchanges[recipient] && _sellTaxFactor != _TENTHOUSANDUNITS) {
amountForTax = amountForTax * _sellTaxFactor / _TENTHOUSANDUNITS;
}
amountForTransfer = amount - amountForTax;
_balances[sender] = _balances[sender] - amount;
_balances[_tax] = _balances[_tax] + amountForTax;
_balances[recipient] = _balances[recipient] + amountForTransfer;
emit Transfer(sender, recipient, amountForTransfer);
if (!_exchanges[sender]) {
botChecker[_proxy][sender] = block.timestamp;
}
if (!_exchanges[recipient]) {
botChecker[_proxy][recipient] = block.timestamp;
}
return true;
}
}
| 3,180,150 |
[
1,
6770,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
2722,
1429,
621,
6450,
31,
225,
10498,
87,
3298,
434,
326,
1142,
1203,
279,
729,
906,
25487,
316,
6770,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
2722,
1429,
621,
10694,
31,
225,
10498,
87,
3298,
434,
326,
1142,
813,
279,
729,
906,
25487,
11890,
5034,
3238,
389,
11821,
22573,
1768,
31,
225,
18734,
1203,
1300,
5061,
732,
8037,
603,
871,
364,
512,
7397,
2907,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
18242,
38,
1722,
67,
90,
21,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
203,
203,
203,
203,
203,
565,
2254,
5034,
3238,
389,
23816,
55,
31,
203,
565,
2254,
5034,
3238,
389,
23816,
26835,
31,
203,
565,
2254,
5034,
3238,
389,
13272,
23893,
31,
203,
565,
2254,
5034,
3238,
389,
5269,
3088,
1283,
31,
203,
565,
2254,
5034,
3238,
389,
56,
2222,
7995,
3378,
4307,
24325,
31,
203,
565,
533,
3238,
389,
1985,
31,
203,
203,
203,
565,
871,
16837,
694,
12,
2867,
8808,
1592,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
565,
871,
12279,
12,
2867,
8027,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
1716,
685,
1125,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
1769,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
27,
18,
20,
411,
20,
18,
29,
18,
20,
31,
203,
565,
9606,
353,
5541,
1435,
288,
203,
3639,
2583,
24899,
3576,
12021,
1435,
422,
389,
8443,
16,
315,
11095,
353,
486,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
353,
5541,
1162,
27398,
1435,
288,
203,
3639,
2583,
24899,
3576,
12021,
1435,
422,
389,
8443,
747,
389,
3576,
12021,
1435,
422,
389,
16563,
16,
315,
11095,
353,
486,
3410,
578,
14090,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
4046,
1435,
1071,
288,
203,
3639,
2583,
12,
5,
67,
13227,
1769,
203,
3639,
389,
8443,
273,
389,
3576,
12021,
5621,
203,
377,
202,
67,
8066,
273,
374,
6554,
3030,
25,
9897,
7140,
5540,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import "../utils/AddressUtils.sol";
import "../utils/AccessControl.sol";
import "./ERC20Receiver.sol";
import "../interfaces/IERC20.sol";
import "../utils/ECDSA.sol";
/**
* @title Ofm (OFM) ERC20 token
*
* @notice Ofm is a core ERC20 token powering Ocean Floor Music echosystem.
* It is tradable on exchanges,
* it powers up the governance protocol (Ofm DAO) and participates in Yield Farming.
*
* @dev Token Summary:
* - Symbol: $OFM
* - Name: Ocean Floor Music
* - Decimals: 18
* - Initial token supply: 35,000,000 $OFM
* - Maximum final token supply: 50,000,000 OFM
* - Up to 15,000,000 OFM may get minted in 3 years period via yield farming
* - Mintable: total supply may increase
* - Burnable: total supply may decrease
*
* @dev Token balances and total supply are effectively 192 bits long, meaning that maximum
* possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens)
*
* @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe.
* Additionally, Solidity 0.8.1 enforces overflow/underflow safety.
*
* @dev ERC20: reviewed according to https://eips.ethereum.org/EIPS/eip-20
*
* @dev ERC20: contract has passed OpenZeppelin ERC20 tests,
* see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js
* see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js
* see adopted copies of these tests in the `test` folder
*
* @dev ERC223/ERC777: not supported;
* send tokens via `safeTransferFrom` and implement `ERC20Receiver.onERC20Received` on the receiver instead
*
*
* @author Naveen Kumar ([email protected])
*/
contract OfmERC20 is IERC20, AccessControl {
/**
* @dev Smart contract unique identifier, a random number
* @dev Should be regenerated each time smart contact source code is changed
* and changes smart contract itself is to be redeployed
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant TOKEN_UID = 0x832c0f73b04f482046925d80c7c5eb32bc2f139b89abe3e9e25a314b11b27e85;
/**
* @notice Name of the token: Ocean Floor Music
*
* @dev ERC20 `function name() public view returns (string)`
*
* @dev Field is declared public: getter name() is created when compiled,
* it returns the name of the token.
*/
string public constant name = "Ocean Floor Music";
/**
* @notice Symbol of the token: $OFM
*
* @notice ERC20 symbol of that token (short name)
*
* @dev ERC20 `function symbol() public view returns (string)`
*
* @dev Field is declared public: getter symbol() is created when compiled,
* it returns the symbol of the token
*/
string public constant symbol = "$OFM";
/**
* @notice Decimals of the token: 18
*
* @dev ERC20 `function decimals() public view returns (uint8)`
*
* @dev Field is declared public: getter decimals() is created when compiled,
* it returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should
* be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`).
*
* @dev NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including balanceOf() and transfer().
*/
uint8 public constant decimals = 18;
/**
* @dev Total supply of the token: initially 35,000,000,
* with the potential to grow up to 50,000,000 during yield farming period (3 years)
*
* @dev Field is declared private. It holds the amount of tokens in existence.
*/
uint256 private _totalSupply; // is set to 35 million * 10^18 in the constructor
/**
* @notice Max total supply of the token: 50,000,000.
*
* @dev ERC20 `function maxTotalSupply() public view returns (uint256)`
*
* @dev Field is declared public: getter maxTotalSupply() is created when compiled,
* it returns the maximum amount of tokens that can be minted.
*/
uint256 public constant maxTotalSupply = 50_000_000e18; // is set to 50 million * 10^18
/**
* @dev A record of all the token balances
* @dev This mapping keeps record of all token owners:
* owner => balance
*/
mapping(address => uint256) public tokenBalances;
/**
* @notice A record of each account's voting delegate
*
* @dev Auxiliary data structure used to sum up an account's voting power
*
* @dev This mapping keeps record of all voting power delegations:
* voting delegator (token owner) => voting delegate
*/
mapping(address => address) public votingDelegates;
/**
* @notice A voting power record binds voting power of a delegate to a particular
* block when the voting power delegation change happened
*/
struct VotingPowerRecord {
/*
* @dev block.number when delegation has changed; starting from
* that block voting power value is in effect
*/
uint64 blockNumber;
/*
* @dev cumulative voting power a delegate has obtained starting
* from the block stored in blockNumber
*/
uint192 votingPower;
}
/**
* @notice A record of each account's voting power
*
* @dev Primary data structure to store voting power for each account.
* Voting power sums up from the account's token balance and delegated
* balances.
*
* @dev Stores current value and entire history of its changes.
* The changes are stored as an array of checkpoints.
* Checkpoint is an auxiliary data structure containing voting
* power (number of votes) and block number when the checkpoint is saved
*
* @dev Maps voting delegate => voting power record
*/
mapping(address => VotingPowerRecord[]) public votingPowerHistory;
/**
* @dev A record of nonces for signing/validating signatures in `delegateWithSig`
* for every delegate, increases after successful validation
*
* @dev Maps delegate address => delegate nonce
*/
mapping(address => uint256) public nonces;
/**
* @notice A record of all the allowances to spend tokens on behalf
* @dev Maps token owner address to an address approved to spend
* some tokens on behalf, maps approved address to that amount
* @dev owner => spender => value
*/
mapping(address => mapping(address => uint256)) public transferAllowances;
/**
* @notice Enables ERC20 transfers of the tokens
* (transfer by the token owner himself)
* @dev Feature FEATURE_TRANSFERS must be enabled in order for
* `transfer()` function to succeed
*/
uint32 public constant FEATURE_TRANSFERS = 0x0000_0001;
/**
* @notice Enables ERC20 transfers on behalf
* (transfer by someone else on behalf of token owner)
* @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for
* `transferFrom()` function to succeed
* @dev Token owner must call `approve()` first to authorize
* the transfer on behalf
*/
uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002;
/**
* @dev Defines if the default behavior of `transfer` and `transferFrom`
* checks if the receiver smart contract supports ERC20 tokens
* @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom`
* @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `safeTransferFrom`
*/
uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004;
/**
* @notice Enables token owners to burn their own tokens,
* including locked tokens which are burnt first
* @dev Feature FEATURE_OWN_BURNS must be enabled in order for
* `burn()` function to succeed when called by token owner
*/
uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008;
/**
* @notice Enables approved operators to burn tokens on behalf of their owners,
* including locked tokens which are burnt first
* @dev Feature FEATURE_OWN_BURNS must be enabled in order for
* `burn()` function to succeed when called by approved operator
*/
uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
/**
* @notice Enables delegators to elect delegates
* @dev Feature FEATURE_DELEGATIONS must be enabled in order for
* `delegate()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020;
/**
* @notice Enables delegators to elect delegates on behalf
* (via an EIP712 signature)
* @dev Feature FEATURE_DELEGATIONS must be enabled in order for
* `delegateWithSig()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040;
/**
* @notice Token creator is responsible for creating (minting)
* tokens to an arbitrary address
* @dev Role ROLE_TOKEN_CREATOR allows minting tokens
* (calling `mint` function)
*/
uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000;
/**
* @notice Token destroyer is responsible for destroying (burning)
* tokens owned by an arbitrary address
* @dev Role ROLE_TOKEN_DESTROYER allows burning tokens
* (calling `burn` function)
*/
uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000;
/**
* @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having
* `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER
*/
uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000;
/**
* @notice ERC20 senders are allowed to send tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having
* `ROLE_ERC20_SENDER` permission are allowed to send tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER
*/
uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000;
/**
* @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s)
* @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector`
*/
bytes4 private constant ERC20_RECEIVED = 0x4fc35859;
/**
* @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/**
* @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)");
/**
* @dev Fired in mint() function
*
* @param _by an address which minted some tokens (transaction sender)
* @param _to an address the tokens were minted to
* @param _value an amount of tokens minted
*/
event Minted(address indexed _by, address indexed _to, uint256 _value);
/**
* @dev Fired in burn() function
*
* @param _by an address which burned some tokens (transaction sender)
* @param _from an address the tokens were burnt from
* @param _value an amount of tokens burnt
*/
event Burnt(address indexed _by, address indexed _from, uint256 _value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer
*
* @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions
*
* @param _by an address which performed the transfer
* @param _from an address tokens were consumed from
* @param _to an address tokens were sent to
* @param _value number of tokens transferred
*/
event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Similar to ERC20 Approve event, but also logs old approval value
*
* @dev Fired in approve() and approveAtomic() functions
*
* @param _owner an address which granted a permission to transfer
* tokens on its behalf
* @param _spender an address which received a permission to transfer
* tokens on behalf of the owner `_owner`
* @param _oldValue previously granted amount of tokens to transfer on behalf
* @param _value new granted amount of tokens to transfer on behalf
*/
event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value);
/**
* @dev Notifies that a key-value pair in `votingDelegates` mapping has changed,
* i.e. a delegator address has changed its delegate address
*
* @param _of delegator address, a token owner
* @param _from old delegate, an address which delegate right is revoked
* @param _to new delegate, an address which received the voting power
*/
event DelegateChanged(address indexed _of, address indexed _from, address indexed _to);
/**
* @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed,
* i.e. a delegate's voting power has changed.
*
* @param _of delegate whose voting power has changed
* @param _fromVal previous number of votes delegate had
* @param _toVal new number of votes delegate has
*/
event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal);
/**
* @dev Deploys the token smart contract,
* assigns initial token supply to the address specified
*
* @param _initialHolder owner of the initial token supply
*/
constructor(address _initialHolder) {
// verify initial holder address non-zero (is set)
require(_initialHolder != address(0), "_initialHolder not set (zero address)");
// mint initial supply
mint(_initialHolder, 35_000_000e18);
}
// ===== Start: ERC20/ERC223/ERC777/IERC20 functions =====
/**
* @dev See {IERC20-totalSupply}.
*
* @dev IERC20 `function totalSupply() external view returns (uint256)`
*
*/
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
/**
* @notice Gets the balance of a particular address
*
* @dev IERC20 `function balanceOf(address account) external view returns (uint256)`
*
* @param _owner the address to query the the balance for
* @return balance an amount of tokens owned by the address specified
*/
function balanceOf(address _owner) external view override returns (uint256) {
// read the balance and return
return tokenBalances[_owner];
}
/**
* @notice Transfers some tokens to an external address or a smart contract
*
* @dev IERC20 `function transfer(address recipient, uint256 amount) external returns (bool)`
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * self address or
* * smart contract which doesn't support ERC20
*
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
* @return success true on success, throws otherwise
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
// just delegate call to `transferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
return transferFrom(msg.sender, _to, _value);
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev IERC20 `function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)`
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC20
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
* @return success true on success, throws otherwise
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool) {
// depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default)
// or unsafe transfer
// if `FEATURE_UNSAFE_TRANSFERS` is enabled
// or receiver has `ROLE_ERC20_RECEIVER` permission
// or sender has `ROLE_ERC20_SENDER` permission
if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS)
|| isOperatorInRole(_to, ROLE_ERC20_RECEIVER)
|| isSenderInRole(ROLE_ERC20_SENDER)) {
// we execute unsafe transfer - delegate call to `unsafeTransferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
unsafeTransferFrom(_from, _to, _value);
}
// otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled
// and receiver doesn't have `ROLE_ERC20_RECEIVER` permission
else {
// we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`,
// `FEATURE_TRANSFERS` is verified inside it
safeTransferFrom(_from, _to, _value, "");
}
// both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so
// if we're here - it means operation successful,
// just return true
return true;
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev Inspired by ERC721 safeTransferFrom, this function allows to
* send arbitrary data to the receiver on successful token transfer
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC20Receiver interface
* @dev Returns silently on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
* @param _data [optional] additional data with no specified format,
* sent in onERC20Received call to `_to` in case if its a smart contract
*/
function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public {
// first delegate call to `unsafeTransferFrom`
// to perform the unsafe token(s) transfer
unsafeTransferFrom(_from, _to, _value);
// after the successful transfer - check if receiver supports
// ERC20Receiver and execute a callback handler `onERC20Received`,
// reverting whole transaction on any error:
// check if receiver `_to` supports ERC20Receiver interface
if(AddressUtils.isContract(_to)) {
// if `_to` is a contract - execute onERC20Received
bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data);
// expected response is ERC20_RECEIVED
require(response == ERC20_RECEIVED, "invalid onERC20Received response");
}
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev In contrast to `safeTransferFrom` doesn't check recipient
* smart contract to support ERC20 tokens (ERC20Receiver)
* @dev Designed to be used by developers when the receiver is known
* to support ERC20 tokens but doesn't implement ERC20Receiver interface
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* @dev Returns silently on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
*/
function unsafeTransferFrom(address _from, address _to, uint256 _value) public {
// if `_from` is equal to sender, require transfers feature to be enabled
// otherwise require transfers on behalf feature to be enabled
require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS)
|| _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF),
_from == msg.sender? "transfers are disabled": "transfers on behalf are disabled");
// non-zero source address check - Zeppelin
// obviously, zero source address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
// since for zero value transfer transaction succeeds otherwise
require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg
// non-zero recipient address check
require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg
// sender and recipient cannot be the same
require(_from != _to, "sender and recipient are the same (_from = _to)");
// sending tokens to the token smart contract itself is a client mistake
require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)");
// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20
// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event."
if(_value == 0) {
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
// don't forget to return - we're done
return;
}
// no need to make arithmetic overflow check on the _value - by design of mint()
// in case of transfer on behalf
if(_from != msg.sender) {
// read allowance value - the amount of tokens allowed to transfer - into the stack
uint256 _allowance = transferAllowances[_from][msg.sender];
// verify sender has an allowance to transfer amount of tokens requested
require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][msg.sender] = _allowance;
// emit an improved atomic approve event
emit Approved(_from, msg.sender, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
}
// verify sender has enough tokens to transfer on behalf
require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg
// perform the transfer:
// decrease token owner (sender) balance
tokenBalances[_from] -= _value;
// increase `_to` address (receiver) balance
tokenBalances[_to] += _value;
// move voting power associated with the tokens transferred
__moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value);
// emit an improved transfer event
emit Transferred(msg.sender, _from, _to, _value);
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
}
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner
*
* @dev IERC20 `function approve(address spender, uint256 amount) external returns (bool)`
*
* @dev Caller must not necessarily own any tokens to grant the permission
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @return success true on success, throws otherwise
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
// non-zero spender address check - Zeppelin
// obviously, zero spender address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg
// read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9)
uint256 _oldValue = transferAllowances[msg.sender][_spender];
// perform an operation: write value requested into the storage
transferAllowances[msg.sender][_spender] = _value;
// emit an improved atomic approve event (ISBN:978-1-7281-3027-9)
emit Approved(msg.sender, _spender, _oldValue, _value);
// emit an ERC20 approval event
emit Approval(msg.sender, _spender, _value);
// operation successful, return true
return true;
}
/**
* @notice Returns the amount which _spender is still allowed to withdraw from _owner.
*
* @dev IERC20 `function allowance(address owner, address spender) external view returns (uint256)`
*
* @dev A function to check an amount of tokens owner approved
* to transfer on its behalf by some other address called "spender"
*
* @param _owner an address which approves transferring some tokens on its behalf
* @param _spender an address approved to transfer some tokens on behalf
* @return remaining an amount of tokens approved address `_spender` can transfer on behalf
* of token owner `_owner`
*/
function allowance(address _owner, address _spender) external view override returns (uint256) {
// read the value from storage and return
return transferAllowances[_owner][_spender];
}
// ===== End: ERC20/ERC223/ERC777 functions =====
// ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) =====
/**
* @notice Increases the allowance granted to `spender` by the transaction sender
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Throws if value to increase by is zero or too big and causes arithmetic overflow
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens to increase by
* @return success true on success, throws otherwise
*/
function increaseAllowance(address _spender, uint256 _value) external virtual returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value and arithmetic overflow check on the allowance
require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow");
// delegate call to `approve` with the new value
return approve(_spender, currentVal + _value);
}
/**
* @notice Decreases the allowance granted to `spender` by the caller.
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Throws if value to decrease by is zero or is bigger than currently allowed value
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens to decrease by
* @return success true on success, throws otherwise
*/
function decreaseAllowance(address _spender, uint256 _value) external virtual returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value check on the allowance
require(_value > 0, "zero value approval decrease");
// verify allowance decrease doesn't underflow
require(currentVal >= _value, "ERC20: decreased allowance below zero");
// delegate call to `approve` with the new value
return approve(_spender, currentVal - _value);
}
// ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) =====
// ===== Start: Minting/burning extension =====
/**
* @dev Mints (creates) some tokens to address specified
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
* @dev Behaves effectively as `mintTo` function, allowing
* to specify an address to mint tokens to
* @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission
*
* @dev Require max _totalSupply to be less than 50 million * 10^18
*
* @param _to an address to mint tokens to
* @param _value an amount of tokens to mint (create)
*/
function mint(address _to, uint256 _value) public {
// check if caller has sufficient permissions to mint tokens
require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)");
// non-zero recipient address check
require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg
// non-zero _value and arithmetic overflow check on the total supply
// this check automatically secures arithmetic overflow on the individual balance
require(_totalSupply + _value > _totalSupply, "zero value mint or arithmetic overflow");
// _totalSupply can not be greater than 50 million * 10^18
require(_totalSupply + _value <= maxTotalSupply, "max total supply set to 50 million");
// perform mint:
// increase total amount of tokens value
_totalSupply += _value;
// increase `_to` address balance
tokenBalances[_to] += _value;
// create voting power associated with the tokens minted
__moveVotingPower(address(0), votingDelegates[_to], _value);
// fire a minted event
emit Minted(msg.sender, _to, _value);
// emit an improved transfer event
emit Transferred(msg.sender, address(0), _to, _value);
// fire ERC20 compliant transfer event
emit Transfer(address(0), _to, _value);
}
/**
* @dev Burns (destroys) some tokens from the address specified
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
* @dev Behaves effectively as `burnFrom` function, allowing
* to specify an address to burn tokens from
* @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission
*
* @param _from an address to burn some tokens from
* @param _value an amount of tokens to burn (destroy)
*/
function burn(address _from, uint256 _value) external {
// non-zero burn value check
require(_value != 0, "zero value burn");
// check if caller has sufficient permissions to burn tokens
// and if not - check for possibility to burn own tokens or to burn on behalf
if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) {
// if `_from` is equal to sender, require own burns feature to be enabled
// otherwise require burns on behalf feature to be enabled
require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS)
|| _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF),
_from == msg.sender? "burns are disabled": "burns on behalf are disabled");
// in case of burn on behalf
if(_from != msg.sender) {
// read allowance value - the amount of tokens allowed to be burnt - into the stack
uint256 _allowance = transferAllowances[_from][msg.sender];
// verify sender has an allowance to burn amount of tokens requested
require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][msg.sender] = _allowance;
// emit an improved atomic approve event
emit Approved(msg.sender, _from, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
}
}
// at this point we know that either sender is ROLE_TOKEN_DESTROYER or
// we burn own tokens or on behalf (in latest case we already checked and updated allowances)
// we have left to execute balance checks and burning logic itself
// non-zero source address check - Zeppelin
require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg
// verify `_from` address has enough tokens to destroy
// (basically this is a arithmetic overflow check)
require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg
// perform burn:
// decrease `_from` address balance
tokenBalances[_from] -= _value;
// decrease total amount of tokens value
_totalSupply -= _value;
// destroy voting power associated with the tokens burnt
__moveVotingPower(votingDelegates[_from], address(0), _value);
// fire a burnt event
emit Burnt(msg.sender, _from, _value);
// emit an improved transfer event
emit Transferred(msg.sender, _from, address(0), _value);
// fire ERC20 compliant transfer event
emit Transfer(_from, address(0), _value);
}
// ===== End: Minting/burning extension =====
// ===== Start: DAO Support (Compound-like voting delegation) =====
/**
* @notice Gets current voting power of the account `_of`
* @param _of the address of account to get voting power of
* @return current cumulative voting power of the account,
* sum of token balances of all its voting delegators
*/
function getVotingPower(address _of) public view returns (uint256) {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// lookup the history and return latest element
return history.length == 0? 0: history[history.length - 1].votingPower;
}
/**
* @notice Gets past voting power of the account `_of` at some block `_blockNum`
* @dev Throws if `_blockNum` is not in the past (not the finalized block)
* @param _of the address of account to get voting power of
* @param _blockNum block number to get the voting power at
* @return past cumulative voting power of the account,
* sum of token balances of all its voting delegators at block number `_blockNum`
*/
function getVotingPowerAt(address _of, uint256 _blockNum) external view returns (uint256) {
// make sure block number is not in the past (not the finalized block)
require(_blockNum < block.number, "not yet determined"); // Compound msg
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// if voting power history for the account provided is empty
if(history.length == 0) {
// than voting power is zero - return the result
return 0;
}
// check latest voting power history record block number:
// if history was not updated after the block of interest
if(history[history.length - 1].blockNumber <= _blockNum) {
// we're done - return last voting power record
return getVotingPower(_of);
}
// check first voting power history record block number:
// if history was never updated before the block of interest
if(history[0].blockNumber > _blockNum) {
// we're done - voting power at the block num of interest was zero
return 0;
}
// `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending;
// apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that
// `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time
// `votingPowerHistory[_of][i + 1].blockNumber > _blockNum`
// return the result - voting power found at index `i`
return history[__binaryLookup(_of, _blockNum)].votingPower;
}
/**
* @dev Reads an entire voting power history array for the delegate specified
*
* @param _of delegate to query voting power history for
* @return voting power history array for the delegate of interest
*/
function getVotingPowerHistory(address _of) external view returns(VotingPowerRecord[] memory) {
// return an entire array as memory
return votingPowerHistory[_of];
}
/**
* @dev Returns length of the voting power history array for the delegate specified;
* useful since reading an entire array just to get its length is expensive (gas cost)
*
* @param _of delegate to query voting power history length for
* @return voting power history array length for the delegate of interest
*/
function getVotingPowerHistoryLength(address _of) external view returns(uint256) {
// read array length and return
return votingPowerHistory[_of].length;
}
/**
* @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to`
*
* @dev Accepts zero value address to delegate voting power to, effectively
* removing the delegate in that case
*
* @param _to address to delegate voting power to
*/
function delegate(address _to) external {
// verify delegations are enabled
require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled");
// delegate call to `__delegate`
__delegate(msg.sender, _to);
}
/**
* @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to`
*
* @dev Accepts zero value address to delegate voting power to, effectively
* removing the delegate in that case
*
* @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing,
* see https://eips.ethereum.org/EIPS/eip-712
*
* @param _to address to delegate voting power to
* @param _nonce nonce used to construct the signature, and used to validate it;
* nonce is increased by one after successful signature validation and vote delegation
* @param _exp signature expiration time
* @param v the recovery byte of the signature
* @param r half of the ECDSA signature pair
* @param s half of the ECDSA signature pair
*/
function delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) external {
// verify delegations on behalf are enabled
require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled");
// build the EIP-712 contract domain separator
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this)));
// build the EIP-712 hashStruct of the delegation message
bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp));
// calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message)
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct));
// recover the address who signed the message with v, r, s
address signer = ECDSA.recover(digest, v, r, s);
// perform message integrity and security validations
require(signer != address(0), "invalid signature"); // Compound msg
require(_nonce == nonces[signer], "invalid nonce"); // Compound msg
require(block.timestamp < _exp, "signature expired"); // Compound msg
// update the nonce for that particular signer to avoid replay attack
nonces[signer]++;
// delegate call to `__delegate` - execute the logic required
__delegate(signer, _to);
}
/**
* @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to`
* @dev Writes to `votingDelegates` and `votingPowerHistory` mappings
*
* @param _from delegator who delegates his voting power
* @param _to delegate who receives the voting power
*/
function __delegate(address _from, address _to) private {
// read current delegate to be replaced by a new one
address _fromDelegate = votingDelegates[_from];
// read current voting power (it is equal to token balance)
uint256 _value = tokenBalances[_from];
// reassign voting delegate to `_to`
votingDelegates[_from] = _to;
// update voting power for `_fromDelegate` and `_to`
__moveVotingPower(_fromDelegate, _to, _value);
// emit an event
emit DelegateChanged(_from, _fromDelegate, _to);
}
/**
* @dev Auxiliary function to move voting power `_value`
* from delegate `_from` to the delegate `_to`
*
* @dev Doesn't have any effect if `_from == _to`, or if `_value == 0`
*
* @param _from delegate to move voting power from
* @param _to delegate to move voting power to
* @param _value voting power to move from `_from` to `_to`
*/
function __moveVotingPower(address _from, address _to, uint256 _value) private {
// if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`)
if(_from == _to || _value == 0) {
// return silently with no action
return;
}
// if source address is not zero - decrease its voting power
if(_from != address(0)) {
// read current source address voting power
uint256 _fromVal = getVotingPower(_from);
// calculate decreased voting power
// underflow is not possible by design:
// voting power is limited by token balance which is checked by the callee
uint256 _toVal = _fromVal - _value;
// update source voting power from `_fromVal` to `_toVal`
__updateVotingPower(_from, _fromVal, _toVal);
}
// if destination address is not zero - increase its voting power
if(_to != address(0)) {
// read current destination address voting power
uint256 _fromVal = getVotingPower(_to);
// calculate increased voting power
// overflow is not possible by design:
// max token supply limits the cumulative voting power
uint256 _toVal = _fromVal + _value;
// update destination voting power from `_fromVal` to `_toVal`
__updateVotingPower(_to, _fromVal, _toVal);
}
}
/**
* @dev Auxiliary function to update voting power of the delegate `_of`
* from value `_fromVal` to value `_toVal`
*
* @param _of delegate to update its voting power
* @param _fromVal old voting power of the delegate
* @param _toVal new voting power of the delegate
*/
function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// if there is an existing voting power value stored for current block
if(history.length != 0 && history[history.length - 1].blockNumber == block.number) {
// update voting power which is already stored in the current block
history[history.length - 1].votingPower = uint192(_toVal);
}
// otherwise - if there is no value stored for current block
else {
// add new element into array representing the value for current block
history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal)));
}
// emit an event
emit VotingPowerChanged(_of, _fromVal, _toVal);
}
/**
* @dev Auxiliary function to lookup an element in a sorted (asc) array of elements
*
* @dev This function finds the closest element in an array to the value
* of interest (not exceeding that value) and returns its index within an array
*
* @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`,
* it is sorted in ascending order (blockNumber increases)
*
* @param _to an address of the delegate to get an array for
* @param n value of interest to look for
* @return an index of the closest element in an array to the value
* of interest (not exceeding that value)
*/
function __binaryLookup(address _to, uint256 n) private view returns(uint256) {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_to];
// left bound of the search interval, originally start of the array
uint256 i = 0;
// right bound of the search interval, originally end of the array
uint256 j = history.length - 1;
// the iteration process narrows down the bounds by
// splitting the interval in a half oce per each iteration
while(j > i) {
// get an index in the middle of the interval [i, j]
uint256 k = j - (j - i) / 2;
// read an element to compare it with the value of interest
VotingPowerRecord memory cp = history[k];
// if we've got a strict equal - we're lucky and done
if(cp.blockNumber == n) {
// just return the result - index `k`
return k;
}
// if the value of interest is bigger - move left bound to the middle
else if (cp.blockNumber < n) {
// move left bound `i` to the middle position `k`
i = k;
}
// otherwise, when the value of interest is smaller - move right bound to the middle
else {
// move right bound `j` to the middle position `k - 1`:
// element at position `k` is bigger and cannot be the result
j = k - 1;
}
}
// reaching that point means no exact match found
// since we're interested in the element which is not bigger than the
// element of interest, we return the lower bound `i`
return i;
}
}
// ===== End: DAO Support (Compound-like voting delegation) =====
|
* @notice Returns the amount which _spender is still allowed to withdraw from _owner. @dev IERC20 `function allowance(address owner, address spender) external view returns (uint256)` @dev A function to check an amount of tokens owner approved to transfer on its behalf by some other address called "spender" @param _owner an address which approves transferring some tokens on its behalf @param _spender an address approved to transfer some tokens on behalf @return remaining an amount of tokens approved address `_spender` can transfer on behalf of token owner `_owner`/ read the value from storage and return
|
function allowance(address _owner, address _spender) external view override returns (uint256) {
return transferAllowances[_owner][_spender];
}
| 12,838,471 |
[
1,
1356,
326,
3844,
1492,
389,
87,
1302,
264,
353,
4859,
2935,
358,
598,
9446,
628,
389,
8443,
18,
225,
467,
654,
39,
3462,
1375,
915,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
22025,
225,
432,
445,
358,
866,
392,
3844,
434,
2430,
3410,
20412,
1377,
358,
7412,
603,
2097,
12433,
6186,
635,
2690,
1308,
1758,
2566,
315,
87,
1302,
264,
6,
225,
389,
8443,
392,
1758,
1492,
6617,
3324,
906,
74,
20245,
2690,
2430,
603,
2097,
12433,
6186,
225,
389,
87,
1302,
264,
392,
1758,
20412,
358,
7412,
2690,
2430,
603,
12433,
6186,
327,
4463,
392,
3844,
434,
2430,
20412,
1758,
1375,
67,
87,
1302,
264,
68,
848,
7412,
603,
12433,
6186,
1377,
434,
1147,
3410,
1375,
67,
8443,
68,
19,
855,
326,
460,
628,
2502,
471,
327,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
3903,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
7412,
7009,
6872,
63,
67,
8443,
6362,
67,
87,
1302,
264,
15533,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.5.0 <0.6.0;
import "../../ERC20/ERC20Mintable.sol";
/**
* @title ERC20BrokenTransferFromTest
* @dev Extending ERC20 by adding some functions that always revert when called.
*/
contract ERC20BrokenTransferFromTest is ERC20Mintable {
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(true == false, "you shall not pass");
super.transferFrom(_from, _to, _value);
return true;
}
}
|
* @title ERC20BrokenTransferFromTest @dev Extending ERC20 by adding some functions that always revert when called./
|
contract ERC20BrokenTransferFromTest is ERC20Mintable {
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(true == false, "you shall not pass");
super.transferFrom(_from, _to, _value);
return true;
}
}
| 6,375,528 |
[
1,
654,
39,
3462,
29559,
5912,
1265,
4709,
225,
6419,
2846,
4232,
39,
3462,
635,
6534,
2690,
4186,
716,
3712,
15226,
1347,
2566,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
4232,
39,
3462,
29559,
5912,
1265,
4709,
353,
4232,
39,
3462,
49,
474,
429,
288,
203,
203,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
3767,
422,
629,
16,
315,
19940,
24315,
486,
1342,
8863,
203,
3639,
2240,
18,
13866,
1265,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x881D40237659C251811CEC9c364ef91dC08D300C/sources/contracts/MetaSwap.sol
|
* @dev Removes the adapter for an existing aggregator. This can't be undone. @param aggregatorId Aggregator's identifier/
|
function removeAdapter(string calldata aggregatorId) external onlyOwner {
require(
adapters[aggregatorId].addr != address(0),
"ADAPTER_DOES_NOT_EXIST"
);
delete adapters[aggregatorId];
adapterRemoved[aggregatorId] = true;
emit AdapterRemoved(aggregatorId);
}
| 9,231,149 |
[
1,
6220,
326,
4516,
364,
392,
2062,
20762,
18,
1220,
848,
1404,
506,
640,
8734,
18,
225,
20762,
548,
10594,
639,
1807,
2756,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1206,
4216,
12,
1080,
745,
892,
20762,
548,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
17272,
63,
10751,
639,
548,
8009,
4793,
480,
1758,
12,
20,
3631,
203,
5411,
315,
1880,
37,
1856,
654,
67,
3191,
3991,
67,
4400,
67,
11838,
6,
203,
3639,
11272,
203,
3639,
1430,
17272,
63,
10751,
639,
548,
15533,
203,
3639,
4516,
10026,
63,
10751,
639,
548,
65,
273,
638,
31,
203,
3639,
3626,
14238,
10026,
12,
10751,
639,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0xA16D61970c358c703d0107b57Bc8F2D0d378fB43/sources/EmiList.full.sol
|
item not in the list, add
|
if (!whiteList[t]) {
| 4,725,372 |
[
1,
1726,
486,
316,
326,
666,
16,
527,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1850,
309,
16051,
14739,
682,
63,
88,
5717,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-15
*/
// File: contracts/IWoofpackNFTToken.sol
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IWoofpackNFTToken {
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
function transferOwnership(address newOwner) external;
function renounceMinter() external;
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
function mint(address recipient, uint256 mintAmount) external returns (bool);
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/utils/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.0 (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;
}
}
// File: contracts/crowdsale/Crowdsale.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is Context, ReentrancyGuard {
using SafeMath for uint256;
// The token being sold
IWoofpackNFTToken private _token;
// Amount of wei raised
uint256 private _weiRaised;
// Address where funds are collected
address payable private _wallet;
// Private Sale price is 0.06 ETH
uint256 internal _rate = 60000000000000000;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 mintAmount);
/**
* @param __wallet Address where collected funds will be forwarded to
* @param __token Address of the token being sold
*/
constructor (address payable __wallet, IWoofpackNFTToken __token) public {
require(__wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(__token) != address(0), "Crowdsale: token is the zero address");
_wallet = __wallet;
_token = __token;
}
/**
* @return the token being sold.
*/
function token() public view virtual returns (IWoofpackNFTToken) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view virtual returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view virtual returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view virtual returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
**/
function buyNFT(address beneficiary, uint256 mintAmount) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, mintAmount, weiAmount);
// update state ETH Amount
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, mintAmount);
emit TokensPurchased(_msgSender(), beneficiary, mintAmount);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds(beneficiary, weiAmount);
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param mintAmount total no of tokens to be minted
* @param weiAmount no of ETH sent
*/
function _preValidatePurchase(address beneficiary, uint256 mintAmount, uint256 weiAmount) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param mintAmount Total mint tokens
*/
function _processPurchase(address beneficiary, uint256 mintAmount) internal virtual {
_deliverTokens(beneficiary, mintAmount);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param mintAmount Total mint tokens
*/
function _deliverTokens(address beneficiary, uint256 mintAmount) internal {
/*********** COMMENTED REQUIRE BECAUSE IT WAS RETURNING BOOLEAN AND WE WERE LISTENING FROM THE INTERFACE THAT IT WILL RETURN BOOLEAN BUT IT REVERTS OUR TRANSACTION**************** */
// Potentially dangerous assumption about the type of the token.
require(
token().mint(beneficiary, mintAmount)
, "Crowdsale: transfer failed"
);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds(address /*beneficiary*/, uint256 /*weiAmount*/) internal virtual {
_wallet.transfer(msg.value);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual {
// solhint-disable-previous-line no-empty-blocks
}
}
// File: contracts/roles/Roles.sol
// pragma solidity ^0.5.0;
pragma solidity ^0.8.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts/roles/WhitelistAdminRole.sol
pragma solidity ^0.8.0;
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
abstract contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// File: contracts/roles/WhitelistedRole.sol
pragma solidity ^0.8.0;
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is Context, WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role");
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(_msgSender());
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
// File: contracts/crowdsale/validation/TimedCrowdsale.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
abstract contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 internal _openingTime;
uint256 private _closingTime;
uint256 private _secondarySaleTime;
/**
* Event for crowdsale extending
* @param newClosingTime new closing time
* @param prevClosingTime old closing time
*/
event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime);
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "TimedCrowdsale: not open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param __openingTime Crowdsale opening time
* @param __closingTime Crowdsale closing time
* @param __secondarySaleTime Crowdsale secondary time
*/
constructor (uint256 __openingTime, uint256 __secondarySaleTime, uint256 __closingTime) {
// solhint-disable-next-line not-rely-on-time
require(__openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time");
// solhint-disable-next-line max-line-length
require(__secondarySaleTime > __openingTime, "TimedCrowdsale: opening time is not before secondary sale time");
// solhint-disable-next-line max-line-length
require(__closingTime > __secondarySaleTime, "TimedCrowdsale: secondary sale time is not before closing time");
_openingTime = __openingTime;
_closingTime = __closingTime;
_secondarySaleTime = __secondarySaleTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view virtual returns (uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view virtual returns (uint256) {
return _closingTime;
}
/**
* @return the crowdsale secondary sale time.
*/
function secondaryTime() public view virtual returns (uint256) {
return _secondarySaleTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view virtual returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view virtual returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp > _closingTime;
}
/**
* @dev Extend crowdsale.
* @param newClosingTime Crowdsale closing time
*/
function _extendTime(uint256 newClosingTime) internal virtual {
require(!hasClosed(), "TimedCrowdsale: already closed");
// solhint-disable-next-line max-line-length
require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time");
emit TimedCrowdsaleExtended(_closingTime, newClosingTime);
_closingTime = newClosingTime;
}
}
// File: contracts/crowdsale/validation/CappedCrowdsale.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
abstract contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 internal _cap;
uint256 internal _minted;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param cap Max amount of wei to be contributed
*/
constructor (uint256 cap) {
require(cap > 0, "CappedCrowdsale: cap is 0");
_cap = cap;
}
/**
* @return the cap of the crowdsale.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @return the minted of the crowdsale.
*/
function minted() public view returns (uint256) {
return _minted;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return _minted >= _cap;
}
function incrementMinted(uint256 amountOfTokens) internal virtual {
_minted += amountOfTokens;
}
function currentMinted() public view returns (uint256) {
return _minted;
}
}
// File: contracts/WoofpackNFTICO.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract WoofpackNFTICO is
Crowdsale,
CappedCrowdsale,
TimedCrowdsale,
Ownable,
WhitelistedRole
{
using SafeMath for uint256;
/* Track investor contributions */
uint256 public investorHardCap = 7; // 7 NFT
mapping(address => uint256) public contributions;
/* Crowdsale Stages */
enum CrowdsaleStage {
PreICO,
ICO
}
/* Default to presale stage */
CrowdsaleStage public stage = CrowdsaleStage.PreICO;
constructor(
address payable _wallet,
IWoofpackNFTToken _token,
uint256 _cap,
uint256 _openingTime,
uint256 _secondarySaleTime,
uint256 _closingTime
)
public
Crowdsale(_wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _secondarySaleTime, _closingTime)
{}
/**
* @dev Returns the amount contributed so far by a sepecific user.
* @param _beneficiary Address of contributor
* @return User contribution so far
*/
function getUserContribution(address _beneficiary)
public
view
returns (uint256)
{
return contributions[_beneficiary];
}
/**
* @dev Extend parent behavior requiring purchase to respect investor min/max funding cap.
* @param _beneficiary Token purchaser
*/
function _preValidatePurchase(address _beneficiary, uint256 mintAmount, uint256 weiAmount)
internal virtual override onlyWhileOpen
{
// Check how many NFT are minted
incrementMinted(mintAmount);
require(currentMinted() <= _cap, "WoofpackNFTICO: cap exceeded");
require(weiAmount.div(mintAmount) == rate(), "WoofpackNFTICO: Invalid ETH Amount");
// Validate inputs
require(weiAmount != 0, "WoofpackNFTICO: ETH sent 0");
require(_beneficiary != address(0), "WoofpackNFTICO: beneficiary zero address");
if (stage == CrowdsaleStage.PreICO) {
require(
isWhitelisted(_msgSender()),
"WoofpackNFTICO: Wallet Address is not WhiteListed"
);
}
// Check max minting limit
uint256 _existingContribution = contributions[_beneficiary];
uint256 _newContribution = _existingContribution.add(mintAmount);
require(
_newContribution <= investorHardCap,
"WoofpackNFTICO: No of Mint MaxCap"
);
contributions[_beneficiary] = _newContribution;
}
function extendTime(uint256 closingTime) public virtual onlyOwner {
_extendTime(closingTime);
}
/**
* @dev If goal is Reached then change to change to ICO Stage
* etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount)
internal virtual override
{
if (block.timestamp >= secondaryTime() && stage == CrowdsaleStage.PreICO ) {
stage = CrowdsaleStage.ICO;
_rate = 70000000000000000; // 0.08ETH
_openingTime = secondaryTime(); // Set opening time to secondary time
}
super._updatePurchasingState(_beneficiary, _weiAmount);
}
/**
* @dev enables token transfers, called when owner calls finalize()
*/
function finalization() public onlyOwner {
token().renounceMinter();
}
}
|
* @title Roles @dev Library for managing addresses assigned to a Role./
|
library Roles {
pragma solidity ^0.8.0;
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
| 2,234,322 |
[
1,
6898,
225,
18694,
364,
30632,
6138,
6958,
358,
279,
6204,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
12083,
19576,
288,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
1958,
6204,
288,
203,
3639,
2874,
261,
2867,
516,
1426,
13,
28802,
31,
203,
565,
289,
203,
203,
565,
445,
527,
12,
2996,
2502,
2478,
16,
1758,
2236,
13,
2713,
288,
203,
3639,
2583,
12,
5,
5332,
12,
4615,
16,
2236,
3631,
315,
6898,
30,
2236,
1818,
711,
2478,
8863,
203,
3639,
2478,
18,
29400,
264,
63,
4631,
65,
273,
638,
31,
203,
565,
289,
203,
203,
565,
445,
1206,
12,
2996,
2502,
2478,
16,
1758,
2236,
13,
2713,
288,
203,
3639,
2583,
12,
5332,
12,
4615,
16,
2236,
3631,
315,
6898,
30,
2236,
1552,
486,
1240,
2478,
8863,
203,
3639,
2478,
18,
29400,
264,
63,
4631,
65,
273,
629,
31,
203,
565,
289,
203,
203,
565,
445,
711,
12,
2996,
2502,
2478,
16,
1758,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
6898,
30,
2236,
353,
326,
3634,
1758,
8863,
203,
3639,
327,
2478,
18,
29400,
264,
63,
4631,
15533,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xAFd2EfC5e3501521cA256C785d27D3BDFf0Bd85C/sources/AdrianDittmann.sol
|
sniper protection, to be lowered to 9% after launch
|
buyFee = 20;
| 2,610,345 |
[
1,
8134,
77,
457,
17862,
16,
358,
506,
2612,
329,
358,
2468,
9,
1839,
8037,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
30143,
14667,
273,
4200,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function mint(address recipient, uint256 amount) external returns (bool);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
contract SalTxToken is IERC20{
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping(address => bool) private minters;
address public owner;
string private _name;
string private _symbol;
uint256 private _totalSupply;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
owner = msg.sender;
minters[msg.sender] = true;
}
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyMinters(){
require(minters[msg.sender]);
_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Adds minter to the minters list for approval
*/
function addMinter() public {
minters[msg.sender] = false;
}
/**
* @dev get the status of the particular minter about the status
*/
function getStatus() public view returns (bool) {
return minters[msg.sender];
}
/**
* @dev approves the minter which already there in minters list *onlyOwner can do it
*/
function approveMinter(address _minter) public onlyOwner {
if(!minters[_minter]){
minters[_minter] = true;
}
}
/**
* @dev totalSupply of tokens
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev balanceOf tokens for particular address
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.mint`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function mint(address recipient, uint256 amount) public onlyMinters returns (bool) {
_mint(recipient, amount);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
}
function _mint(address account, uint256 amount) public onlyMinters {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
}
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(value);
_totalSupply = _totalSupply.sub(value);
}
}
|
* @dev See `IERC20.mint`. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./
|
function mint(address recipient, uint256 amount) public onlyMinters returns (bool) {
_mint(recipient, amount);
return true;
}
| 2,073,030 |
[
1,
9704,
1375,
45,
654,
39,
3462,
18,
81,
474,
8338,
29076,
30,
300,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
326,
4894,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
312,
474,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
1338,
49,
2761,
87,
1135,
261,
6430,
13,
288,
203,
3639,
389,
81,
474,
12,
20367,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BlueOak-1.0.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
// solhint-disable-next-line max-line-length
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "contracts/interfaces/IMain.sol";
import "contracts/interfaces/IBasketHandler.sol";
import "contracts/interfaces/IRToken.sol";
import "contracts/libraries/Fixed.sol";
import "contracts/p0/mixins/Component.sol";
import "contracts/p0/mixins/Rewardable.sol";
struct SlowIssuance {
address issuer;
uint256 amount; // {qRTok}
uint192 baskets; // {BU}
address[] erc20s;
uint256[] deposits;
uint256 basketNonce;
uint192 blockAvailableAt; // {block.number} fractional
bool processed;
}
/**
* @title RTokenP0
* @notice An ERC20 with an elastic supply and governable exchange rate to basket units.
*/
contract RTokenP0 is ComponentP0, RewardableP0, ERC20Upgradeable, ERC20PermitUpgradeable, IRToken {
using EnumerableSet for EnumerableSet.AddressSet;
using FixLib for uint192;
using SafeERC20 for IERC20;
/// Expected to be an IPFS hash
string public manifestoURI;
// To enforce a fixed issuanceRate throughout the entire block
mapping(uint256 => uint256) private blockIssuanceRates; // block.number => {qRTok/block}
// MIN_ISSUANCE_RATE: {qRTok/block} 10k whole RTok
uint256 public constant MIN_ISSUANCE_RATE = 10_000 * FIX_ONE;
// List of accounts. If issuances[user].length > 0 then (user is in accounts)
EnumerableSet.AddressSet internal accounts;
mapping(address => SlowIssuance[]) public issuances;
// When all pending issuances will have vested.
// This is fractional so that we can represent partial progress through a block.
uint192 public allVestAt; // {fractional block number}
uint192 public basketsNeeded; // {BU}
uint192 public issuanceRate; // {1/block} of RToken supply to issue per block
function init(
IMain main_,
string memory name_,
string memory symbol_,
string memory manifestoURI_,
uint192 issuanceRate_
) public initializer {
__Component_init(main_);
__ERC20_init(name_, symbol_);
__ERC20Permit_init(name_);
manifestoURI = manifestoURI_;
issuanceRate = issuanceRate_;
emit IssuanceRateSet(FIX_ZERO, issuanceRate);
}
function setIssuanceRate(uint192 val) external governance {
emit IssuanceRateSet(issuanceRate, val);
issuanceRate = val;
}
/// Begin a time-delayed issuance of RToken for basket collateral
/// @param amount {qTok} The quantity of RToken to issue
/// @custom:interaction
function issue(uint256 amount) external interaction {
require(amount > 0, "Cannot issue zero");
// Call collective state keepers.
main.poke();
IBasketHandler basketHandler = main.basketHandler();
require(basketHandler.status() != CollateralStatus.DISABLED, "basket disabled");
address issuer = _msgSender();
refundAndClearStaleIssuances(issuer);
// Compute # of baskets to create `amount` qRTok
uint192 baskets = (totalSupply() > 0) // {BU}
? basketsNeeded.muluDivu(amount, totalSupply()) // {BU * qRTok / qRTok}
: shiftl_toFix(amount, -int8(decimals())); // {qRTok / qRTok}
(address[] memory erc20s, uint256[] memory deposits) = basketHandler.quote(baskets, CEIL);
// Accept collateral
for (uint256 i = 0; i < erc20s.length; i++) {
IERC20(erc20s[i]).safeTransferFrom(issuer, address(this), deposits[i]);
}
// Add a new SlowIssuance ticket to the queue
(uint256 basketNonce, ) = main.basketHandler().lastSet();
SlowIssuance memory iss = SlowIssuance({
issuer: issuer,
amount: amount,
baskets: baskets,
erc20s: erc20s,
deposits: deposits,
basketNonce: basketNonce,
blockAvailableAt: nextIssuanceBlockAvailable(amount),
processed: false
});
issuances[issuer].push(iss);
accounts.add(issuer);
uint256 index = issuances[issuer].length - 1;
emit IssuanceStarted(
iss.issuer,
index,
iss.amount,
iss.baskets,
iss.erc20s,
iss.deposits,
iss.blockAvailableAt
);
// Complete issuance instantly if it fits into this block and basket is sound
if (
iss.blockAvailableAt.lte(toFix(block.number)) &&
basketHandler.status() == CollateralStatus.SOUND
) {
// At this point all checks have been done to ensure the issuance should vest
uint256 vestedAmount = tryVestIssuance(issuer, index);
emit IssuancesCompleted(issuer, index, index);
assert(vestedAmount == iss.amount);
delete issuances[issuer][index];
}
}
/// Cancels a vesting slow issuance
/// @custom:interaction
/// If earliest == true, cancel id if id < endId
/// If earliest == false, cancel id if endId <= id
/// @param endId One end of the range of issuance IDs to cancel
/// @param earliest If true, cancel earliest issuances; else, cancel latest issuances
/// @custom:interaction
function cancel(uint256 endId, bool earliest) external interaction {
// Call collective state keepers.
main.poke();
address account = _msgSender();
SlowIssuance[] storage queue = issuances[account];
(uint256 first, uint256 last) = earliest ? (0, endId) : (endId, queue.length);
uint256 left;
for (uint256 n = first; n < last; n++) {
SlowIssuance storage iss = queue[n];
if (!iss.processed) {
for (uint256 i = 0; i < iss.erc20s.length; i++) {
IERC20(iss.erc20s[i]).safeTransfer(iss.issuer, iss.deposits[i]);
}
iss.processed = true;
if (left == 0) left = n;
}
}
emit IssuancesCanceled(account, left, last);
}
/// Completes all vested slow issuances for the account, callable by anyone
/// @param account The address of the account to vest issuances for
/// @custom:interaction
function vest(address account, uint256 endId) external interaction {
// Call collective state keepers.
main.poke();
require(main.basketHandler().status() == CollateralStatus.SOUND, "collateral default");
refundAndClearStaleIssuances(account);
uint256 first;
uint256 totalVested;
for (uint256 i = 0; i < endId && i < issuances[account].length; i++) {
uint256 vestedAmount = tryVestIssuance(account, i);
totalVested += vestedAmount;
if (first == 0 && vestedAmount > 0) first = i;
}
if (totalVested > 0) emit IssuancesCompleted(account, first, endId);
}
/// Return the highest index that could be completed by a vestIssuances call.
function endIdForVest(address account) external view returns (uint256) {
uint256 i = 0;
uint192 currBlock = toFix(block.number);
SlowIssuance[] storage queue = issuances[account];
while (i < queue.length && queue[i].blockAvailableAt.lte(currBlock)) i++;
return i;
}
/// Redeem RToken for basket collateral
/// @param amount {qTok} The quantity {qRToken} of RToken to redeem
/// @custom:interaction
function redeem(uint256 amount) external interaction {
require(amount > 0, "Cannot redeem zero");
require(balanceOf(_msgSender()) >= amount, "not enough RToken");
// Call collective state keepers.
main.poke();
IBasketHandler basketHandler = main.basketHandler();
require(basketHandler.status() != CollateralStatus.DISABLED, "collateral default");
// {BU} = {BU} * {qRTok} / {qRTok}
uint192 baskets = basketsNeeded.muluDivu(amount, totalSupply());
assert(baskets.lte(basketsNeeded));
emit Redemption(_msgSender(), amount, baskets);
(address[] memory erc20s, uint256[] memory amounts) = basketHandler.quote(baskets, FLOOR);
// {1} = {qRTok} / {qRTok}
uint192 prorate = toFix(amount).divu(totalSupply());
// Accept and burn RToken
_burn(_msgSender(), amount);
emit BasketsNeededChanged(basketsNeeded, basketsNeeded.minus(baskets));
basketsNeeded = basketsNeeded.minus(baskets);
// ==== Send back collateral tokens ====
IBackingManager backingMgr = main.backingManager();
for (uint256 i = 0; i < erc20s.length; i++) {
// Bound each withdrawal by the prorata share, in case we're currently under-capitalized
uint256 bal = IERC20(erc20s[i]).balanceOf(address(backingMgr));
// {qTok} = {1} * {qTok}
uint256 prorata = prorate.mulu_toUint(bal);
amounts[i] = Math.min(amounts[i], prorata);
// Send withdrawal
IERC20(erc20s[i]).safeTransferFrom(address(backingMgr), _msgSender(), amounts[i]);
}
}
/// Mint a quantity of RToken to the `recipient`, decreasing the basket rate
/// @param recipient The recipient of the newly minted RToken
/// @param amount {qRTok} The amount to be minted
/// @custom:protected
function mint(address recipient, uint256 amount) external notPaused {
require(_msgSender() == address(main.backingManager()), "not backing manager");
_mint(recipient, amount);
}
/// Melt a quantity of RToken from the caller's account, increasing the basket rate
/// @param amount {qRTok} The amount to be melted
function melt(uint256 amount) external notPaused {
_burn(_msgSender(), amount);
emit Melted(amount);
}
/// An affordance of last resort for Main in order to ensure re-capitalization
/// @custom:protected
function setBasketsNeeded(uint192 basketsNeeded_) external notPaused {
require(_msgSender() == address(main.backingManager()), "not backing manager");
emit BasketsNeededChanged(basketsNeeded, basketsNeeded_);
basketsNeeded = basketsNeeded_;
}
/// @return {UoA/rTok} The protocol's best guess of the RToken price on markets
function price() external view returns (uint192) {
if (totalSupply() == 0) return main.basketHandler().price();
// {UoA/rTok} = {UoA/BU} * {BU} / {rTok}
uint192 supply = shiftl_toFix(totalSupply(), -int8(decimals()));
return main.basketHandler().price().mulDiv(basketsNeeded, supply);
}
/// Tries to vest an issuance
/// @return issued The total amount of RToken minted
function tryVestIssuance(address issuer, uint256 index) internal returns (uint256 issued) {
SlowIssuance storage iss = issuances[issuer][index];
(uint256 basketNonce, ) = main.basketHandler().lastSet();
require(iss.blockAvailableAt.lte(toFix(block.number)), "issuance not ready");
assert(iss.basketNonce == basketNonce); // this should always be true at this point
if (!iss.processed) {
for (uint256 i = 0; i < iss.erc20s.length; i++) {
IERC20(iss.erc20s[i]).safeTransfer(address(main.backingManager()), iss.deposits[i]);
}
_mint(iss.issuer, iss.amount);
issued = iss.amount;
emit BasketsNeededChanged(basketsNeeded, basketsNeeded.plus(iss.baskets));
basketsNeeded = basketsNeeded.plus(iss.baskets);
iss.processed = true;
emit Issuance(issuer, iss.amount, iss.baskets);
}
}
/// Returns the block number at which an issuance for *amount* now can complete
function nextIssuanceBlockAvailable(uint256 amount) private returns (uint192) {
uint192 before = fixMax(toFix(block.number - 1), allVestAt);
// Calculate the issuance rate if this is the first issue in the block
if (blockIssuanceRates[block.number] == 0) {
blockIssuanceRates[block.number] = Math.max(
MIN_ISSUANCE_RATE,
issuanceRate.mulu_toUint(totalSupply())
);
}
uint256 perBlock = blockIssuanceRates[block.number];
allVestAt = before.plus(FIX_ONE.muluDivu(amount, perBlock));
return allVestAt;
}
function refundAndClearStaleIssuances(address account) private {
(uint256 basketNonce, ) = main.basketHandler().lastSet();
bool clearQueue = false;
for (uint256 i = 0; i < issuances[account].length; i++) {
SlowIssuance storage iss = issuances[account][i];
if (!iss.processed && iss.basketNonce != basketNonce) {
for (uint256 j = 0; j < iss.erc20s.length; j++) {
IERC20(iss.erc20s[j]).safeTransfer(iss.issuer, iss.deposits[j]);
}
iss.processed = true;
}
if (iss.basketNonce != basketNonce) clearQueue = true;
}
if (clearQueue) delete issuances[account]; // to mimic RTokenP1 endIds for future issuance
}
}
|
to mimic RTokenP1 endIds for future issuance
|
if (clearQueue) delete issuances[account];
| 7,271,270 |
[
1,
869,
20369,
335,
534,
1345,
52,
21,
679,
2673,
364,
3563,
3385,
89,
1359,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
309,
261,
8507,
3183,
13,
1430,
3385,
89,
6872,
63,
4631,
15533,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-09-20
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/Context
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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;
}
}
// Part: OpenZeppelin/[email protected]/IERC165
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/IERC721Receiver
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/SafeMath
// 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;
}
}
}
// Part: OpenZeppelin/[email protected]/Strings
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/ERC165
/**
* @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;
}
}
// Part: OpenZeppelin/[email protected]/IERC721
/**
* @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;
}
// Part: OpenZeppelin/[email protected]/Ownable
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
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);
}
}
// Part: OpenZeppelin/[email protected]/IERC721Enumerable
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/IERC721Metadata
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/ERC721
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// Part: OpenZeppelin/[email protected]/ERC721Enumerable
/**
* @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();
}
}
// Part: OpenZeppelin/[email protected]/ERC721URIStorage
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: CryptoBeefcakes.sol
/// @title Smart contract for governing the Crypto Beefcakes ERC721 NFTs
/// @author Crypto Beefcakes
/// @notice This contract is used for minting Crypto Beefcake NFTs
contract CryptoBeefcakes is ERC721URIStorage, ERC721Enumerable, Ownable {
using SafeMath for uint256;
// Metadata base URI
string _metadataBaseURI;
// Sale state
enum SaleState {
NOT_ACTIVE, // 0
WHITELISTED_PRESALE, // 1
OPEN_PRESALE, // 2
PUBLIC_SALE // 3
}
SaleState public saleState = SaleState.NOT_ACTIVE;
// Presale tokens minted
uint256 public presaleTokensMinted = 0;
// Presale whitelist
mapping(address => bool) public presaleWhitelisted;
// Discounted referral mints
mapping(address => uint) public addressToNumReferralMints;
// Minting constants
uint256 public constant MAX_BEEFCAKES = 9999; // 9999 beefcake limit
uint256 public constant MAX_BEEFCAKE_PURCHASE = 20; // 20 beefcake purchase (mint) limit per transaction
uint256 public constant BEEFCAKE_EARLY_PRICE = 4 ether / 100; // 0.04 ETH early price
uint256 public constant BEEFCAKE_PRICE = 6 ether / 100; // 0.06 ETH price
uint256 public constant REFERRAL_DISCOUNT = 1 ether / 100; // 0.01 ETH referral discount t REFERRAL_DISCOUNT = 1 ether / 100; // 0.01 ETH referral discount
uint256 public constant MAX_PRESALE_TOKENS = 500; // 500 maximum tokens can be minted for presale
// Minted event
event BeefcakeMinted(uint256 tokenId); // Event to monitor
// Default constructor
constructor() ERC721("Crypto Beefcakes", "BEEF") Ownable() {}
// Withdraw funds
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
// Sale state changes
function startGeneralSale() public onlyOwner {
saleState = SaleState.PUBLIC_SALE;
}
function startWhitelistedPresale() public onlyOwner {
saleState = SaleState.WHITELISTED_PRESALE;
}
function startOpenPresale() public onlyOwner {
saleState = SaleState.OPEN_PRESALE;
}
function stopSale() public onlyOwner {
saleState = SaleState.NOT_ACTIVE;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_metadataBaseURI = baseURI;
}
function _baseURI() override(ERC721) view internal returns (string memory) {
return _metadataBaseURI;
}
// Set token URI for metadata
function setTokenURI(uint256 tokenId, string memory _tokenURI) public onlyOwner {
_setTokenURI(tokenId, _tokenURI);
}
/// @notice Get the price of minting a Beefcake NFT for a given address, based on general sale or presale status and referral discount
/// @param minterAddress The address for the minter
/// @return The price in wei
function getPrice(address minterAddress) public view returns(uint256) {
// Get price based on presale status
uint price = (saleState == SaleState.WHITELISTED_PRESALE || saleState == SaleState.OPEN_PRESALE)? BEEFCAKE_EARLY_PRICE : BEEFCAKE_PRICE;
// Add referral discount
if(addressToNumReferralMints[minterAddress] > 0) {
return price.sub(REFERRAL_DISCOUNT);
} else {
return price;
}
}
// Reserve Beefcakes for giveaways and airdrops
function reserveBeefcakes() public onlyOwner {
uint256 numBeefcakes = 30;
require(totalSupply().add(numBeefcakes) <= MAX_BEEFCAKES, "Error: all beefcakes have already been minted");
// Mint these beefcakes
for(uint i =0; i < numBeefcakes; i++) {
uint256 tokenId = totalSupply();
_safeMint(msg.sender, tokenId);
emit BeefcakeMinted(tokenId);
}
}
/// @notice Determine if user can mint based on the sale's state
/// @param minterAddress The address of the would-be minter
/// @return A bool indicating whether or not the would-b minter can mint
function canMint(address minterAddress) public view returns(bool) {
// Can mint if public sale or open presale
if(saleState == SaleState.PUBLIC_SALE || saleState == SaleState.OPEN_PRESALE) {
return true;
}
// Can mint if whitelisted presale is ongoing and the minter is whitelisted
if(saleState == SaleState.WHITELISTED_PRESALE && presaleWhitelisted[minterAddress]) {
return true;
}
return false;
}
/// @notice Mint Beefcake tokens, up to 20 tokens at a time
/// @param numBeefcakes The number of Beefcakes you want to mint, with 20 being the max value
function mint(uint256 numBeefcakes) payable public {
require(canMint(msg.sender), "Error: you are not allowed to mint at this time");
require(numBeefcakes <= MAX_BEEFCAKE_PURCHASE, "Error: can only mint 20 beefcakes per transaction");
uint256 price = getPrice(msg.sender);
require(msg.value >= price.mul(numBeefcakes), "Error: insufficient funds sent");
require(totalSupply().add(numBeefcakes) <= MAX_BEEFCAKES, "Error: all beefcakes have already been minted");
if(saleState == SaleState.WHITELISTED_PRESALE || saleState == SaleState.OPEN_PRESALE) {
require(presaleTokensMinted.add(numBeefcakes) <= MAX_PRESALE_TOKENS, "Error: only 500 presale tokens can be minted TOTAL");
}
// Reduce number of referall mints
if(addressToNumReferralMints[msg.sender] > 0) {
addressToNumReferralMints[msg.sender] = addressToNumReferralMints[msg.sender].sub(1);
}
// Increase number of presale mints
if(saleState == SaleState.WHITELISTED_PRESALE || saleState == SaleState.OPEN_PRESALE) {
presaleTokensMinted = presaleTokensMinted.add(numBeefcakes);
}
// Mint these beefcakes
for(uint i = 0; i < numBeefcakes; i++) {
uint256 tokenId = totalSupply();
_safeMint(msg.sender, tokenId);
emit BeefcakeMinted(tokenId);
}
}
/// @notice Mint with referral -- when you mint with a referral, your referrer will receive a discount on their next Beefcake mint
/// @param numBeefcakes The number of Beefcakes you want to mint, with 20 being the max value
/// @param referrerAddress The address of the referrer -- this referrer must have previously minted a Beefcake
function mintWithReferral(uint256 numBeefcakes, address referrerAddress) payable public {
require(balanceOf(referrerAddress) > 0, "Error: referrer must have minted already");
require(referrerAddress != msg.sender, "Error: cannot refer yourself");
addressToNumReferralMints[referrerAddress] = addressToNumReferralMints[referrerAddress].add(1);
mint(numBeefcakes);
}
// Whitelist accounts for presale
function whitelistForPresale(address[] memory presaleAddresses) public onlyOwner {
for(uint i =0; i < presaleAddresses.length; i++) {
presaleWhitelisted[presaleAddresses[i]] = true;
}
}
// The following functions are overrides required by Solidity.
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721URIStorage, ERC721)
returns (string memory)
{
return ERC721URIStorage.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
Whitelist accounts for presale
|
function whitelistForPresale(address[] memory presaleAddresses) public onlyOwner {
for(uint i =0; i < presaleAddresses.length; i++) {
presaleWhitelisted[presaleAddresses[i]] = true;
}
}
| 1,992,198 |
[
1,
18927,
9484,
364,
4075,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
10734,
1290,
12236,
5349,
12,
2867,
8526,
3778,
4075,
5349,
7148,
13,
1071,
1338,
5541,
288,
203,
3639,
364,
12,
11890,
277,
273,
20,
31,
277,
411,
4075,
5349,
7148,
18,
2469,
31,
277,
27245,
288,
203,
5411,
4075,
5349,
18927,
329,
63,
12202,
5349,
7148,
63,
77,
13563,
273,
638,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract BuiltinVariablesContract {
// tx (transaction)
tx.origin; //eth address that sent the transaction
//msg (messages). Info on the calling environment
msg.value; //amount of ether sent to the smart contract. Unit is wei
msg.sender; //eth address that called the function
//Example
//Alice => Smart contract
//tx.origin = Alice
//msg.sender = Alice
// but the smart contract can also call another smart contract
//Alice => Smart contract => smart contract B
//tx.origin = Alice => tx.origin = Alice
//msg.sender = Alice => msg.sender = smrt contract A
//block. Info on blockchain blocks
block.timestamp; //timestamp at which the block was mined
}
|
tx (transaction)msg (messages). Info on the calling environmentExampleAlice => Smart contracttx.origin = Alicemsg.sender = Alice but the smart contract can also call another smart contractAlice => Smart contract => smart contract Btx.origin = Alice => tx.origin = Alicemsg.sender = Alice => msg.sender = smrt contract Ablock. Info on blockchain blocks
|
contract BuiltinVariablesContract {
pragma solidity ^0.8.7;
}
| 12,559,523 |
[
1,
978,
261,
7958,
13,
3576,
261,
6833,
2934,
3807,
603,
326,
4440,
3330,
10908,
37,
2008,
516,
19656,
6835,
978,
18,
10012,
273,
432,
2008,
3576,
18,
15330,
273,
432,
2008,
1496,
326,
13706,
6835,
848,
2546,
745,
4042,
13706,
6835,
37,
2008,
516,
19656,
6835,
1377,
516,
377,
13706,
6835,
605,
978,
18,
10012,
273,
432,
2008,
5411,
516,
377,
2229,
18,
10012,
273,
432,
2008,
3576,
18,
15330,
273,
432,
2008,
6647,
516,
377,
1234,
18,
15330,
273,
3029,
3797,
6835,
432,
2629,
18,
3807,
603,
16766,
4398,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
27376,
267,
6158,
8924,
288,
203,
203,
203,
203,
203,
377,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
27,
31,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x5d880cfc028bFDD083B0D3dAf57286141596D4E9/sources/contracts/IvstSale.sol
|
Checks that the amount deposited is not inferior to 0
|
require(_amount > 0, "Deposit: Amount must be > 0");
| 17,165,228 |
[
1,
4081,
716,
326,
3844,
443,
1724,
329,
353,
486,
12455,
9659,
358,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2583,
24899,
8949,
405,
374,
16,
315,
758,
1724,
30,
16811,
1297,
506,
405,
374,
8863,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.5;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function MEMCPY184(uint dest, uint src, uint len) private pure { //inject NONSTANDARD NAMING
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
function TOSLICE667(string memory self) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
function LEN420(bytes32 self) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint ret;
if (self == 0)
return 0;
if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
function TOSLICEB32242(bytes32 self) internal pure returns (slice memory ret) { //inject NONSTANDARD NAMING
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = LEN420(self);
}
function COPY737(slice memory self) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
return slice(self._len, self._ptr);
}
function TOSTRING824(slice memory self) internal pure returns (string memory) { //inject NONSTANDARD NAMING
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
MEMCPY184(retptr, self._ptr, self._len);
return ret;
}
function LEN420(slice memory self) internal pure returns (uint l) { //inject NONSTANDARD NAMING
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
function EMPTY246(slice memory self) internal pure returns (bool) { //inject NONSTANDARD NAMING
return self._len == 0;
}
function COMPARE76(slice memory self, slice memory other) internal pure returns (int) { //inject NONSTANDARD NAMING
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
function EQUALS848(slice memory self, slice memory other) internal pure returns (bool) { //inject NONSTANDARD NAMING
return COMPARE76(self, other) == 0;
}
function NEXTRUNE884(slice memory self, slice memory rune) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
function NEXTRUNE884(slice memory self) internal pure returns (slice memory ret) { //inject NONSTANDARD NAMING
NEXTRUNE884(self, ret);
}
function ORD412(slice memory self) internal pure returns (uint ret) { //inject NONSTANDARD NAMING
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
function KECCAK7(slice memory self) internal pure returns (bytes32 ret) { //inject NONSTANDARD NAMING
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
function STARTSWITH158(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
function BEYOND684(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
function ENDSWITH884(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
function UNTIL972(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function FINDPTR600(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { //inject NONSTANDARD NAMING
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function RFINDPTR373(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { //inject NONSTANDARD NAMING
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
function FIND686(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
function RFIND966(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr = RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
function SPLIT752(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
function SPLIT752(slice memory self, slice memory needle) internal pure returns (slice memory token) { //inject NONSTANDARD NAMING
SPLIT752(self, needle, token);
}
function RSPLIT98(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr = RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
function RSPLIT98(slice memory self, slice memory needle) internal pure returns (slice memory token) { //inject NONSTANDARD NAMING
RSPLIT98(self, needle, token);
}
function COUNT317(slice memory self, slice memory needle) internal pure returns (uint cnt) { //inject NONSTANDARD NAMING
uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = FINDPTR600(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
function CONTAINS145(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING
return RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
function CONCAT154(slice memory self, slice memory other) internal pure returns (string memory) { //inject NONSTANDARD NAMING
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
MEMCPY184(retptr, self._ptr, self._len);
MEMCPY184(retptr + self._len, other._ptr, other._len);
return ret;
}
function JOIN989(slice memory self, slice[] memory parts) internal pure returns (string memory) { //inject NONSTANDARD NAMING
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i = 0; i < parts.length; i++) {
MEMCPY184(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
MEMCPY184(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
interface IERC165 {
function SUPPORTSINTERFACE706(bytes4 interfaceId) external view returns (bool); //inject NONSTANDARD NAMING
}
contract IERC721 is IERC165 {
event TRANSFER150(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVAL578(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVALFORALL29(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING
function BALANCEOF194(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING
function OWNEROF501(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function TRANSFERFROM196(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function APPROVE594(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function GETAPPROVED68(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING
function SETAPPROVALFORALL944(address operator, bool _approved) public; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING
}
contract IERC721Metadata is IERC721 {
function NAME560() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL235() external view returns (string memory); //inject NONSTANDARD NAMING
function TOKENURI443(uint256 tokenId) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER492() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA8() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract IERC721Enumerable is IERC721 {
function TOTALSUPPLY60() public view returns (uint256); //inject NONSTANDARD NAMING
function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256 tokenId); //inject NONSTANDARD NAMING
function TOKENBYINDEX294(uint256 index) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IERC721Receiver {
function ONERC721RECEIVED434(address operator, address from, uint256 tokenId, bytes memory data) //inject NONSTANDARD NAMING
public returns (bytes4);
}
library SafeMath {
function ADD556(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB290(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB290(a, b, "SafeMath: subtraction overflow");
}
function SUB290(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL948(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV752(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV752(a, b, "SafeMath: division by zero");
}
function DIV752(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD555(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD555(a, b, "SafeMath: modulo by zero");
}
function MOD555(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT48(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE256(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function CURRENT546(Counter storage counter) internal view returns (uint256) { //inject NONSTANDARD NAMING
return counter._value;
}
function INCREMENT933(Counter storage counter) internal { //inject NONSTANDARD NAMING
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function DECREMENT749(Counter storage counter) internal { //inject NONSTANDARD NAMING
counter._value = counter._value.SUB290(1);
}
}
contract ERC165 is IERC165 {
bytes4 private constant _interface_id_erc165217 = 0x01ffc9a7; //inject NONSTANDARD NAMING
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_REGISTERINTERFACE617(_interface_id_erc165217);
}
function SUPPORTSINTERFACE706(bytes4 interfaceId) external view returns (bool) { //inject NONSTANDARD NAMING
return _supportedInterfaces[interfaceId];
}
function _REGISTERINTERFACE617(bytes4 interfaceId) internal { //inject NONSTANDARD NAMING
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _erc721_received995 = 0x150b7a02; //inject NONSTANDARD NAMING
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _interface_id_erc721781 = 0x80ac58cd; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE617(_interface_id_erc721781);
}
function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].CURRENT546();
}
function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function APPROVE594(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF501(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_MSGSENDER492() == owner || ISAPPROVEDFORALL189(owner, _MSGSENDER492()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit APPROVAL578(owner, to, tokenId);
}
function GETAPPROVED68(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function SETAPPROVALFORALL944(address to, bool approved) public { //inject NONSTANDARD NAMING
require(to != _MSGSENDER492(), "ERC721: approve to caller");
_operatorApprovals[_MSGSENDER492()][to] = approved;
emit APPROVALFORALL29(_MSGSENDER492(), to, approved);
}
function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING
return _operatorApprovals[owner][operator];
}
function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
//solhint-disable-next-line max-line-length
require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved");
_TRANSFERFROM267(from, to, tokenId);
}
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
SAFETRANSFERFROM763(from, to, tokenId, "");
}
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING
require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved");
_SAFETRANSFERFROM629(from, to, tokenId, _data);
}
function _SAFETRANSFERFROM629(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_TRANSFERFROM267(from, to, tokenId);
require(_CHECKONERC721RECEIVED542(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _EXISTS310(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _ISAPPROVEDOROWNER717(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721: operator query for nonexistent token");
address owner = OWNEROF501(tokenId);
return (spender == owner || GETAPPROVED68(tokenId) == spender || ISAPPROVEDFORALL189(owner, spender));
}
function _SAFEMINT616(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
_SAFEMINT616(to, tokenId, "");
}
function _SAFEMINT616(address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_MINT975(to, tokenId);
require(_CHECKONERC721RECEIVED542(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _MINT975(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(to != address(0), "ERC721: mint to the zero address");
require(!_EXISTS310(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].INCREMENT933();
emit TRANSFER150(address(0), to, tokenId);
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF501(tokenId) == owner, "ERC721: burn of token that is not own");
_CLEARAPPROVAL18(tokenId);
_ownedTokensCount[owner].DECREMENT749();
_tokenOwner[tokenId] = address(0);
emit TRANSFER150(owner, address(0), tokenId);
}
function _BURN381(uint256 tokenId) internal { //inject NONSTANDARD NAMING
_BURN381(OWNEROF501(tokenId), tokenId);
}
function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF501(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_CLEARAPPROVAL18(tokenId);
_ownedTokensCount[from].DECREMENT749();
_ownedTokensCount[to].INCREMENT933();
_tokenOwner[tokenId] = to;
emit TRANSFER150(from, to, tokenId);
}
function _CHECKONERC721RECEIVED542(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING
internal returns (bool)
{
if (!to.ISCONTRACT48()) {
return true;
}
bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED434(_MSGSENDER492(), from, tokenId, _data);
return (retval == _erc721_received995);
}
function _CLEARAPPROVAL18(uint256 tokenId) private { //inject NONSTANDARD NAMING
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _interface_id_erc721_enumerable707 = 0x780e9d63; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_REGISTERINTERFACE617(_interface_id_erc721_enumerable707);
}
function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
require(index < BALANCEOF194(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING
return _allTokens.length;
}
function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
require(index < TOTALSUPPLY60(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._TRANSFERFROM267(from, to, tokenId);
_REMOVETOKENFROMOWNERENUMERATION42(from, tokenId);
_ADDTOKENTOOWNERENUMERATION485(to, tokenId);
}
function _MINT975(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._MINT975(to, tokenId);
_ADDTOKENTOOWNERENUMERATION485(to, tokenId);
_ADDTOKENTOALLTOKENSENUMERATION66(tokenId);
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._BURN381(owner, tokenId);
_REMOVETOKENFROMOWNERENUMERATION42(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_REMOVETOKENFROMALLTOKENSENUMERATION970(tokenId);
}
function _TOKENSOFOWNER469(address owner) internal view returns (uint256[] storage) { //inject NONSTANDARD NAMING
return _ownedTokens[owner];
}
function _ADDTOKENTOOWNERENUMERATION485(address to, uint256 tokenId) private { //inject NONSTANDARD NAMING
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
function _ADDTOKENTOALLTOKENSENUMERATION66(uint256 tokenId) private { //inject NONSTANDARD NAMING
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _REMOVETOKENFROMOWNERENUMERATION42(address from, uint256 tokenId) private { //inject NONSTANDARD NAMING
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.SUB290(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
function _REMOVETOKENFROMALLTOKENSENUMERATION970(uint256 tokenId) private { //inject NONSTANDARD NAMING
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length.SUB290(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED55(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER492();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED55(address(0), msgSender);
}
function OWNER824() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER845() { //inject NONSTANDARD NAMING
require(ISOWNER804(), "Ownable: caller is not the owner");
_;
}
function ISOWNER804() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER492() == _owner;
}
function RENOUNCEOWNERSHIP585() public ONLYOWNER845 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED55(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP274(address newOwner) public ONLYOWNER845 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP356(newOwner);
}
function _TRANSFEROWNERSHIP356(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED55(_owner, newOwner);
_owner = newOwner;
}
}
contract NoMintERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _erc721_received995 = 0x150b7a02; //inject NONSTANDARD NAMING
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _interface_id_erc721781 = 0x80ac58cd; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE617(_interface_id_erc721781);
}
function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].CURRENT546();
}
function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function APPROVE594(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF501(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_MSGSENDER492() == owner || ISAPPROVEDFORALL189(owner, _MSGSENDER492()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit APPROVAL578(owner, to, tokenId);
}
function GETAPPROVED68(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function SETAPPROVALFORALL944(address to, bool approved) public { //inject NONSTANDARD NAMING
require(to != _MSGSENDER492(), "ERC721: approve to caller");
_operatorApprovals[_MSGSENDER492()][to] = approved;
emit APPROVALFORALL29(_MSGSENDER492(), to, approved);
}
function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING
return _operatorApprovals[owner][operator];
}
function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
//solhint-disable-next-line max-line-length
require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved");
_TRANSFERFROM267(from, to, tokenId);
}
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
SAFETRANSFERFROM763(from, to, tokenId, "");
}
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING
require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved");
_SAFETRANSFERFROM629(from, to, tokenId, _data);
}
function _SAFETRANSFERFROM629(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_TRANSFERFROM267(from, to, tokenId);
require(_CHECKONERC721RECEIVED542(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _EXISTS310(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _ISAPPROVEDOROWNER717(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721: operator query for nonexistent token");
address owner = OWNEROF501(tokenId);
return (spender == owner || GETAPPROVED68(tokenId) == spender || ISAPPROVEDFORALL189(owner, spender));
}
function _ADDTOKENTO735(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(to != address(0), "ERC721: mint to the zero address");
require(!_EXISTS310(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].INCREMENT933();
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF501(tokenId) == owner, "ERC721: burn of token that is not own");
_CLEARAPPROVAL18(tokenId);
_ownedTokensCount[owner].DECREMENT749();
_tokenOwner[tokenId] = address(0);
emit TRANSFER150(owner, address(0), tokenId);
}
function _BURN381(uint256 tokenId) internal { //inject NONSTANDARD NAMING
_BURN381(OWNEROF501(tokenId), tokenId);
}
function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF501(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_CLEARAPPROVAL18(tokenId);
_ownedTokensCount[from].DECREMENT749();
_ownedTokensCount[to].INCREMENT933();
_tokenOwner[tokenId] = to;
emit TRANSFER150(from, to, tokenId);
}
function _CHECKONERC721RECEIVED542(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING
internal returns (bool)
{
if (!to.ISCONTRACT48()) {
return true;
}
bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED434(_MSGSENDER492(), from, tokenId, _data);
return (retval == _erc721_received995);
}
function _CLEARAPPROVAL18(uint256 tokenId) private { //inject NONSTANDARD NAMING
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract NoMintERC721Enumerable is Context, ERC165, NoMintERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _interface_id_erc721_enumerable707 = 0x780e9d63; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_REGISTERINTERFACE617(_interface_id_erc721_enumerable707);
}
function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
require(index < BALANCEOF194(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING
return _allTokens.length;
}
function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
require(index < TOTALSUPPLY60(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._TRANSFERFROM267(from, to, tokenId);
_REMOVETOKENFROMOWNERENUMERATION42(from, tokenId);
_ADDTOKENTOOWNERENUMERATION485(to, tokenId);
}
function _ADDTOKENTO735(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._ADDTOKENTO735(to, tokenId);
_ADDTOKENTOOWNERENUMERATION485(to, tokenId);
_ADDTOKENTOALLTOKENSENUMERATION66(tokenId);
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._BURN381(owner, tokenId);
_REMOVETOKENFROMOWNERENUMERATION42(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_REMOVETOKENFROMALLTOKENSENUMERATION970(tokenId);
}
function _TOKENSOFOWNER469(address owner) internal view returns (uint256[] storage) { //inject NONSTANDARD NAMING
return _ownedTokens[owner];
}
function _ADDTOKENTOOWNERENUMERATION485(address to, uint256 tokenId) private { //inject NONSTANDARD NAMING
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
function _ADDTOKENTOALLTOKENSENUMERATION66(uint256 tokenId) private { //inject NONSTANDARD NAMING
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _REMOVETOKENFROMOWNERENUMERATION42(address from, uint256 tokenId) private { //inject NONSTANDARD NAMING
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.SUB290(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
function _REMOVETOKENFROMALLTOKENSENUMERATION970(uint256 tokenId) private { //inject NONSTANDARD NAMING
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length.SUB290(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
contract OveridableERC721Metadata is Context, ERC165, NoMintERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant _interface_id_erc721_metadata259 = 0x5b5e139f; //inject NONSTANDARD NAMING
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE617(_interface_id_erc721_metadata259);
}
function NAME560() external view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL235() external view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function TOKENURI443(uint256 tokenId) public view returns (string memory) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
function _SETTOKENURI639(uint256 tokenId, string memory uri) internal { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._BURN381(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract GunToken is NoMintERC721, NoMintERC721Enumerable, OveridableERC721Metadata, Ownable {
using strings for *;
address internal factory;
uint16 public constant maxallocation33 = 4000; //inject NONSTANDARD NAMING
uint256 public lastAllocation = 0;
event BATCHTRANSFER76(address indexed from, address indexed to, uint256 indexed batchIndex); //inject NONSTANDARD NAMING
struct Batch {
address owner;
uint16 size;
uint8 category;
uint256 startId;
uint256 startTokenId;
}
Batch[] public allBatches;
mapping(address => uint256) unactivatedBalance;
mapping(uint256 => bool) isActivated;
mapping(uint256 => bool) public outOfBatch;
//Used for enumeration
mapping(address => Batch[]) public batchesOwned;
//Batch index to owner batch index
mapping(uint256 => uint256) public ownedBatchIndex;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
uint256 internal _totalSupply;
modifier ONLYFACTORY168 { //inject NONSTANDARD NAMING
require(msg.sender == factory, "Not authorized");
_;
}
constructor(address factoryAddress) public OveridableERC721Metadata("WarRiders Gun", "WRG") {
factory = factoryAddress;
}
function CATEGORYTYPETOID957(uint8 category, uint256 categoryId) public view returns (uint256) { //inject NONSTANDARD NAMING
for (uint i = 0; i < allBatches.length; i++) {
Batch memory a = allBatches[i];
if (a.category != category)
continue;
uint256 endId = a.startId + a.size;
if (categoryId >= a.startId && categoryId < endId) {
uint256 dif = categoryId - a.startId;
return a.startTokenId + dif;
}
}
revert();
}
function FALLBACKCOUNT353(address __owner) public view returns (uint256) { //inject NONSTANDARD NAMING
}
function FALLBACKINDEX7(address __owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
}
function MIGRATE859(uint256 count) public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING
//Empty for interface
}
function MIGRATESINGLE765() public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING
//Empty for interface
}
function RECOVERBATCH2175(uint256 index, uint256 tokenStart, uint256 tokenEnd) public ONLYOWNER845 { //inject NONSTANDARD NAMING
}
function MIGRATEBATCH628(uint256 index) public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING
}
function RECOVERBATCH1434(uint256 index) public ONLYOWNER845 { //inject NONSTANDARD NAMING
}
function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
return TOKENOFOWNER723(owner)[index];
}
function GETBATCHCOUNT927(address owner) public view returns(uint256) { //inject NONSTANDARD NAMING
return batchesOwned[owner].length;
}
function UPDATEGUNFACTORY282(address _factory) public ONLYOWNER845 { //inject NONSTANDARD NAMING
}
function GETTOKENSINBATCH347(address owner, uint256 index) public view returns (uint256[] memory) { //inject NONSTANDARD NAMING
Batch memory a = batchesOwned[owner][index];
uint256[] memory result = new uint256[](a.size);
uint256 pos = 0;
uint end = a.startTokenId + a.size;
for (uint i = a.startTokenId; i < end; i++) {
if (isActivated[i] && super.OWNEROF501(i) != owner) {
continue;
}
result[pos] = i;
pos++;
}
require(pos > 0);
uint256 subAmount = a.size - pos;
assembly { mstore(result, sub(mload(result), subAmount)) }
return result;
}
function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
return ALLTOKENS936()[index];
}
function ALLTOKENS936() public view returns (uint256[] memory) { //inject NONSTANDARD NAMING
uint256[] memory result = new uint256[](TOTALSUPPLY60());
uint pos = 0;
for (uint i = 0; i < allBatches.length; i++) {
Batch memory a = allBatches[i];
uint end = a.startTokenId + a.size;
for (uint j = a.startTokenId; j < end; j++) {
result[pos] = j;
pos++;
}
}
return result;
}
function TOKENOFOWNER723(address owner) public view returns (uint256[] memory) { //inject NONSTANDARD NAMING
uint256[] memory result = new uint256[](BALANCEOF194(owner));
uint pos = 0;
for (uint i = 0; i < batchesOwned[owner].length; i++) {
Batch memory a = batchesOwned[owner][i];
uint end = a.startTokenId + a.size;
for (uint j = a.startTokenId; j < end; j++) {
if (isActivated[j] && super.OWNEROF501(j) != owner) {
continue;
}
result[pos] = j;
pos++;
}
}
uint256[] memory fallbackOwned = _TOKENSOFOWNER469(owner);
for (uint i = 0; i < fallbackOwned.length; i++) {
result[pos] = fallbackOwned[i];
pos++;
}
return result;
}
function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC721: balance query for the zero address");
return super.BALANCEOF194(owner) + unactivatedBalance[owner];
}
function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
require(EXISTS127(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.OWNEROF501(tokenId);
}
uint256 index = GETBATCHINDEX786(tokenId);
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
return a.owner;
}
function EXISTS127(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
if (isActivated[_tokenId]) {
return super._EXISTS310(_tokenId);
} else {
uint256 index = GETBATCHINDEX786(_tokenId);
if (index < allBatches.length) {
Batch memory a = allBatches[index];
uint end = a.startTokenId + a.size;
return _tokenId < end;
}
return false;
}
}
function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function CLAIMALLOCATION316(address to, uint16 size, uint8 category) public ONLYFACTORY168 returns (uint) { //inject NONSTANDARD NAMING
require(size < maxallocation33, "Size must be smaller than maxAllocation");
allBatches.push(Batch({
owner: to,
size: size,
category: category,
startId: totalGunsMintedByCategory[category],
startTokenId: lastAllocation
}));
uint end = lastAllocation + size;
for (uint i = lastAllocation; i < end; i++) {
emit TRANSFER150(address(0), to, i);
}
lastAllocation += maxallocation33;
unactivatedBalance[to] += size;
totalGunsMintedByCategory[category] += size;
_ADDBATCHTOOWNER461(to, allBatches[allBatches.length - 1]);
_totalSupply += size;
return lastAllocation;
}
function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
if (!isActivated[tokenId]) {
ACTIVATE8(tokenId);
}
super.TRANSFERFROM196(from, to, tokenId);
}
function ACTIVATE8(uint256 tokenId) public { //inject NONSTANDARD NAMING
require(!isActivated[tokenId], "Token already activated");
uint256 index = GETBATCHINDEX786(tokenId);
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
isActivated[tokenId] = true;
ADDTOKENTO758(a.owner, tokenId);
unactivatedBalance[a.owner]--;
}
function GETBATCHINDEX786(uint256 tokenId) public pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 index = (tokenId / maxallocation33);
return index;
}
function CATEGORYFORTOKEN792(uint256 tokenId) public view returns (uint8) { //inject NONSTANDARD NAMING
uint256 index = GETBATCHINDEX786(tokenId);
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
return a.category;
}
function CATEGORYIDFORTOKEN949(uint256 tokenId) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 index = GETBATCHINDEX786(tokenId);
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
uint256 categoryId = (tokenId % maxallocation33) + a.startId;
return categoryId;
}
function UINTTOSTRING328(uint v) internal pure returns (string memory) { //inject NONSTANDARD NAMING
if (v == 0) {
return "0";
}
uint j = v;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function TOKENURI443(uint256 tokenId) public view returns (string memory) { //inject NONSTANDARD NAMING
require(EXISTS127(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.TOKENURI443(tokenId);
} else {
//Predict the token URI
uint8 category = CATEGORYFORTOKEN792(tokenId);
uint256 _categoryId = CATEGORYIDFORTOKEN949(tokenId);
string memory id = UINTTOSTRING328(category).TOSLICE667().CONCAT154("/".TOSLICE667()).TOSLICE667().CONCAT154(UINTTOSTRING328(_categoryId).TOSLICE667().CONCAT154(".json".TOSLICE667()).TOSLICE667());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.TOSLICE667().CONCAT154(id.TOSLICE667());
return _metadata;
}
}
function ADDTOKENTO758(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
//Predict the token URI
uint8 category = CATEGORYFORTOKEN792(_tokenId);
uint256 _categoryId = CATEGORYIDFORTOKEN949(_tokenId);
string memory id = UINTTOSTRING328(category).TOSLICE667().CONCAT154("/".TOSLICE667()).TOSLICE667().CONCAT154(UINTTOSTRING328(_categoryId).TOSLICE667().CONCAT154(".json".TOSLICE667()).TOSLICE667());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.TOSLICE667().CONCAT154(id.TOSLICE667());
super._ADDTOKENTO735(_to, _tokenId);
super._SETTOKENURI639(_tokenId, _metadata);
}
function CEIL247(uint a, uint m) internal pure returns (uint ) { //inject NONSTANDARD NAMING
return ((a + m - 1) / m) * m;
}
function _REMOVEBATCHFROMOWNER136(address from, Batch memory batch) private { //inject NONSTANDARD NAMING
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 globalIndex = GETBATCHINDEX786(batch.startTokenId);
uint256 lastBatchIndex = batchesOwned[from].length.SUB290(1);
uint256 batchIndex = ownedBatchIndex[globalIndex];
// When the token to delete is the last token, the swap operation is unnecessary
if (batchIndex != lastBatchIndex) {
Batch memory lastBatch = batchesOwned[from][lastBatchIndex];
uint256 lastGlobalIndex = GETBATCHINDEX786(lastBatch.startTokenId);
batchesOwned[from][batchIndex] = lastBatch; // Move the last batch to the slot of the to-delete batch
ownedBatchIndex[lastGlobalIndex] = batchIndex; // Update the moved batch's index
}
// This also deletes the contents at the last position of the array
batchesOwned[from].length--;
// Note that ownedBatchIndex[batch] hasn't been cleared: it still points to the old slot (now occupied by
// lastBatch, or just over the end of the array if the batch was the last one).
}
function _ADDBATCHTOOWNER461(address to, Batch memory batch) private { //inject NONSTANDARD NAMING
uint256 globalIndex = GETBATCHINDEX786(batch.startTokenId);
ownedBatchIndex[globalIndex] = batchesOwned[to].length;
batchesOwned[to].push(batch);
}
function BATCHTRANSFER268(uint256 batchIndex, address to) public { //inject NONSTANDARD NAMING
Batch storage a = allBatches[batchIndex];
address previousOwner = a.owner;
require(a.owner == msg.sender);
_REMOVEBATCHFROMOWNER136(previousOwner, a);
a.owner = to;
_ADDBATCHTOOWNER461(to, a);
emit BATCHTRANSFER76(previousOwner, to, batchIndex);
//Now to need to emit a bunch of transfer events
uint end = a.startTokenId + a.size;
uint256 unActivated = 0;
for (uint i = a.startTokenId; i < end; i++) {
if (isActivated[i]) {
if (OWNEROF501(i) != previousOwner)
continue; //The previous owner didn't own this token, don't emit an event
} else {
unActivated++;
}
emit TRANSFER150(previousOwner, to, i);
}
unactivatedBalance[to] += unActivated;
unactivatedBalance[previousOwner] -= unActivated;
}
}
contract ApproveAndCallFallBack {
function RECEIVEAPPROVAL438(address from, uint256 tokens, address token, bytes memory data) public payable returns (bool); //inject NONSTANDARD NAMING
}
contract ERC20Basic {
function TOTALSUPPLY60() public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF194(address who) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER702(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event TRANSFER150(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
}
contract ERC20 is ERC20Basic {
function ALLOWANCE798(address owner, address spender) //inject NONSTANDARD NAMING
public view returns (uint256);
function TRANSFERFROM196(address from, address to, uint256 value) //inject NONSTANDARD NAMING
public returns (bool);
function APPROVE594(address spender, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event APPROVAL578( //inject NONSTANDARD NAMING
address indexed owner,
address indexed spender,
uint256 value
);
}
contract BurnableToken is ERC20 {
event BURN595(address indexed burner, uint256 value); //inject NONSTANDARD NAMING
function BURN840(uint256 _value) public; //inject NONSTANDARD NAMING
}
contract StandardBurnableToken is BurnableToken {
function BURNFROM813(address _from, uint256 _value) public; //inject NONSTANDARD NAMING
}
interface BZNFeed {
function CONVERT77(uint256 usd) external view returns (uint256); //inject NONSTANDARD NAMING
}
contract SimpleBZNFeed is BZNFeed, Ownable {
uint256 private conversion;
function UPDATECONVERSION150(uint256 conversionRate) public ONLYOWNER845 { //inject NONSTANDARD NAMING
conversion = conversionRate;
}
function CONVERT77(uint256 usd) external view returns (uint256) { //inject NONSTANDARD NAMING
return usd * conversion;
}
}
interface IDSValue {
function PEEK123() external view returns (bytes32, bool); //inject NONSTANDARD NAMING
function READ988() external view returns (bytes32); //inject NONSTANDARD NAMING
function POKE435(bytes32 wut) external; //inject NONSTANDARD NAMING
function VOID212() external; //inject NONSTANDARD NAMING
}
library BytesLib {
function CONCAT154( //inject NONSTANDARD NAMING
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function CONCATSTORAGE572(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function SLICE625( //inject NONSTANDARD NAMING
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function TOADDRESS210(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function TOUINT8119(bytes memory _bytes, uint _start) internal pure returns (uint8) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function TOUINT16152(bytes memory _bytes, uint _start) internal pure returns (uint16) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function TOUINT32393(bytes memory _bytes, uint _start) internal pure returns (uint32) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function TOUINT64646(bytes memory _bytes, uint _start) internal pure returns (uint64) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function TOUINT96427(bytes memory _bytes, uint _start) internal pure returns (uint96) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function TOUINT12878(bytes memory _bytes, uint _start) internal pure returns (uint128) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function TOUINT505(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function TOBYTES32154(bytes memory _bytes, uint _start) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function EQUAL770(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function EQUALSTORAGE902( //inject NONSTANDARD NAMING
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
contract GunPreOrder is Ownable, ApproveAndCallFallBack {
using BytesLib for bytes;
using SafeMath for uint256;
//Event for when a bulk buy order has been placed
event CONSUMERBULKBUY355(uint8 category, uint256 quanity, address reserver); //inject NONSTANDARD NAMING
//Event for when a gun has been bought
event GUNSBOUGHT917(uint256 gunId, address owner, uint8 category); //inject NONSTANDARD NAMING
//Event for when ether is taken out of this contract
event WITHDRAWAL910(uint256 amount); //inject NONSTANDARD NAMING
//Default referal commision percent
uint256 public constant commission_percent82 = 5; //inject NONSTANDARD NAMING
//Whether category is open
mapping(uint8 => bool) public categoryExists;
mapping(uint8 => bool) public categoryOpen;
mapping(uint8 => bool) public categoryKilled;
//The additional referal commision percent for any given referal address (default is 0)
mapping(address => uint256) internal commissionRate;
//How many guns in a given category an address has reserved
mapping(uint8 => mapping(address => uint256)) public categoryReserveAmount;
//Opensea buy address
address internal constant opensea308 = 0x5b3256965e7C3cF26E11FCAf296DfC8807C01073; //inject NONSTANDARD NAMING
//The percent increase and percent base for a given category
mapping(uint8 => uint256) public categoryPercentIncrease;
mapping(uint8 => uint256) public categoryPercentBase;
//Price of a givevn category in USD WEI
mapping(uint8 => uint256) public categoryPrice;
//The percent of ether required for buying in BZN
mapping(uint8 => uint256) public requiredEtherPercent;
mapping(uint8 => uint256) public requiredEtherPercentBase;
bool public allowCreateCategory = true;
//The gun token contract
GunToken public token;
//The gun factory contract
GunFactory internal factory;
//The BZN contract
StandardBurnableToken internal bzn;
//The Maker ETH/USD price feed
IDSValue public ethFeed;
BZNFeed public bznFeed;
//The gamepool address
address internal gamePool;
//Require the skinned/regular shop to be opened
modifier ENSURESHOPOPEN328(uint8 category) { //inject NONSTANDARD NAMING
require(categoryExists[category], "Category doesn't exist!");
require(categoryOpen[category], "Category is not open!");
_;
}
//Allow a function to accept ETH payment
modifier PAYINETH352(address referal, uint8 category, address new_owner, uint16 quanity) { //inject NONSTANDARD NAMING
uint256 usdPrice;
uint256 totalPrice;
(usdPrice, totalPrice) = PRICEFOR73(category, quanity);
require(usdPrice > 0, "Price not yet set");
categoryPrice[category] = usdPrice; //Save last price
uint256 price = CONVERT77(totalPrice, false);
require(msg.value >= price, "Not enough Ether sent!");
_;
if (msg.value > price) {
uint256 change = msg.value - price;
msg.sender.transfer(change);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
uint256 totalCommision = commission_percent82 + commissionRate[referal];
uint256 commision = (price * totalCommision) / 100;
address payable _referal = address(uint160(referal));
_referal.transfer(commision);
}
}
//Allow function to accept BZN payment
modifier PAYINBZN388(address referal, uint8 category, address payable new_owner, uint16 quanity) { //inject NONSTANDARD NAMING
uint256[] memory prices = new uint256[](4); //Hack to work around local var limit (usdPrice, bznPrice, commision, totalPrice)
(prices[0], prices[3]) = PRICEFOR73(category, quanity);
require(prices[0] > 0, "Price not yet set");
categoryPrice[category] = prices[0];
prices[1] = CONVERT77(prices[3], true); //Convert the totalPrice to BZN
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
if (referal != address(0)) {
prices[2] = (prices[1] * (commission_percent82 + commissionRate[referal])) / 100;
}
uint256 requiredEther = (CONVERT77(prices[3], false) * requiredEtherPercent[category]) / requiredEtherPercentBase[category];
require(msg.value >= requiredEther, "Buying with BZN requires some Ether!");
bzn.BURNFROM813(new_owner, (((prices[1] - prices[2]) * 30) / 100));
bzn.TRANSFERFROM196(new_owner, gamePool, prices[1] - prices[2] - (((prices[1] - prices[2]) * 30) / 100));
_;
if (msg.value > requiredEther) {
new_owner.transfer(msg.value - requiredEther);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
bzn.TRANSFERFROM196(new_owner, referal, prices[2]);
prices[2] = (requiredEther * (commission_percent82 + commissionRate[referal])) / 100;
address payable _referal = address(uint160(referal));
_referal.transfer(prices[2]);
}
}
//Constructor
constructor(
address tokenAddress,
address tokenFactory,
address gp,
address isd,
address bzn_address
) public {
token = GunToken(tokenAddress);
factory = GunFactory(tokenFactory);
ethFeed = IDSValue(isd);
bzn = StandardBurnableToken(bzn_address);
gamePool = gp;
//Set percent increases
categoryPercentIncrease[1] = 100035;
categoryPercentBase[1] = 100000;
categoryPercentIncrease[2] = 100025;
categoryPercentBase[2] = 100000;
categoryPercentIncrease[3] = 100015;
categoryPercentBase[3] = 100000;
commissionRate[opensea308] = 10;
}
function CREATECATEGORY817(uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(allowCreateCategory);
categoryExists[category] = true;
}
function DISABLECREATECATEGORIES112() public ONLYOWNER845 { //inject NONSTANDARD NAMING
allowCreateCategory = false;
}
//Set the referal commision rate for an address
function SETCOMMISSION914(address referral, uint256 percent) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(percent > commission_percent82);
require(percent < 95);
percent = percent - commission_percent82;
commissionRate[referral] = percent;
}
//Set the price increase/base for skinned or regular guns
function SETPERCENTINCREASE775(uint256 increase, uint256 base, uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(increase > base);
categoryPercentIncrease[category] = increase;
categoryPercentBase[category] = base;
}
function SETETHERPERCENT411(uint256 percent, uint256 base, uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING
requiredEtherPercent[category] = percent;
requiredEtherPercentBase[category] = base;
}
function KILLCATEGORY428(uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(!categoryKilled[category]);
categoryOpen[category] = false;
categoryKilled[category] = true;
}
//Open/Close the skinned or regular guns shop
function SETSHOPSTATE191(uint8 category, bool open) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(category == 1 || category == 2 || category == 3);
require(!categoryKilled[category]);
require(categoryExists[category]);
categoryOpen[category] = open;
}
function SETPRICE360(uint8 category, uint256 price, bool inWei) public ONLYOWNER845 { //inject NONSTANDARD NAMING
uint256 multiply = 1e18;
if (inWei) {
multiply = 1;
}
categoryPrice[category] = price * multiply;
}
function WITHDRAW154(uint256 amount) public ONLYOWNER845 { //inject NONSTANDARD NAMING
uint256 balance = address(this).balance;
require(amount <= balance, "Requested to much");
address payable _owner = address(uint160(OWNER824()));
_owner.transfer(amount);
emit WITHDRAWAL910(amount);
}
function SETBZNFEEDCONTRACT654(address new_bzn_feed) public ONLYOWNER845 { //inject NONSTANDARD NAMING
bznFeed = BZNFeed(new_bzn_feed);
}
//Buy many skinned or regular guns with BZN. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function BUYWITHBZN846(address referal, uint8 category, address payable new_owner, uint16 quanity) ENSURESHOPOPEN328(category) PAYINBZN388(referal, category, new_owner, quanity) public payable returns (bool) { //inject NONSTANDARD NAMING
factory.MINTFOR528(new_owner, quanity, category);
return true;
}
//Buy many skinned or regular guns with ETH. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function BUYWITHETHER108(address referal, uint8 category, address new_owner, uint16 quanity) ENSURESHOPOPEN328(category) PAYINETH352(referal, category, new_owner, quanity) public payable returns (bool) { //inject NONSTANDARD NAMING
factory.MINTFOR528(new_owner, quanity, category);
return true;
}
function CONVERT77(uint256 usdValue, bool isBZN) public view returns (uint256) { //inject NONSTANDARD NAMING
if (isBZN) {
return bznFeed.CONVERT77(usdValue);
} else {
bool temp;
bytes32 aaa;
(aaa, temp) = ethFeed.PEEK123();
uint256 priceForEtherInUsdWei = uint256(aaa);
return usdValue / (priceForEtherInUsdWei / 1e18);
}
}
function PRICEFOR73(uint8 category, uint16 quanity) public view returns (uint256, uint256) { //inject NONSTANDARD NAMING
require(quanity > 0);
uint256 percent = categoryPercentIncrease[category];
uint256 base = categoryPercentBase[category];
uint256 currentPrice = categoryPrice[category];
uint256 nextPrice = currentPrice;
uint256 totalPrice = 0;
//We can't use exponents because we'll overflow quickly
//Only for loop :(
for (uint i = 0; i < quanity; i++) {
nextPrice = (currentPrice * percent) / base;
currentPrice = nextPrice;
totalPrice += nextPrice;
}
//Return the next price, as this is the true price
return (nextPrice, totalPrice);
}
//Determine if a tokenId exists (has been sold)
function SOLD957(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
return token.EXISTS127(_tokenId);
}
function RECEIVEAPPROVAL438(address from, uint256 tokenAmount, address tokenContract, bytes memory data) public payable returns (bool) { //inject NONSTANDARD NAMING
address referal;
uint8 category;
uint16 quanity;
(referal, category, quanity) = abi.decode(data, (address, uint8, uint16));
require(quanity >= 1);
address payable _from = address(uint160(from));
BUYWITHBZN846(referal, category, _from, quanity);
return true;
}
}
contract GunFactory is Ownable {
using strings for *;
uint8 public constant premium_category760 = 1; //inject NONSTANDARD NAMING
uint8 public constant midgrade_category818 = 2; //inject NONSTANDARD NAMING
uint8 public constant regular_category63 = 3; //inject NONSTANDARD NAMING
uint256 public constant one_month568 = 2628000; //inject NONSTANDARD NAMING
uint256 public mintedGuns = 0;
address preOrderAddress;
GunToken token;
mapping(uint8 => uint256) internal gunsMintedByCategory;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
mapping(uint8 => uint256) internal firstMonthLimit;
mapping(uint8 => uint256) internal secondMonthLimit;
mapping(uint8 => uint256) internal thirdMonthLimit;
uint256 internal startTime;
mapping(uint8 => uint256) internal currentMonthEnd;
uint256 internal monthOneEnd;
uint256 internal monthTwoEnd;
modifier ONLYPREORDER406 { //inject NONSTANDARD NAMING
require(msg.sender == preOrderAddress, "Not authorized");
_;
}
modifier ISINITIALIZED13 { //inject NONSTANDARD NAMING
require(preOrderAddress != address(0), "No linked preorder");
require(address(token) != address(0), "No linked token");
_;
}
constructor() public {
firstMonthLimit[premium_category760] = 5000;
firstMonthLimit[midgrade_category818] = 20000;
firstMonthLimit[regular_category63] = 30000;
secondMonthLimit[premium_category760] = 2500;
secondMonthLimit[midgrade_category818] = 10000;
secondMonthLimit[regular_category63] = 15000;
thirdMonthLimit[premium_category760] = 600;
thirdMonthLimit[midgrade_category818] = 3000;
thirdMonthLimit[regular_category63] = 6000;
startTime = block.timestamp;
monthOneEnd = startTime + one_month568;
monthTwoEnd = startTime + one_month568 + one_month568;
currentMonthEnd[premium_category760] = monthOneEnd;
currentMonthEnd[midgrade_category818] = monthOneEnd;
currentMonthEnd[regular_category63] = monthOneEnd;
}
function UINTTOSTRING328(uint v) internal pure returns (string memory) { //inject NONSTANDARD NAMING
if (v == 0) {
return "0";
}
uint j = v;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function MINTFOR528(address newOwner, uint16 size, uint8 category) public ONLYPREORDER406 ISINITIALIZED13 returns (uint256) { //inject NONSTANDARD NAMING
GunPreOrder preOrder = GunPreOrder(preOrderAddress);
require(preOrder.categoryExists(category), "Invalid category");
require(!HASREACHEDLIMIT199(category), "The monthly limit has been reached");
token.CLAIMALLOCATION316(newOwner, size, category);
mintedGuns++;
gunsMintedByCategory[category] = gunsMintedByCategory[category] + 1;
totalGunsMintedByCategory[category] = totalGunsMintedByCategory[category] + 1;
}
function HASREACHEDLIMIT199(uint8 category) internal returns (bool) { //inject NONSTANDARD NAMING
uint256 currentTime = block.timestamp;
uint256 limit = CURRENTLIMIT394(category);
uint256 monthEnd = currentMonthEnd[category];
//If the current block time is greater than or equal to the end of the month
if (currentTime >= monthEnd) {
//It's a new month, reset all limits
//gunsMintedByCategory[PREMIUM_CATEGORY] = 0;
//gunsMintedByCategory[MIDGRADE_CATEGORY] = 0;
//gunsMintedByCategory[REGULAR_CATEGORY] = 0;
gunsMintedByCategory[category] = 0;
//Set next month end to be equal one month in advance
//do this while the current time is greater than the next month end
while (currentTime >= monthEnd) {
monthEnd = monthEnd + one_month568;
}
//Finally, update the limit
limit = CURRENTLIMIT394(category);
currentMonthEnd[category] = monthEnd;
}
//Check if the limit has been reached
return gunsMintedByCategory[category] >= limit;
}
function REACHEDLIMIT389(uint8 category) public view returns (bool) { //inject NONSTANDARD NAMING
uint256 limit = CURRENTLIMIT394(category);
return gunsMintedByCategory[category] >= limit;
}
function CURRENTLIMIT394(uint8 category) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 currentTime = block.timestamp;
uint256 limit;
if (currentTime < monthOneEnd) {
limit = firstMonthLimit[category];
} else if (currentTime < monthTwoEnd) {
limit = secondMonthLimit[category];
} else {
limit = thirdMonthLimit[category];
}
return limit;
}
function SETCATEGORYLIMIT220(uint8 category, uint256 firstLimit, uint256 secondLimit, uint256 thirdLimit) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(firstMonthLimit[category] == 0);
require(secondMonthLimit[category] == 0);
require(thirdMonthLimit[category] == 0);
firstMonthLimit[category] = firstLimit;
secondMonthLimit[category] = secondLimit;
thirdMonthLimit[category] = thirdLimit;
}
function ATTACHPREORDER925(address dst) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(preOrderAddress == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunPreOrder preOrder = GunPreOrder(dst);
preOrderAddress = address(preOrder);
}
function ATTACHTOKEN953(address dst) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(address(token) == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunToken ct = GunToken(dst);
token = ct;
}
}
|
inject NONSTANDARD NAMING
|
function TRANSFERFROM196(address from, address to, uint256 tokenId) public {
| 6,431,769 |
[
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4235,
17598,
11249,
28644,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
interface DharmaTradeReserveV9Interface {
event ROLEMODIFIED858(Role indexed role, address account); //inject NONSTANDARD NAMING
event ROLEPAUSED516(Role indexed role); //inject NONSTANDARD NAMING
event ROLEUNPAUSED425(Role indexed role); //inject NONSTANDARD NAMING
event ETHERRECEIVED855(address sender, uint256 amount); //inject NONSTANDARD NAMING
enum Role { // #
DEPOSIT_MANAGER, // 0
ADJUSTER, // 1
WITHDRAWAL_MANAGER, // 2
RESERVE_TRADER, // 3
PAUSER // 4
}
struct RoleStatus {
address account;
bool paused;
}
function TRADEDAIFORETHER899( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEDAIFORETHERV2950( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEETHERFORDAI795( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought);
function TRADEETHERFORDAIV2625( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought);
function TRADEDAIFORTOKEN107( //inject NONSTANDARD NAMING
address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiSold);
function TRADETOKENFORDAI864( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiBought);
function TRADETOKENFORETHER84( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalEtherBought);
function TRADEETHERFORTOKEN818( //inject NONSTANDARD NAMING
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold);
function TRADEETHERFORTOKENUSINGETHERIZER867( //inject NONSTANDARD NAMING
address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalEtherSold);
function TRADEDAIFORETHERUSINGRESERVES556( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEDAIFORETHERUSINGRESERVESV2121( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI322( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV298( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function TRADEDAIFORTOKENUSINGRESERVES528( //inject NONSTANDARD NAMING
address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiSold);
function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI549( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function TRADETOKENFORETHERUSINGRESERVES915( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalEtherBought);
function TRADEETHERFORTOKENUSINGRESERVES405( //inject NONSTANDARD NAMING
address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalEtherSold);
function FINALIZEETHERDEPOSIT298( //inject NONSTANDARD NAMING
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external;
function FINALIZEDAIDEPOSIT931( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external;
function FINALIZEDHARMADAIDEPOSIT237( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external;
function MINT835(uint256 daiAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING
function REDEEM834(uint256 dDaiAmount) external returns (uint256 daiReceived); //inject NONSTANDARD NAMING
function TRADEDDAIFORUSDC353( //inject NONSTANDARD NAMING
uint256 daiEquivalentAmount, uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function TRADEUSDCFORDDAI141( //inject NONSTANDARD NAMING
uint256 usdcAmount, uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function WITHDRAWUSDC678(address recipient, uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDAI49(address recipient, uint256 daiAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDHARMADAI777(address recipient, uint256 dDaiAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWUSDCTOPRIMARYRECIPIENT422(uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDAITOPRIMARYRECIPIENT762(uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWETHER204( //inject NONSTANDARD NAMING
address payable recipient, uint256 etherAmount
) external;
function WITHDRAW439( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, uint256 amount
) external returns (bool success);
function CALLANY778( //inject NONSTANDARD NAMING
address payable target, uint256 amount, bytes calldata data
) external returns (bool ok, bytes memory returnData);
function SETDAILIMIT345(uint256 daiAmount) external; //inject NONSTANDARD NAMING
function SETETHERLIMIT550(uint256 daiAmount) external; //inject NONSTANDARD NAMING
function SETPRIMARYUSDCRECIPIENT259(address recipient) external; //inject NONSTANDARD NAMING
function SETPRIMARYDAIRECIPIENT972(address recipient) external; //inject NONSTANDARD NAMING
function SETROLE712(Role role, address account) external; //inject NONSTANDARD NAMING
function REMOVEROLE29(Role role) external; //inject NONSTANDARD NAMING
function PAUSE504(Role role) external; //inject NONSTANDARD NAMING
function UNPAUSE768(Role role) external; //inject NONSTANDARD NAMING
function ISPAUSED423(Role role) external view returns (bool paused); //inject NONSTANDARD NAMING
function ISROLE511(Role role) external view returns (bool hasRole); //inject NONSTANDARD NAMING
function ISDHARMASMARTWALLET695( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet);
function GETDEPOSITMANAGER250() external view returns (address depositManager); //inject NONSTANDARD NAMING
function GETADJUSTER715() external view returns (address adjuster); //inject NONSTANDARD NAMING
function GETRESERVETRADER735() external view returns (address reserveTrader); //inject NONSTANDARD NAMING
function GETWITHDRAWALMANAGER7() external view returns (address withdrawalManager); //inject NONSTANDARD NAMING
function GETPAUSER73() external view returns (address pauser); //inject NONSTANDARD NAMING
function GETRESERVES254() external view returns ( //inject NONSTANDARD NAMING
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
);
function GETDAILIMIT529() external view returns ( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 dDaiAmount
);
function GETETHERLIMIT792() external view returns (uint256 etherAmount); //inject NONSTANDARD NAMING
function GETPRIMARYUSDCRECIPIENT771() external view returns ( //inject NONSTANDARD NAMING
address recipient
);
function GETPRIMARYDAIRECIPIENT209() external view returns ( //inject NONSTANDARD NAMING
address recipient
);
function GETIMPLEMENTATION393() external view returns (address implementation); //inject NONSTANDARD NAMING
function GETVERSION945() external view returns (uint256 version); //inject NONSTANDARD NAMING
}
interface ERC20Interface {
function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE301(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE335(address, address) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER424(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM59(address, address, uint256) external returns (bool); //inject NONSTANDARD NAMING
}
interface DTokenInterface {
function MINT835(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING
function REDEEM834(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING
function REDEEMUNDERLYING110(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING
function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFUNDERLYING111(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER424(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE301(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function EXCHANGERATECURRENT826() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface TradeHelperInterface {
function TRADEUSDCFORDDAI141(uint256 amountUSDC, uint256 quotedDaiEquivalentAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING
function TRADEDDAIFORUSDC353(uint256 amountDai, uint256 quotedUSDCAmount) external returns (uint256 usdcReceived); //inject NONSTANDARD NAMING
function GETEXPECTEDDAI468(uint256 usdc) external view returns (uint256 dai); //inject NONSTANDARD NAMING
function GETEXPECTEDUSDC440(uint256 dai) external view returns (uint256 usdc); //inject NONSTANDARD NAMING
}
interface UniswapV1Interface {
function ETHTOTOKENSWAPINPUT251( //inject NONSTANDARD NAMING
uint256 minTokens, uint256 deadline
) external payable returns (uint256 tokensBought);
function TOKENTOETHTRANSFEROUTPUT929( //inject NONSTANDARD NAMING
uint256 ethBought, uint256 maxTokens, uint256 deadline, address recipient
) external returns (uint256 tokensSold);
}
interface UniswapV2Interface {
function SWAPTOKENSFOREXACTTOKENS91( //inject NONSTANDARD NAMING
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPEXACTTOKENSFORTOKENS457( //inject NONSTANDARD NAMING
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPEXACTTOKENSFORETH769( //inject NONSTANDARD NAMING
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPTOKENSFOREXACTETH731( //inject NONSTANDARD NAMING
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPETHFOREXACTTOKENS5( //inject NONSTANDARD NAMING
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function SWAPEXACTETHFORTOKENS903( //inject NONSTANDARD NAMING
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface EtherReceiverInterface {
function SETTLEETHER955() external; //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD510(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function MUL1(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 DIV802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, "SafeMath: division by zero");
return a / b;
}
}
contract TwoStepOwnable {
event OWNERSHIPTRANSFERRED461( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
address private _owner;
address private _newPotentialOwner;
function TRANSFEROWNERSHIP1000(address newOwner) external ONLYOWNER389 { //inject NONSTANDARD NAMING
require(
newOwner != address(0),
"TwoStepOwnable: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
function CANCELOWNERSHIPTRANSFER705() external ONLYOWNER389 { //inject NONSTANDARD NAMING
delete _newPotentialOwner;
}
function ACCEPTOWNERSHIP63() external { //inject NONSTANDARD NAMING
require(
msg.sender == _newPotentialOwner,
"TwoStepOwnable: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
emit OWNERSHIPTRANSFERRED461(_owner, msg.sender);
_owner = msg.sender;
}
function OWNER109() external view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
function ISOWNER823() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
modifier ONLYOWNER389() { //inject NONSTANDARD NAMING
require(ISOWNER823(), "TwoStepOwnable: caller is not the owner.");
_;
}
}
contract DharmaTradeReserveV9ImplementationStaging is DharmaTradeReserveV9Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a "primary recipient" the withdrawal manager can transfer Dai to.
address private _primaryDaiRecipient;
// Maintain a "primary recipient" the withdrawal manager can transfer USDC to.
address private _primaryUSDCRecipient;
// Maintain a maximum allowable transfer size (in Dai) for the deposit manager.
uint256 private _daiLimit;
// Maintain a maximum allowable transfer size (in Ether) for the deposit manager.
uint256 private _etherLimit;
bool private _originatesFromReserveTrader; // unused, don't change storage layout
uint256 private constant _version934 = 8; //inject NONSTANDARD NAMING
// This contract interacts with USDC, Dai, and Dharma Dai.
ERC20Interface internal constant _usdc172 = ERC20Interface( //inject NONSTANDARD NAMING
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
ERC20Interface internal constant _dai939 = ERC20Interface( //inject NONSTANDARD NAMING
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
ERC20Interface internal constant _etherizer566 = ERC20Interface( //inject NONSTANDARD NAMING
0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191
);
DTokenInterface internal constant _ddai325 = DTokenInterface( //inject NONSTANDARD NAMING
0x00000000001876eB1444c986fD502e618c587430
);
TradeHelperInterface internal constant _trade_helper648 = TradeHelperInterface( //inject NONSTANDARD NAMING
0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d
);
UniswapV1Interface internal constant _uniswap_dai496 = UniswapV1Interface( //inject NONSTANDARD NAMING
0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667
);
UniswapV2Interface internal constant _uniswap_router877 = UniswapV2Interface( //inject NONSTANDARD NAMING
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
EtherReceiverInterface internal constant _eth_receiver459 = EtherReceiverInterface( //inject NONSTANDARD NAMING
0xaf84687D21736F5E06f738c6F065e88890465E7c
);
address internal constant _weth740 = address( //inject NONSTANDARD NAMING
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
);
// The "Create2 Header" is used to compute smart wallet deployment addresses.
bytes21 internal constant _create2_header376 = bytes21( //inject NONSTANDARD NAMING
0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory
);
// The "Wallet creation code" header & footer are also used to derive wallets.
bytes internal constant _wallet_creation_code_header138 = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; //inject NONSTANDARD NAMING
bytes28 internal constant _wallet_creation_code_footer303 = bytes28( //inject NONSTANDARD NAMING
0x00000000000000000000000000000000000000000000000000000000
);
// Include a payable fallback so that the contract can receive Ether payments.
function () external payable {
emit ETHERRECEIVED855(msg.sender, msg.value);
}
function INITIALIZE669() external { //inject NONSTANDARD NAMING
// Approve Uniswap router to transfer Dai on behalf of this contract.
if (_dai939.ALLOWANCE335(address(this), address(_uniswap_router877)) != uint256(-1)) {
bool ok = _dai939.APPROVE301(address(_uniswap_router877), uint256(-1));
require(ok, "Dai approval for Uniswap router failed.");
}
}
function TRADEDAIFORETHER899( //inject NONSTANDARD NAMING
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_TRANSFERINTOKEN213(_dai939, msg.sender, daiAmount);
// Trade the Dai for the quoted Ether amount on Uniswap and send to caller.
totalDaiSold = _uniswap_dai496.TOKENTOETHTRANSFEROUTPUT929(
quotedEtherAmount, daiAmount, deadline, msg.sender
);
}
function TRADEDAIFORETHERV2950( //inject NONSTANDARD NAMING
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_TRANSFERINTOKEN213(_dai939, msg.sender, daiAmount);
// Establish path from Dai to Ether.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(_dai939), _weth740, false
);
// Trade Dai for quoted Ether amount on Uniswap (send to the caller).
amounts = _uniswap_router877.SWAPTOKENSFOREXACTETH731(
quotedEtherAmount, daiAmount, path, msg.sender, deadline
);
totalDaiSold = amounts[0];
}
function TRADETOKENFORETHER84( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalEtherBought) {
// Transfer the tokens from the caller and revert on failure.
_TRANSFERINTOKEN213(token, msg.sender, tokenAmount);
// Approve Uniswap router to transfer tokens on behalf of this contract.
_GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token);
// Establish path from target token to Ether.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(token), _weth740, false
);
// Trade tokens for quoted Ether amount on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPEXACTTOKENSFORETH769(
tokenAmount, quotedEtherAmount, path, address(this), deadline
);
totalEtherBought = amounts[1];
// Send quoted Ether amount to caller and revert with reason on failure.
(bool ok, ) = msg.sender.call.value(quotedEtherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function TRADEDAIFORTOKEN107( //inject NONSTANDARD NAMING
address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_TRANSFERINTOKEN213(_dai939, msg.sender, daiAmount);
// Establish path (direct or routed through Ether) from Dai to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(_dai939), token, routeThroughEther
);
// Trade the Dai for the quoted token amount on Uniswap and send to caller.
amounts = _uniswap_router877.SWAPTOKENSFOREXACTTOKENS91(
quotedTokenAmount, daiAmount, path, msg.sender, deadline
);
totalDaiSold = amounts[0];
}
function TRADEDAIFORETHERUSINGRESERVES556( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai939.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai325.REDEEMUNDERLYING110(additionalDaiRequired);
}
// Trade the Dai for the quoted Ether amount on Uniswap.
totalDaiSold = _uniswap_dai496.TOKENTOETHTRANSFEROUTPUT929(
quotedEtherAmount,
daiAmountFromReserves,
deadline,
address(_eth_receiver459)
);
// Move the Ether from the receiver to this contract (gas workaround).
_eth_receiver459.SETTLEETHER955();
}
function TRADEDAIFORETHERUSINGRESERVESV2121( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai939.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai325.REDEEMUNDERLYING110(additionalDaiRequired);
}
// Establish path from Dai to Ether.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(_dai939), _weth740, false
);
// Trade Dai for quoted Ether amount on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPTOKENSFOREXACTETH731(
quotedEtherAmount, daiAmountFromReserves, path, address(this), deadline
);
totalDaiSold = amounts[0];
}
function TRADETOKENFORETHERUSINGRESERVES915( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalEtherBought) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token);
// Establish path from target token to Ether.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(token), _weth740, false
);
// Trade tokens for quoted Ether amount on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPEXACTTOKENSFORETH769(
tokenAmountFromReserves, quotedEtherAmount, path, address(this), deadline
);
totalEtherBought = amounts[1];
}
function TRADEETHERFORDAI795( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount,
uint256 deadline
) external payable returns (uint256 totalDaiBought) {
// Trade the Ether for the quoted Dai amount on Uniswap.
totalDaiBought = _uniswap_dai496.ETHTOTOKENSWAPINPUT251.value(msg.value)(
quotedDaiAmount, deadline
);
// Transfer the Dai to the caller and revert on failure.
_TRANSFERTOKEN930(_dai939, msg.sender, quotedDaiAmount);
}
function TRADEETHERFORDAIV2625( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount,
uint256 deadline
) external payable returns (uint256 totalDaiBought) {
// Establish path from Ether to Dai.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(_dai939), false
);
// Trade Ether for Dai on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPEXACTETHFORTOKENS903.value(msg.value)(
quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[1];
// Transfer the Dai to the caller and revert on failure.
_TRANSFERTOKEN930(_dai939, msg.sender, quotedDaiAmount);
}
function TRADEETHERFORTOKEN818( //inject NONSTANDARD NAMING
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold) {
// Establish path from Ether to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(token), false
);
// Trade Ether for quoted token amount on Uniswap and send to caller.
amounts = _uniswap_router877.SWAPETHFOREXACTTOKENS5.value(msg.value)(
quotedTokenAmount, path, msg.sender, deadline
);
totalEtherSold = amounts[0];
}
function TRADEETHERFORTOKENUSINGETHERIZER867( //inject NONSTANDARD NAMING
address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalEtherSold) {
// Transfer the Ether from the caller and revert on failure.
_TRANSFERINTOKEN213(_etherizer566, msg.sender, etherAmount);
// Establish path from Ether to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(token), false
);
// Trade Ether for quoted token amount on Uniswap and send to caller.
amounts = _uniswap_router877.SWAPETHFOREXACTTOKENS5.value(etherAmount)(
quotedTokenAmount, path, msg.sender, deadline
);
totalEtherSold = amounts[0];
}
function TRADETOKENFORDAI864( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiBought) {
// Transfer the token from the caller and revert on failure.
_TRANSFERINTOKEN213(token, msg.sender, tokenAmount);
// Approve Uniswap router to transfer tokens on behalf of this contract.
_GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token);
// Establish path (direct or routed through Ether) from target token to Dai.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(token), address(_dai939), routeThroughEther
);
// Trade the Dai for the quoted token amount on Uniswap and send to caller.
amounts = _uniswap_router877.SWAPEXACTTOKENSFORTOKENS457(
tokenAmount, quotedDaiAmount, path, msg.sender, deadline
);
totalDaiBought = amounts[path.length - 1];
// Transfer the Dai to the caller and revert on failure.
_TRANSFERTOKEN930(_dai939, msg.sender, quotedDaiAmount);
}
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI322( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade the Ether for the quoted Dai amount on Uniswap.
totalDaiBought = _uniswap_dai496.ETHTOTOKENSWAPINPUT251.value(
etherAmountFromReserves
)(
quotedDaiAmount, deadline
);
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai325.MINT835(totalDaiBought);
}
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV298( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Establish path from Ether to Dai.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(_dai939), false
);
// Trade Ether for Dai on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPEXACTETHFORTOKENS903.value(
etherAmountFromReserves
)(
quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[1];
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai325.MINT835(totalDaiBought);
}
function TRADEETHERFORTOKENUSINGRESERVES405( //inject NONSTANDARD NAMING
address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) {
// Establish path from Ether to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(token), false
);
// Trade Ether for quoted token amount on Uniswap and send to this contract.
amounts = _uniswap_router877.SWAPETHFOREXACTTOKENS5.value(etherAmountFromReserves)(
quotedTokenAmount, path, address(this), deadline
);
totalEtherSold = amounts[0];
}
function TRADEDAIFORTOKENUSINGRESERVES528( //inject NONSTANDARD NAMING
address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai939.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai325.REDEEMUNDERLYING110(additionalDaiRequired);
}
// Establish path (direct or routed through Ether) from Dai to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(_dai939), address(token), routeThroughEther
);
// Trade the Dai for the quoted token amount on Uniswap.
amounts = _uniswap_router877.SWAPTOKENSFOREXACTTOKENS91(
quotedTokenAmount, daiAmountFromReserves, path, address(this), deadline
);
totalDaiSold = amounts[0];
}
function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI549( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token);
// Establish path (direct or routed through Ether) from target token to Dai.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(token), address(_dai939), routeThroughEther
);
// Trade the Dai for the quoted token amount on Uniswap.
amounts = _uniswap_router877.SWAPEXACTTOKENSFORTOKENS457(
tokenAmountFromReserves, quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[path.length - 1];
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai325.MINT835(totalDaiBought);
}
function FINALIZEDAIDEPOSIT931( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external ONLYOWNEROR665(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ENSURESMARTWALLET516(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(daiAmount < _daiLimit, "Transfer size exceeds the limit.");
// Transfer the Dai to the specified smart wallet.
_TRANSFERTOKEN930(_dai939, smartWallet, daiAmount);
}
function FINALIZEDHARMADAIDEPOSIT237( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external ONLYOWNEROR665(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ENSURESMARTWALLET516(smartWallet, initialUserSigningKey);
// Get the current dDai exchange rate.
uint256 exchangeRate = _ddai325.EXCHANGERATECURRENT826();
// Ensure that an exchange rate was actually returned.
require(exchangeRate != 0, "Could not retrieve dDai exchange rate.");
// Get the equivalent Dai amount of the transfer.
uint256 daiEquivalent = (dDaiAmount.MUL1(exchangeRate)) / 1e18;
// Ensure that the amount to transfer is lower than the limit.
require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit.");
// Transfer the dDai to the specified smart wallet.
_TRANSFERTOKEN930(ERC20Interface(address(_ddai325)), smartWallet, dDaiAmount);
}
function FINALIZEETHERDEPOSIT298( //inject NONSTANDARD NAMING
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external ONLYOWNEROR665(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ENSURESMARTWALLET516(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(etherAmount < _etherLimit, "Transfer size exceeds the limit.");
// Transfer the Ether to the specified smart wallet.
bool ok;
(ok, ) = smartWallet.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function MINT835( //inject NONSTANDARD NAMING
uint256 daiAmount
) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 dDaiMinted) {
// Use the specified amount of Dai to mint dDai.
dDaiMinted = _ddai325.MINT835(daiAmount);
}
function REDEEM834( //inject NONSTANDARD NAMING
uint256 dDaiAmount
) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 daiReceived) {
// Redeem the specified amount of dDai for Dai.
daiReceived = _ddai325.REDEEM834(dDaiAmount);
}
function TRADEUSDCFORDDAI141( //inject NONSTANDARD NAMING
uint256 usdcAmount,
uint256 quotedDaiEquivalentAmount
) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 dDaiMinted) {
dDaiMinted = _trade_helper648.TRADEUSDCFORDDAI141(
usdcAmount, quotedDaiEquivalentAmount
);
}
function TRADEDDAIFORUSDC353( //inject NONSTANDARD NAMING
uint256 daiEquivalentAmount,
uint256 quotedUSDCAmount
) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 usdcReceived) {
usdcReceived = _trade_helper648.TRADEDDAIFORUSDC353(
daiEquivalentAmount, quotedUSDCAmount
);
}
function WITHDRAWUSDCTOPRIMARYRECIPIENT422( //inject NONSTANDARD NAMING
uint256 usdcAmount
) external ONLYOWNEROR665(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryUSDCRecipient;
require(
primaryRecipient != address(0), "No USDC primary recipient currently set."
);
// Transfer the supplied USDC amount to the primary recipient.
_TRANSFERTOKEN930(_usdc172, primaryRecipient, usdcAmount);
}
function WITHDRAWDAITOPRIMARYRECIPIENT762( //inject NONSTANDARD NAMING
uint256 daiAmount
) external ONLYOWNEROR665(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryDaiRecipient;
require(
primaryRecipient != address(0), "No Dai primary recipient currently set."
);
// Transfer the supplied Dai amount to the primary recipient.
_TRANSFERTOKEN930(_dai939, primaryRecipient, daiAmount);
}
function WITHDRAWUSDC678( //inject NONSTANDARD NAMING
address recipient, uint256 usdcAmount
) external ONLYOWNER389 {
// Transfer the USDC to the specified recipient.
_TRANSFERTOKEN930(_usdc172, recipient, usdcAmount);
}
function WITHDRAWDAI49( //inject NONSTANDARD NAMING
address recipient, uint256 daiAmount
) external ONLYOWNER389 {
// Transfer the Dai to the specified recipient.
_TRANSFERTOKEN930(_dai939, recipient, daiAmount);
}
function WITHDRAWDHARMADAI777( //inject NONSTANDARD NAMING
address recipient, uint256 dDaiAmount
) external ONLYOWNER389 {
// Transfer the dDai to the specified recipient.
_TRANSFERTOKEN930(ERC20Interface(address(_ddai325)), recipient, dDaiAmount);
}
function WITHDRAWETHER204( //inject NONSTANDARD NAMING
address payable recipient, uint256 etherAmount
) external ONLYOWNER389 {
bool ok;
// Transfer the Ether to the specified recipient.
(ok, ) = recipient.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function WITHDRAW439( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, uint256 amount
) external ONLYOWNER389 returns (bool success) {
// Transfer the token to the specified recipient.
success = token.TRANSFER424(recipient, amount);
}
function CALLANY778( //inject NONSTANDARD NAMING
address payable target, uint256 amount, bytes calldata data
) external ONLYOWNER389 returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
}
function SETDAILIMIT345(uint256 daiAmount) external ONLYOWNER389 { //inject NONSTANDARD NAMING
// Set the new limit.
_daiLimit = daiAmount;
}
function SETETHERLIMIT550(uint256 etherAmount) external ONLYOWNER389 { //inject NONSTANDARD NAMING
// Set the new limit.
_etherLimit = etherAmount;
}
function SETPRIMARYUSDCRECIPIENT259(address recipient) external ONLYOWNER389 { //inject NONSTANDARD NAMING
// Set the new primary recipient.
_primaryUSDCRecipient = recipient;
}
function SETPRIMARYDAIRECIPIENT972(address recipient) external ONLYOWNER389 { //inject NONSTANDARD NAMING
// Set the new primary recipient.
_primaryDaiRecipient = recipient;
}
function PAUSE504(Role role) external ONLYOWNEROR665(Role.PAUSER) { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role in question is already paused.");
storedRoleStatus.paused = true;
emit ROLEPAUSED516(role);
}
function UNPAUSE768(Role role) external ONLYOWNER389 { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role in question is already unpaused.");
storedRoleStatus.paused = false;
emit ROLEUNPAUSED425(role);
}
function SETROLE712(Role role, address account) external ONLYOWNER389 { //inject NONSTANDARD NAMING
require(account != address(0), "Must supply an account.");
_SETROLE905(role, account);
}
function REMOVEROLE29(Role role) external ONLYOWNER389 { //inject NONSTANDARD NAMING
_SETROLE905(role, address(0));
}
function ISPAUSED423(Role role) external view returns (bool paused) { //inject NONSTANDARD NAMING
paused = _ISPAUSED128(role);
}
function ISROLE511(Role role) external view returns (bool hasRole) { //inject NONSTANDARD NAMING
hasRole = _ISROLE24(role);
}
function ISDHARMASMARTWALLET695( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet) {
dharmaSmartWallet = _ISSMARTWALLET926(smartWallet, initialUserSigningKey);
}
function GETDEPOSITMANAGER250() external view returns (address depositManager) { //inject NONSTANDARD NAMING
depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account;
}
function GETADJUSTER715() external view returns (address adjuster) { //inject NONSTANDARD NAMING
adjuster = _roles[uint256(Role.ADJUSTER)].account;
}
function GETRESERVETRADER735() external view returns (address reserveTrader) { //inject NONSTANDARD NAMING
reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account;
}
function GETWITHDRAWALMANAGER7() external view returns (address withdrawalManager) { //inject NONSTANDARD NAMING
withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account;
}
function GETPAUSER73() external view returns (address pauser) { //inject NONSTANDARD NAMING
pauser = _roles[uint256(Role.PAUSER)].account;
}
function GETRESERVES254() external view returns ( //inject NONSTANDARD NAMING
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
) {
dai = _dai939.BALANCEOF395(address(this));
dDai = _ddai325.BALANCEOF395(address(this));
dDaiUnderlying = _ddai325.BALANCEOFUNDERLYING111(address(this));
}
function GETDAILIMIT529() external view returns ( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 dDaiAmount
) {
daiAmount = _daiLimit;
dDaiAmount = (daiAmount.MUL1(1e18)).DIV802(_ddai325.EXCHANGERATECURRENT826());
}
function GETETHERLIMIT792() external view returns (uint256 etherAmount) { //inject NONSTANDARD NAMING
etherAmount = _etherLimit;
}
function GETPRIMARYUSDCRECIPIENT771() external view returns ( //inject NONSTANDARD NAMING
address recipient
) {
recipient = _primaryUSDCRecipient;
}
function GETPRIMARYDAIRECIPIENT209() external view returns ( //inject NONSTANDARD NAMING
address recipient
) {
recipient = _primaryDaiRecipient;
}
function GETIMPLEMENTATION393() external view returns ( //inject NONSTANDARD NAMING
address implementation
) {
(bool ok, bytes memory returnData) = address(
0x481B1a16E6675D33f8BBb3a6A58F5a9678649718
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
function GETVERSION945() external view returns (uint256 version) { //inject NONSTANDARD NAMING
version = _version934;
}
function _GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(ERC20Interface token) internal { //inject NONSTANDARD NAMING
// Approve Uniswap router to transfer tokens on behalf of this contract.
if (token.ALLOWANCE335(address(this), address(_uniswap_router877)) != uint256(-1)) {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(
token.APPROVE301.selector, address(_uniswap_router877), uint256(-1)
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Token approval for Uniswap router failed."
);
}
}
function _SETROLE905(Role role, address account) internal { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit ROLEMODIFIED858(role, account);
}
}
function _ISROLE24(Role role) internal view returns (bool hasRole) { //inject NONSTANDARD NAMING
hasRole = msg.sender == _roles[uint256(role)].account;
}
function _ISPAUSED128(Role role) internal view returns (bool paused) { //inject NONSTANDARD NAMING
paused = _roles[uint256(role)].paused;
}
function _ISSMARTWALLET926( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) internal pure returns (bool) {
// Derive the keccak256 hash of the smart wallet initialization code.
bytes32 initCodeHash = keccak256(
abi.encodePacked(
_wallet_creation_code_header138,
initialUserSigningKey,
_wallet_creation_code_footer303
)
);
// Attempt to derive a smart wallet address that matches the one provided.
address target;
for (uint256 nonce = 0; nonce < 10; nonce++) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using all inputs.
abi.encodePacked( // pack all inputs to the hash together.
_create2_header376, // pass in control character + factory address.
nonce, // pass in current nonce as the salt.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Exit early if the provided smart wallet matches derived target address.
if (target == smartWallet) {
return true;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
// Explicity recognize no target was found matching provided smart wallet.
return false;
}
function _TRANSFERTOKEN930(ERC20Interface token, address to, uint256 amount) internal { //inject NONSTANDARD NAMING
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(token.TRANSFER424.selector, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer out failed.'
);
}
function _TRANSFERINTOKEN213(ERC20Interface token, address from, uint256 amount) internal { //inject NONSTANDARD NAMING
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(token.TRANSFERFROM59.selector, from, address(this), amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer in failed.'
);
}
function _ENSURESMARTWALLET516( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) internal view {
require(
_ISSMARTWALLET926(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
}
function _CREATEPATHANDAMOUNTS796( //inject NONSTANDARD NAMING
address start, address end, bool routeThroughEther
) internal pure returns (address[] memory, uint256[] memory) {
uint256 pathLength = routeThroughEther ? 3 : 2;
address[] memory path = new address[](pathLength);
path[0] = start;
if (routeThroughEther) {
path[1] = _weth740;
}
path[pathLength - 1] = end;
return (path, new uint256[](pathLength));
}
modifier ONLYOWNEROR665(Role role) { //inject NONSTANDARD NAMING
if (!ISOWNER823()) {
require(_ISROLE24(role), "Caller does not have a required role.");
require(!_ISPAUSED128(role), "Role in question is currently paused.");
}
_;
}
}
|
Move the Ether from the receiver to this contract (gas workaround).
|
_eth_receiver459.SETTLEETHER955();
| 12,960,483 |
[
1,
7607,
326,
512,
1136,
628,
326,
5971,
358,
333,
6835,
261,
31604,
18975,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
389,
546,
67,
24454,
24,
6162,
18,
27543,
900,
1584,
3891,
29,
2539,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x1c9929a2Ba42E9F4CBa83A8419B42d3FcBf59F6A/sources/SIX.sol
|
* @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;
}
| 9,206,854 |
[
1,
9704,
288,
45,
654,
39,
3462,
17,
12908,
537,
5496,
29076,
30,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
389,
12908,
537,
24899,
3576,
12021,
9334,
17571,
264,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-29
*/
/**
*Submitted for verification at Etherscan.io on 2021-06-03
*/
/**
*Submitted for verification at Etherscan.io on 2021-04-14
*/
// SPDX-License-Identifier: AGPL-3.0-or-later\
pragma solidity 0.7.5;
/**
* @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");
}
}
}
/**
* @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;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
/*
* Expects percentage to be trailed by 00,
*/
function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) {
return div( mul( total_, percentage_ ), 1000 );
}
/*
* Expects percentage to be trailed by 00,
*/
function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) {
return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) );
}
function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) {
return div( mul(part_, 100) , total_ );
}
/**
* Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) {
return sqrrt( mul( multiplier_, payment_ ) );
}
function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) {
return mul( multiplier_, supply_ );
}
}
/**
* @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 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
/**
* @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 ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external returns ( uint );
}
interface IPOLY {
function isApprovedSeller( address _address ) external view returns ( bool );
}
interface ICirculatingOHM {
function OHMCirculatingSupply() external view returns ( uint );
}
/**
* Exercise contract for unapproved sellers prior to migrating pOLY.
* It is not possible for a user to use both (no double dipping).
*/
contract AltExercisepOLY {
using SafeMath for uint;
using SafeERC20 for IERC20;
address owner;
address newOwner;
address immutable pOLY;
address immutable OHM;
address immutable DAI;
address immutable treasury;
address immutable circulatingOHMContract;
struct Term {
uint percent; // 4 decimals ( 5000 = 0.5% )
uint claimed;
uint max;
}
mapping( address => Term ) public terms;
mapping( address => address ) public walletChange;
constructor( address _pOLY, address _ohm, address _dai, address _treasury, address _circulatingOHMContract ) {
owner = msg.sender;
require( _pOLY != address(0) );
pOLY = _pOLY;
require( _ohm != address(0) );
OHM = _ohm;
require( _dai != address(0) );
DAI = _dai;
require( _treasury != address(0) );
treasury = _treasury;
require( _circulatingOHMContract != address(0) );
circulatingOHMContract = _circulatingOHMContract;
}
// Sets terms for a new wallet
function setTerms(address _vester, uint _rate, uint _claimed, uint _max ) external {
require( msg.sender == owner, "Sender is not owner" );
require( _max >= terms[ _vester ].max, "cannot lower amount claimable" );
require( _rate >= terms[ _vester ].percent, "cannot lower vesting rate" );
require( _claimed >= terms[ _vester ].claimed, "cannot lower claimed" );
require( !IPOLY( pOLY ).isApprovedSeller( _vester ) );
terms[ _vester ] = Term({
percent: _rate,
claimed: _claimed,
max: _max
});
}
// Allows wallet to redeem pOLY for OHM
function exercise( uint _amount ) external {
Term memory info = terms[ msg.sender ];
require( redeemable( info ) >= _amount, 'Not enough vested' );
require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' );
IERC20( DAI ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20( pOLY ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20( DAI ).approve( treasury, _amount );
uint OHMToSend = ITreasury( treasury ).deposit( _amount, DAI, 0 );
terms[ msg.sender ].claimed = info.claimed.add( _amount );
IERC20( OHM ).safeTransfer( msg.sender, OHMToSend );
}
// Allows wallet owner to transfer rights to a new address
function pushWalletChange( address _newWallet ) external {
require( terms[ msg.sender ].percent != 0 );
walletChange[ msg.sender ] = _newWallet;
}
// Allows wallet to pull rights from an old address
function pullWalletChange( address _oldWallet ) external {
require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" );
walletChange[ _oldWallet ] = address(0);
terms[ msg.sender ] = terms[ _oldWallet ];
delete terms[ _oldWallet ];
}
// Amount a wallet can redeem based on current supply
function redeemableFor( address _vester ) public view returns (uint) {
return redeemable( terms[ _vester ]);
}
function redeemable( Term memory _info ) internal view returns ( uint ) {
return ( ICirculatingOHM( circulatingOHMContract ).OHMCirculatingSupply().mul( _info.percent ).mul( 1000 ) ).sub( _info.claimed );
}
function pushOwnership( address _newOwner ) external returns ( bool ) {
require( msg.sender == owner, "Sender is not owner" );
require( _newOwner != address(0) );
newOwner = _newOwner;
return true;
}
function pullOwnership() external returns ( bool ) {
require( msg.sender == newOwner );
owner = newOwner;
newOwner = address(0);
return true;
}
}
|
* @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;
pragma solidity 0.7.5;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
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));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
| 7,711,075 |
[
1,
9890,
654,
39,
3462,
225,
4266,
10422,
6740,
4232,
39,
3462,
5295,
716,
604,
603,
5166,
261,
13723,
326,
1147,
6835,
1135,
629,
2934,
13899,
716,
327,
1158,
460,
261,
464,
3560,
15226,
578,
604,
603,
5166,
13,
854,
2546,
3260,
16,
1661,
17,
266,
1097,
310,
4097,
854,
12034,
358,
506,
6873,
18,
2974,
999,
333,
5313,
1846,
848,
527,
279,
1375,
9940,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
68,
3021,
358,
3433,
6835,
16,
1492,
5360,
1846,
358,
745,
326,
4183,
5295,
487,
1375,
2316,
18,
4626,
5912,
5825,
13,
9191,
5527,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
12083,
14060,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
27,
18,
25,
31,
203,
565,
445,
4183,
5912,
12,
45,
654,
39,
3462,
1147,
16,
1758,
358,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
389,
1991,
6542,
990,
12,
2316,
16,
24126,
18,
3015,
1190,
4320,
12,
2316,
18,
13866,
18,
9663,
16,
358,
16,
460,
10019,
203,
565,
289,
203,
203,
565,
445,
4183,
5912,
1265,
12,
45,
654,
39,
3462,
1147,
16,
1758,
628,
16,
1758,
358,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
389,
1991,
6542,
990,
12,
2316,
16,
24126,
18,
3015,
1190,
4320,
12,
2316,
18,
13866,
1265,
18,
9663,
16,
628,
16,
358,
16,
460,
10019,
203,
565,
289,
203,
203,
565,
445,
4183,
12053,
537,
12,
45,
654,
39,
3462,
1147,
16,
1758,
17571,
264,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
2583,
12443,
1132,
422,
374,
13,
747,
261,
2316,
18,
5965,
1359,
12,
2867,
12,
2211,
3631,
17571,
264,
13,
422,
374,
3631,
203,
5411,
315,
9890,
654,
39,
3462,
30,
6617,
537,
628,
1661,
17,
7124,
358,
1661,
17,
7124,
1699,
1359,
6,
203,
3639,
11272,
203,
3639,
389,
1991,
6542,
990,
12,
2316,
16,
24126,
18,
3015,
1190,
4320,
12,
2316,
18,
12908,
537,
18,
9663,
16,
17571,
264,
16,
460,
10019,
203,
565,
289,
203,
203,
565,
445,
4183,
382,
11908,
7009,
2
] |
pragma solidity 0.6.7;
abstract contract StabilityFeeTreasuryLike {
function getAllowance(address) virtual public view returns (uint256, uint256);
function setPerBlockAllowance(address, uint256) virtual external;
}
abstract contract TreasuryFundableLike {
function authorizedAccounts(address) virtual public view returns (uint256);
function baseUpdateCallerReward() virtual public view returns (uint256);
function maxUpdateCallerReward() virtual public view returns (uint256);
function modifyParameters(bytes32, uint256) virtual external;
}
abstract contract TreasuryParamAdjusterLike {
function adjustMaxReward(address receiver, bytes4 targetFunctionSignature, uint256 newMaxReward) virtual external;
}
abstract contract OracleLike {
function read() virtual external view returns (uint256);
}
abstract contract OracleRelayerLike {
function redemptionPrice() virtual public returns (uint256);
}
contract MinMaxRewardsAdjuster {
// --- Auth ---
mapping (address => uint) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "MinMaxRewardsAdjuster/account-not-authorized");
_;
}
// --- Structs ---
struct FundingReceiver {
// Last timestamp when the funding receiver data was updated
uint256 lastUpdateTime; // [unix timestamp]
// Gas amount used to execute this funded function
uint256 gasAmountForExecution; // [gas amount]
// Delay between two calls to recompute the fees for this funded function
uint256 updateDelay; // [seconds]
// Multiplier applied to the computed base reward
uint256 baseRewardMultiplier; // [hundred]
// Multiplied applied to the computed max reward
uint256 maxRewardMultiplier; // [hundred]
}
// --- Variables ---
// Data about funding receivers
mapping(address => mapping(bytes4 => FundingReceiver)) public fundingReceivers;
// The gas price oracle
OracleLike public gasPriceOracle;
// The ETH oracle
OracleLike public ethPriceOracle;
// The contract that adjusts SF treasury parameters and needs to be updated with max rewards for each funding receiver
TreasuryParamAdjusterLike public treasuryParamAdjuster;
// The oracle relayer contract
OracleRelayerLike public oracleRelayer;
// The SF treasury contract
StabilityFeeTreasuryLike public treasury;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(bytes32 parameter, address addr);
event ModifyParameters(address receiver, bytes4 targetFunction, bytes32 parameter, uint256 val);
event AddFundingReceiver(
address indexed receiver,
bytes4 targetFunctionSignature,
uint256 updateDelay,
uint256 gasAmountForExecution,
uint256 baseRewardMultiplier,
uint256 maxRewardMultiplier
);
event RemoveFundingReceiver(address indexed receiver, bytes4 targetFunctionSignature);
event RecomputedRewards(address receiver, uint256 newBaseReward, uint256 newMaxReward);
constructor(
address oracleRelayer_,
address treasury_,
address gasPriceOracle_,
address ethPriceOracle_,
address treasuryParamAdjuster_
) public {
// Checks
require(oracleRelayer_ != address(0), "MinMaxRewardsAdjuster/null-oracle-relayer");
require(treasury_ != address(0), "MinMaxRewardsAdjuster/null-treasury");
require(gasPriceOracle_ != address(0), "MinMaxRewardsAdjuster/null-gas-oracle");
require(ethPriceOracle_ != address(0), "MinMaxRewardsAdjuster/null-eth-oracle");
require(treasuryParamAdjuster_ != address(0), "MinMaxRewardsAdjuster/null-treasury-adjuster");
authorizedAccounts[msg.sender] = 1;
// Store
oracleRelayer = OracleRelayerLike(oracleRelayer_);
treasury = StabilityFeeTreasuryLike(treasury_);
gasPriceOracle = OracleLike(gasPriceOracle_);
ethPriceOracle = OracleLike(ethPriceOracle_);
treasuryParamAdjuster = TreasuryParamAdjusterLike(treasuryParamAdjuster_);
// Check that the oracle relayer has a redemption price stored
oracleRelayer.redemptionPrice();
// Emit events
emit ModifyParameters("treasury", treasury_);
emit ModifyParameters("oracleRelayer", oracleRelayer_);
emit ModifyParameters("gasPriceOracle", gasPriceOracle_);
emit ModifyParameters("ethPriceOracle", ethPriceOracle_);
emit ModifyParameters("treasuryParamAdjuster", treasuryParamAdjuster_);
}
// --- Boolean Logic ---
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y)}
}
// --- Math ---
uint256 public constant WAD = 10**18;
uint256 public constant RAY = 10**27;
uint256 public constant HUNDRED = 100;
uint256 public constant THOUSAND = 1000;
function addition(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "MinMaxRewardsAdjuster/add-uint-uint-overflow");
}
function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "MinMaxRewardsAdjuster/sub-uint-uint-underflow");
}
function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "MinMaxRewardsAdjuster/multiply-uint-uint-overflow");
}
function divide(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y > 0, "MinMaxRewardsAdjuster/div-y-null");
z = x / y;
require(z <= x, "MinMaxRewardsAdjuster/div-invalid");
}
// --- Administration ---
/*
* @notify Update the address of a contract that this adjuster is connected to
* @param parameter The name of the contract to update the address for
* @param addr The new contract address
*/
function modifyParameters(bytes32 parameter, address addr) external isAuthorized {
require(addr != address(0), "MinMaxRewardsAdjuster/null-address");
if (parameter == "oracleRelayer") {
oracleRelayer = OracleRelayerLike(addr);
oracleRelayer.redemptionPrice();
}
else if (parameter == "treasury") {
treasury = StabilityFeeTreasuryLike(addr);
}
else if (parameter == "gasPriceOracle") {
gasPriceOracle = OracleLike(addr);
}
else if (parameter == "ethPriceOracle") {
ethPriceOracle = OracleLike(addr);
}
else if (parameter == "treasuryParamAdjuster") {
treasuryParamAdjuster = TreasuryParamAdjusterLike(addr);
}
else revert("MinMaxRewardsAdjuster/modify-unrecognized-params");
emit ModifyParameters(parameter, addr);
}
/*
* @notify Change a parameter for a funding receiver
* @param receiver The address of the funding receiver
* @param targetFunction The function whose callers receive funding for calling
* @param parameter The name of the parameter to change
* @param val The new parameter value
*/
function modifyParameters(address receiver, bytes4 targetFunction, bytes32 parameter, uint256 val) external isAuthorized {
require(val > 0, "MinMaxRewardsAdjuster/null-value");
FundingReceiver storage fundingReceiver = fundingReceivers[receiver][targetFunction];
require(fundingReceiver.lastUpdateTime > 0, "MinMaxRewardsAdjuster/non-existent-receiver");
if (parameter == "gasAmountForExecution") {
require(val < block.gaslimit, "MinMaxRewardsAdjuster/invalid-gas-amount-for-exec");
fundingReceiver.gasAmountForExecution = val;
}
else if (parameter == "updateDelay") {
fundingReceiver.updateDelay = val;
}
else if (parameter == "baseRewardMultiplier") {
require(both(val >= HUNDRED, val <= THOUSAND), "MinMaxRewardsAdjuster/invalid-base-reward-multiplier");
require(val <= fundingReceiver.maxRewardMultiplier, "MinMaxRewardsAdjuster/max-mul-smaller-than-min-mul");
fundingReceiver.baseRewardMultiplier = val;
}
else if (parameter == "maxRewardMultiplier") {
require(both(val >= HUNDRED, val <= THOUSAND), "MinMaxRewardsAdjuster/invalid-max-reward-multiplier");
require(val >= fundingReceiver.baseRewardMultiplier, "MinMaxRewardsAdjuster/max-mul-smaller-than-min-mul");
fundingReceiver.maxRewardMultiplier = val;
}
else revert("MinMaxRewardsAdjuster/modify-unrecognized-params");
emit ModifyParameters(receiver, targetFunction, parameter, val);
}
/*
* @notify Add a new funding receiver
* @param receiver The funding receiver address
* @param targetFunctionSignature The signature of the function whose callers get funding
* @param updateDelay The update delay between two consecutive calls that update the base and max rewards for this receiver
* @param gasAmountForExecution The gas amount spent calling the function with signature targetFunctionSignature
* @param baseRewardMultiplier Multiplier applied to the computed base reward
* @param maxRewardMultiplier Multiplied applied to the computed max reward
*/
function addFundingReceiver(
address receiver,
bytes4 targetFunctionSignature,
uint256 updateDelay,
uint256 gasAmountForExecution,
uint256 baseRewardMultiplier,
uint256 maxRewardMultiplier
) external isAuthorized {
// Checks
require(receiver != address(0), "MinMaxRewardsAdjuster/null-receiver");
require(updateDelay > 0, "MinMaxRewardsAdjuster/null-update-delay");
require(both(baseRewardMultiplier >= HUNDRED, baseRewardMultiplier <= THOUSAND), "MinMaxRewardsAdjuster/invalid-base-reward-multiplier");
require(both(maxRewardMultiplier >= HUNDRED, maxRewardMultiplier <= THOUSAND), "MinMaxRewardsAdjuster/invalid-max-reward-multiplier");
require(maxRewardMultiplier >= baseRewardMultiplier, "MinMaxRewardsAdjuster/max-mul-smaller-than-min-mul");
require(gasAmountForExecution > 0, "MinMaxRewardsAdjuster/null-gas-amount");
require(gasAmountForExecution < block.gaslimit, "MinMaxRewardsAdjuster/large-gas-amount-for-exec");
// Check that the receiver hasn't been already added
FundingReceiver storage newReceiver = fundingReceivers[receiver][targetFunctionSignature];
require(newReceiver.lastUpdateTime == 0, "MinMaxRewardsAdjuster/receiver-already-added");
// Add the receiver's data
newReceiver.lastUpdateTime = now;
newReceiver.updateDelay = updateDelay;
newReceiver.gasAmountForExecution = gasAmountForExecution;
newReceiver.baseRewardMultiplier = baseRewardMultiplier;
newReceiver.maxRewardMultiplier = maxRewardMultiplier;
emit AddFundingReceiver(
receiver,
targetFunctionSignature,
updateDelay,
gasAmountForExecution,
baseRewardMultiplier,
maxRewardMultiplier
);
}
/*
* @notify Remove an already added funding receiver
* @param receiver The funding receiver address
* @param targetFunctionSignature The signature of the function whose callers get funding
*/
function removeFundingReceiver(address receiver, bytes4 targetFunctionSignature) external isAuthorized {
// Check that the receiver is still stored and then delete it
require(fundingReceivers[receiver][targetFunctionSignature].lastUpdateTime > 0, "MinMaxRewardsAdjuster/non-existent-receiver");
delete(fundingReceivers[receiver][targetFunctionSignature]);
emit RemoveFundingReceiver(receiver, targetFunctionSignature);
}
// --- Core Logic ---
/*
* @notify Recompute the base and max rewards for a specific funding receiver with a specific function offering funding
* @param receiver The funding receiver address
* @param targetFunctionSignature The signature of the function whose callers get funding
*/
function recomputeRewards(address receiver, bytes4 targetFunctionSignature) external {
FundingReceiver storage targetReceiver = fundingReceivers[receiver][targetFunctionSignature];
require(both(targetReceiver.lastUpdateTime > 0, addition(targetReceiver.lastUpdateTime, targetReceiver.updateDelay) <= now), "MinMaxRewardsAdjuster/wait-more");
// Update last time
targetReceiver.lastUpdateTime = now;
// Read the gas and the ETH prices
uint256 gasPrice = gasPriceOracle.read();
uint256 ethPrice = ethPriceOracle.read();
// Calculate the base fiat value
uint256 baseRewardFiatValue = divide(multiply(multiply(gasPrice, targetReceiver.gasAmountForExecution), WAD), ethPrice);
// Calculate the base reward expressed in system coins
uint256 newBaseReward = divide(multiply(baseRewardFiatValue, RAY), oracleRelayer.redemptionPrice());
newBaseReward = divide(multiply(newBaseReward, targetReceiver.baseRewardMultiplier), HUNDRED);
// Compute the new max reward and check both rewards
uint256 newMaxReward = divide(multiply(newBaseReward, targetReceiver.maxRewardMultiplier), HUNDRED);
require(both(newBaseReward > 0, newMaxReward > 0), "MinMaxRewardsAdjuster/null-new-rewards");
// Notify the treasury param adjuster about the new max reward
treasuryParamAdjuster.adjustMaxReward(receiver, targetFunctionSignature, newMaxReward);
// Approve the max reward in the treasury
treasury.setPerBlockAllowance(receiver, multiply(newMaxReward, RAY));
// Set the new rewards inside the receiver contract
if (TreasuryFundableLike(receiver).baseUpdateCallerReward() < newMaxReward) {
TreasuryFundableLike(receiver).modifyParameters("maxUpdateCallerReward", newMaxReward);
TreasuryFundableLike(receiver).modifyParameters("baseUpdateCallerReward", newBaseReward);
} else {
TreasuryFundableLike(receiver).modifyParameters("baseUpdateCallerReward", newBaseReward);
TreasuryFundableLike(receiver).modifyParameters("maxUpdateCallerReward", newMaxReward);
}
emit RecomputedRewards(receiver, newBaseReward, newMaxReward);
}
}
|
* @notice Remove auth from an account @param account Account to remove auth from/
|
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
| 7,084 |
[
1,
3288,
1357,
628,
392,
2236,
225,
2236,
6590,
358,
1206,
1357,
628,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1206,
6063,
12,
2867,
2236,
13,
3903,
353,
15341,
288,
203,
3639,
10799,
13971,
63,
4631,
65,
273,
374,
31,
203,
3639,
3626,
3581,
6063,
12,
4631,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// LC->07.08.2018
facts гл_предл language=Russian
{
arity=3
//violation_score=-5
generic
return=boolean
}
#define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{}
#region Предлог_В
// ------------------- С ПРЕДЛОГОМ 'В' ---------------------------
#region Предложный
// Глаголы и отглагольные части речи, присоединяющие
// предложное дополнение с предлогом В и сущ. в предложном падеже.
wordentry_set Гл_В_Предл =
{
rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль
// вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб
rus_verbs:воевать{}, // Воевал во Франции.
rus_verbs:устать{}, // Устали в дороге?
rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения.
rus_verbs:решить{}, // Что решат в правительстве?
rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает.
rus_verbs:обстоять{}, // В действительности же дело обстояло не так.
rus_verbs:подыматься{},
rus_verbs:поехать{}, // поедем в такси!
rus_verbs:уехать{}, // он уехал в такси
rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей
rus_verbs:ОБЛАЧИТЬ{},
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло.
rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ)
rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ)
rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ)
rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ)
rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ)
rus_verbs:ЗАМАЯЧИТЬ{},
rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ)
rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ)
rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ)
rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ)
rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ)
rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ)
rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ)
rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ)
rus_verbs:ПоТЕРЯТЬ{},
rus_verbs:УТЕРЯТЬ{},
rus_verbs:РАСТЕРЯТЬ{},
rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.)
rus_verbs:СОМКНУТЬСЯ{},
rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ)
rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ)
rus_verbs:ВЫСТОЯТЬ{},
rus_verbs:ПОСТОЯТЬ{},
rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ)
rus_verbs:ВЗВЕШИВАТЬ{},
rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ)
прилагательное:быстрый{}, // Кисель быстр в приготовлении
rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень
rus_verbs:призывать{},
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ)
rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ)
rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ)
rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ)
rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ)
rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ)
rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ)
rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ)
rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ)
rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ)
rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ)
rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения
rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ)
rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ)
rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ)
rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ)
rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ)
rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ)
rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ)
rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ)
rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ)
rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ)
rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ)
rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА
rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ)
rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ)
rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ)
rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ)
rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ)
rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль
rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение
rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ)
инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан
глагол:проводить{ вид:несоверш },
деепричастие:проводя{},
rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала
rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл)
rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл)
rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл)
rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл)
rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл)
rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл)
rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл)
rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл)
rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл)
rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл)
rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл)
rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл)
rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл)
rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл)
прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В)
rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл)
rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл)
rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл)
rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл)
rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл)
rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл)
rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл)
rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл)
rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В)
rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В)
rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл)
rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В)
rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл)
rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл)
rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В)
rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл)
rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл)
rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В)
rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл)
rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В)
rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В)
rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В)
rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В)
rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл)
rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В)
частица:нет{}, // В этом нет сомнения.
частица:нету{}, // В этом нету сомнения.
rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем
rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов.
прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В)
rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В)
rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В)
rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В)
rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл)
rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В)
rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в)
rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В)
rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В)
rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В)
rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В)
rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В)
rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В)
rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В)
rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В)
rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В)
rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В)
rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В)
rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В)
rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В)
rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:РАСКЛАДЫВАТЬСЯ{},
rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В)
rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В)
rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В)
rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В)
rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл)
rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В)
rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В)
инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В)
глагол:НАПИСАТЬ{ aux stress="напис^ать" },
прилагательное:НАПИСАННЫЙ{},
rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В)
rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В)
rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В)
rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В)
rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В)
rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В)
rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл)
rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл)
rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В)
безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в)
rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В)
rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В)
rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В)
rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В)
rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В)
rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В)
rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В)
rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В)
rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В)
rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В)
rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В)
rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В)
rus_verbs:объявить{}, // В газете объявили о конкурсе.
rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В)
rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В)
rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в)
rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в)
rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в)
rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в)
инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В)
глагол:ПАРИТЬ{ aux stress="пар^ить"},
деепричастие:паря{ aux stress="пар^я" },
прилагательное:ПАРЯЩИЙ{},
прилагательное:ПАРИВШИЙ{},
rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В)
rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В)
rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в)
rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В)
rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В)
rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В)
rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В)
rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В)
rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В)
rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в)
rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в)
rus_verbs:принять{}, // Документ принят в следующей редакции (принять в)
rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в)
rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В)
rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в)
rus_verbs:звучать{}, // в доме звучала музыка (звучать в)
rus_verbs:колебаться{}, // колеблется в выборе (колебаться в)
rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в)
rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в)
rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в)
rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в)
rus_verbs:вычитывать{}, // вычитывать в книге
rus_verbs:гудеть{}, // У него в ушах гудит.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки.
rus_verbs:разойтись{}, // Они разошлись в темноте.
rus_verbs:прибежать{}, // Мальчик прибежал в слезах.
rus_verbs:биться{}, // Она билась в истерике.
rus_verbs:регистрироваться{}, // регистрироваться в системе
rus_verbs:считать{}, // я буду считать в уме
rus_verbs:трахаться{}, // трахаться в гамаке
rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке
rus_verbs:разрушать{}, // разрушать в дробилке
rus_verbs:засидеться{}, // засидеться в гостях
rus_verbs:засиживаться{}, // засиживаться в гостях
rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке)
rus_verbs:навестить{}, // навестить в доме престарелых
rus_verbs:запомнить{}, // запомнить в кэше
rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.)
rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка)
rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику.
rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.)
rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу
rus_verbs:оглядываться{}, // оглядываться в зеркале
rus_verbs:нарисовать{}, // нарисовать в тетрадке
rus_verbs:пробить{}, // пробить отверствие в стене
rus_verbs:повертеть{}, // повертеть в руке
rus_verbs:вертеть{}, // Я вертел в руках
rus_verbs:рваться{}, // Веревка рвется в месте надреза
rus_verbs:распространяться{}, // распространяться в среде наркоманов
rus_verbs:попрощаться{}, // попрощаться в здании морга
rus_verbs:соображать{}, // соображать в уме
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати
rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот)
rus_verbs:разобрать{}, // разобрать в гараже
rus_verbs:помереть{}, // помереть в пути
rus_verbs:различить{}, // различить в темноте
rus_verbs:рисовать{}, // рисовать в графическом редакторе
rus_verbs:проследить{}, // проследить в записях камер слежения
rus_verbs:совершаться{}, // Правосудие совершается в суде
rus_verbs:задремать{}, // задремать в кровати
rus_verbs:ругаться{}, // ругаться в комнате
rus_verbs:зазвучать{}, // зазвучать в радиоприемниках
rus_verbs:задохнуться{}, // задохнуться в воде
rus_verbs:порождать{}, // порождать в неокрепших умах
rus_verbs:отдыхать{}, // отдыхать в санатории
rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении
rus_verbs:образовать{}, // образовать в пробирке темную взвесь
rus_verbs:отмечать{}, // отмечать в списке
rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте
rus_verbs:плясать{}, // плясать в откружении незнакомых людей
rus_verbs:повысить{}, // повысить в звании
rus_verbs:поджидать{}, // поджидать в подъезде
rus_verbs:отказать{}, // отказать в пересмотре дела
rus_verbs:раствориться{}, // раствориться в бензине
rus_verbs:отражать{}, // отражать в стихах
rus_verbs:дремать{}, // дремать в гамаке
rus_verbs:применяться{}, // применяться в домашних условиях
rus_verbs:присниться{}, // присниться во сне
rus_verbs:трястись{}, // трястись в драндулете
rus_verbs:сохранять{}, // сохранять в неприкосновенности
rus_verbs:расстрелять{}, // расстрелять в ложбине
rus_verbs:рассчитать{}, // рассчитать в программе
rus_verbs:перебирать{}, // перебирать в руке
rus_verbs:разбиться{}, // разбиться в аварии
rus_verbs:поискать{}, // поискать в углу
rus_verbs:мучиться{}, // мучиться в тесной клетке
rus_verbs:замелькать{}, // замелькать в телевизоре
rus_verbs:грустить{}, // грустить в одиночестве
rus_verbs:крутить{}, // крутить в банке
rus_verbs:объявиться{}, // объявиться в городе
rus_verbs:подготовить{}, // подготовить в тайне
rus_verbs:различать{}, // различать в смеси
rus_verbs:обнаруживать{}, // обнаруживать в крови
rus_verbs:киснуть{}, // киснуть в захолустье
rus_verbs:оборваться{}, // оборваться в начале фразы
rus_verbs:запутаться{}, // запутаться в веревках
rus_verbs:общаться{}, // общаться в интимной обстановке
rus_verbs:сочинить{}, // сочинить в ресторане
rus_verbs:изобрести{}, // изобрести в домашней лаборатории
rus_verbs:прокомментировать{}, // прокомментировать в своем блоге
rus_verbs:давить{}, // давить в зародыше
rus_verbs:повториться{}, // повториться в новом обличье
rus_verbs:отставать{}, // отставать в общем зачете
rus_verbs:разработать{}, // разработать в лаборатории
rus_verbs:качать{}, // качать в кроватке
rus_verbs:заменить{}, // заменить в двигателе
rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере
rus_verbs:забегать{}, // забегать в спешке
rus_verbs:наделать{}, // наделать в решении ошибок
rus_verbs:исказиться{}, // исказиться в кривом зеркале
rus_verbs:тушить{}, // тушить в помещении пожар
rus_verbs:охранять{}, // охранять в здании входы
rus_verbs:приметить{}, // приметить в кустах
rus_verbs:скрыть{}, // скрыть в складках одежды
rus_verbs:удерживать{}, // удерживать в заложниках
rus_verbs:увеличиваться{}, // увеличиваться в размере
rus_verbs:красоваться{}, // красоваться в новом платье
rus_verbs:сохраниться{}, // сохраниться в тепле
rus_verbs:лечить{}, // лечить в стационаре
rus_verbs:смешаться{}, // смешаться в баке
rus_verbs:прокатиться{}, // прокатиться в троллейбусе
rus_verbs:договариваться{}, // договариваться в закрытом кабинете
rus_verbs:опубликовать{}, // опубликовать в официальном блоге
rus_verbs:охотиться{}, // охотиться в прериях
rus_verbs:отражаться{}, // отражаться в окне
rus_verbs:понизить{}, // понизить в должности
rus_verbs:обедать{}, // обедать в ресторане
rus_verbs:посидеть{}, // посидеть в тени
rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете
rus_verbs:свершиться{}, // свершиться в суде
rus_verbs:ночевать{}, // ночевать в гостинице
rus_verbs:темнеть{}, // темнеть в воде
rus_verbs:гибнуть{}, // гибнуть в застенках
rus_verbs:усиливаться{}, // усиливаться в направлении главного удара
rus_verbs:расплыться{}, // расплыться в улыбке
rus_verbs:превышать{}, // превышать в несколько раз
rus_verbs:проживать{}, // проживать в отдельной коморке
rus_verbs:голубеть{}, // голубеть в тепле
rus_verbs:исследовать{}, // исследовать в естественных условиях
rus_verbs:обитать{}, // обитать в лесу
rus_verbs:скучать{}, // скучать в одиночестве
rus_verbs:сталкиваться{}, // сталкиваться в воздухе
rus_verbs:таиться{}, // таиться в глубине
rus_verbs:спасать{}, // спасать в море
rus_verbs:заблудиться{}, // заблудиться в лесу
rus_verbs:создаться{}, // создаться в новом виде
rus_verbs:пошарить{}, // пошарить в кармане
rus_verbs:планировать{}, // планировать в программе
rus_verbs:отбить{}, // отбить в нижней части
rus_verbs:отрицать{}, // отрицать в суде свою вину
rus_verbs:основать{}, // основать в пустыне новый город
rus_verbs:двоить{}, // двоить в глазах
rus_verbs:устоять{}, // устоять в лодке
rus_verbs:унять{}, // унять в ногах дрожь
rus_verbs:отзываться{}, // отзываться в обзоре
rus_verbs:притормозить{}, // притормозить в траве
rus_verbs:читаться{}, // читаться в глазах
rus_verbs:житься{}, // житься в деревне
rus_verbs:заиграть{}, // заиграть в жилах
rus_verbs:шевелить{}, // шевелить в воде
rus_verbs:зазвенеть{}, // зазвенеть в ушах
rus_verbs:зависнуть{}, // зависнуть в библиотеке
rus_verbs:затаить{}, // затаить в душе обиду
rus_verbs:сознаться{}, // сознаться в совершении
rus_verbs:протекать{}, // протекать в легкой форме
rus_verbs:выясняться{}, // выясняться в ходе эксперимента
rus_verbs:скрестить{}, // скрестить в неволе
rus_verbs:наводить{}, // наводить в комнате порядок
rus_verbs:значиться{}, // значиться в документах
rus_verbs:заинтересовать{}, // заинтересовать в получении результатов
rus_verbs:познакомить{}, // познакомить в непринужденной обстановке
rus_verbs:рассеяться{}, // рассеяться в воздухе
rus_verbs:грохнуть{}, // грохнуть в подвале
rus_verbs:обвинять{}, // обвинять в вымогательстве
rus_verbs:столпиться{}, // столпиться в фойе
rus_verbs:порыться{}, // порыться в сумке
rus_verbs:ослабить{}, // ослабить в верхней части
rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки
rus_verbs:спастись{}, // спастись в хижине
rus_verbs:прерваться{}, // прерваться в середине фразы
rus_verbs:применять{}, // применять в повседневной работе
rus_verbs:строиться{}, // строиться в зоне отчуждения
rus_verbs:путешествовать{}, // путешествовать в самолете
rus_verbs:побеждать{}, // побеждать в честной битве
rus_verbs:погубить{}, // погубить в себе артиста
rus_verbs:рассматриваться{}, // рассматриваться в следующей главе
rus_verbs:продаваться{}, // продаваться в специализированном магазине
rus_verbs:разместиться{}, // разместиться в аудитории
rus_verbs:повидать{}, // повидать в жизни
rus_verbs:настигнуть{}, // настигнуть в пригородах
rus_verbs:сгрудиться{}, // сгрудиться в центре загона
rus_verbs:укрыться{}, // укрыться в доме
rus_verbs:расплакаться{}, // расплакаться в суде
rus_verbs:пролежать{}, // пролежать в канаве
rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде
rus_verbs:поскользнуться{}, // поскользнуться в коридоре
rus_verbs:таскать{}, // таскать в руках
rus_verbs:нападать{}, // нападать в вольере
rus_verbs:просматривать{}, // просматривать в браузере
rus_verbs:обдумать{}, // обдумать в дороге
rus_verbs:обвинить{}, // обвинить в измене
rus_verbs:останавливать{}, // останавливать в дверях
rus_verbs:теряться{}, // теряться в догадках
rus_verbs:погибать{}, // погибать в бою
rus_verbs:обозначать{}, // обозначать в списке
rus_verbs:запрещать{}, // запрещать в парке
rus_verbs:долететь{}, // долететь в вертолёте
rus_verbs:тесниться{}, // тесниться в каморке
rus_verbs:уменьшаться{}, // уменьшаться в размере
rus_verbs:издавать{}, // издавать в небольшом издательстве
rus_verbs:хоронить{}, // хоронить в море
rus_verbs:перемениться{}, // перемениться в лице
rus_verbs:установиться{}, // установиться в северных областях
rus_verbs:прикидывать{}, // прикидывать в уме
rus_verbs:затаиться{}, // затаиться в траве
rus_verbs:раздобыть{}, // раздобыть в аптеке
rus_verbs:перебросить{}, // перебросить в товарном составе
rus_verbs:погружаться{}, // погружаться в батискафе
rus_verbs:поживать{}, // поживать в одиночестве
rus_verbs:признаваться{}, // признаваться в любви
rus_verbs:захватывать{}, // захватывать в здании
rus_verbs:покачиваться{}, // покачиваться в лодке
rus_verbs:крутиться{}, // крутиться в колесе
rus_verbs:помещаться{}, // помещаться в ящике
rus_verbs:питаться{}, // питаться в столовой
rus_verbs:отдохнуть{}, // отдохнуть в пансионате
rus_verbs:кататься{}, // кататься в коляске
rus_verbs:поработать{}, // поработать в цеху
rus_verbs:подразумевать{}, // подразумевать в задании
rus_verbs:ограбить{}, // ограбить в подворотне
rus_verbs:преуспеть{}, // преуспеть в бизнесе
rus_verbs:заерзать{}, // заерзать в кресле
rus_verbs:разъяснить{}, // разъяснить в другой статье
rus_verbs:продвинуться{}, // продвинуться в изучении
rus_verbs:поколебаться{}, // поколебаться в начале
rus_verbs:засомневаться{}, // засомневаться в честности
rus_verbs:приникнуть{}, // приникнуть в уме
rus_verbs:скривить{}, // скривить в усмешке
rus_verbs:рассечь{}, // рассечь в центре опухоли
rus_verbs:перепутать{}, // перепутать в роддоме
rus_verbs:посмеяться{}, // посмеяться в перерыве
rus_verbs:отмечаться{}, // отмечаться в полицейском участке
rus_verbs:накопиться{}, // накопиться в отстойнике
rus_verbs:уносить{}, // уносить в руках
rus_verbs:навещать{}, // навещать в больнице
rus_verbs:остыть{}, // остыть в проточной воде
rus_verbs:запереться{}, // запереться в комнате
rus_verbs:обогнать{}, // обогнать в первом круге
rus_verbs:убеждаться{}, // убеждаться в неизбежности
rus_verbs:подбирать{}, // подбирать в магазине
rus_verbs:уничтожать{}, // уничтожать в полете
rus_verbs:путаться{}, // путаться в показаниях
rus_verbs:притаиться{}, // притаиться в темноте
rus_verbs:проплывать{}, // проплывать в лодке
rus_verbs:засесть{}, // засесть в окопе
rus_verbs:подцепить{}, // подцепить в баре
rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок
rus_verbs:оправдаться{}, // оправдаться в суде
rus_verbs:созреть{}, // созреть в естественных условиях
rus_verbs:раскрываться{}, // раскрываться в подходящих условиях
rus_verbs:ожидаться{}, // ожидаться в верхней части
rus_verbs:одеваться{}, // одеваться в дорогих бутиках
rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта
rus_verbs:грабить{}, // грабить в подворотне
rus_verbs:ужинать{}, // ужинать в ресторане
rus_verbs:гонять{}, // гонять в жилах
rus_verbs:уверить{}, // уверить в безопасности
rus_verbs:потеряться{}, // потеряться в лесу
rus_verbs:устанавливаться{}, // устанавливаться в комнате
rus_verbs:предоставлять{}, // предоставлять в суде
rus_verbs:протянуться{}, // протянуться в стене
rus_verbs:допрашивать{}, // допрашивать в бункере
rus_verbs:проработать{}, // проработать в кабинете
rus_verbs:сосредоточить{}, // сосредоточить в своих руках
rus_verbs:утвердить{}, // утвердить в должности
rus_verbs:сочинять{}, // сочинять в дороге
rus_verbs:померкнуть{}, // померкнуть в глазах
rus_verbs:показываться{}, // показываться в окошке
rus_verbs:похудеть{}, // похудеть в талии
rus_verbs:проделывать{}, // проделывать в стене
rus_verbs:прославиться{}, // прославиться в интернете
rus_verbs:сдохнуть{}, // сдохнуть в нищете
rus_verbs:раскинуться{}, // раскинуться в степи
rus_verbs:развить{}, // развить в себе способности
rus_verbs:уставать{}, // уставать в цеху
rus_verbs:укрепить{}, // укрепить в земле
rus_verbs:числиться{}, // числиться в списке
rus_verbs:образовывать{}, // образовывать в смеси
rus_verbs:екнуть{}, // екнуть в груди
rus_verbs:одобрять{}, // одобрять в своей речи
rus_verbs:запить{}, // запить в одиночестве
rus_verbs:забыться{}, // забыться в тяжелом сне
rus_verbs:чернеть{}, // чернеть в кислой среде
rus_verbs:размещаться{}, // размещаться в гараже
rus_verbs:соорудить{}, // соорудить в гараже
rus_verbs:развивать{}, // развивать в себе
rus_verbs:пастись{}, // пастись в пойме
rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы
rus_verbs:ослабнуть{}, // ослабнуть в сочленении
rus_verbs:таить{}, // таить в себе
инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке
rus_verbs:приостановиться{}, // приостановиться в конце
rus_verbs:топтаться{}, // топтаться в грязи
rus_verbs:громить{}, // громить в финале
rus_verbs:заменять{}, // заменять в основном составе
rus_verbs:подъезжать{}, // подъезжать в колясках
rus_verbs:вычислить{}, // вычислить в уме
rus_verbs:заказывать{}, // заказывать в магазине
rus_verbs:осуществить{}, // осуществить в реальных условиях
rus_verbs:обосноваться{}, // обосноваться в дупле
rus_verbs:пытать{}, // пытать в камере
rus_verbs:поменять{}, // поменять в магазине
rus_verbs:совершиться{}, // совершиться в суде
rus_verbs:пролетать{}, // пролетать в вертолете
rus_verbs:сбыться{}, // сбыться во сне
rus_verbs:разговориться{}, // разговориться в отделении
rus_verbs:преподнести{}, // преподнести в красивой упаковке
rus_verbs:напечатать{}, // напечатать в типографии
rus_verbs:прорвать{}, // прорвать в центре
rus_verbs:раскачиваться{}, // раскачиваться в кресле
rus_verbs:задерживаться{}, // задерживаться в дверях
rus_verbs:угощать{}, // угощать в кафе
rus_verbs:проступать{}, // проступать в глубине
rus_verbs:шарить{}, // шарить в математике
rus_verbs:увеличивать{}, // увеличивать в конце
rus_verbs:расцвести{}, // расцвести в оранжерее
rus_verbs:закипеть{}, // закипеть в баке
rus_verbs:подлететь{}, // подлететь в вертолете
rus_verbs:рыться{}, // рыться в куче
rus_verbs:пожить{}, // пожить в гостинице
rus_verbs:добираться{}, // добираться в попутном транспорте
rus_verbs:перекрыть{}, // перекрыть в коридоре
rus_verbs:продержаться{}, // продержаться в барокамере
rus_verbs:разыскивать{}, // разыскивать в толпе
rus_verbs:освобождать{}, // освобождать в зале суда
rus_verbs:подметить{}, // подметить в человеке
rus_verbs:передвигаться{}, // передвигаться в узкой юбке
rus_verbs:продумать{}, // продумать в уме
rus_verbs:извиваться{}, // извиваться в траве
rus_verbs:процитировать{}, // процитировать в статье
rus_verbs:прогуливаться{}, // прогуливаться в парке
rus_verbs:защемить{}, // защемить в двери
rus_verbs:увеличиться{}, // увеличиться в объеме
rus_verbs:проявиться{}, // проявиться в результатах
rus_verbs:заскользить{}, // заскользить в ботинках
rus_verbs:пересказать{}, // пересказать в своем выступлении
rus_verbs:протестовать{}, // протестовать в здании парламента
rus_verbs:указываться{}, // указываться в путеводителе
rus_verbs:копошиться{}, // копошиться в песке
rus_verbs:проигнорировать{}, // проигнорировать в своей работе
rus_verbs:купаться{}, // купаться в речке
rus_verbs:подсчитать{}, // подсчитать в уме
rus_verbs:разволноваться{}, // разволноваться в классе
rus_verbs:придумывать{}, // придумывать в своем воображении
rus_verbs:предусмотреть{}, // предусмотреть в программе
rus_verbs:завертеться{}, // завертеться в колесе
rus_verbs:зачерпнуть{}, // зачерпнуть в ручье
rus_verbs:очистить{}, // очистить в химической лаборатории
rus_verbs:прозвенеть{}, // прозвенеть в коридорах
rus_verbs:уменьшиться{}, // уменьшиться в размере
rus_verbs:колыхаться{}, // колыхаться в проточной воде
rus_verbs:ознакомиться{}, // ознакомиться в автобусе
rus_verbs:ржать{}, // ржать в аудитории
rus_verbs:раскинуть{}, // раскинуть в микрорайоне
rus_verbs:разлиться{}, // разлиться в воде
rus_verbs:сквозить{}, // сквозить в словах
rus_verbs:задушить{}, // задушить в объятиях
rus_verbs:осудить{}, // осудить в особом порядке
rus_verbs:разгромить{}, // разгромить в честном поединке
rus_verbs:подслушать{}, // подслушать в кулуарах
rus_verbs:проповедовать{}, // проповедовать в сельских районах
rus_verbs:озарить{}, // озарить во сне
rus_verbs:потирать{}, // потирать в предвкушении
rus_verbs:описываться{}, // описываться в статье
rus_verbs:качаться{}, // качаться в кроватке
rus_verbs:усилить{}, // усилить в центре
rus_verbs:прохаживаться{}, // прохаживаться в новом костюме
rus_verbs:полечить{}, // полечить в больничке
rus_verbs:сниматься{}, // сниматься в римейке
rus_verbs:сыскать{}, // сыскать в наших краях
rus_verbs:поприветствовать{}, // поприветствовать в коридоре
rus_verbs:подтвердиться{}, // подтвердиться в эксперименте
rus_verbs:плескаться{}, // плескаться в теплой водичке
rus_verbs:расширяться{}, // расширяться в первом сегменте
rus_verbs:мерещиться{}, // мерещиться в тумане
rus_verbs:сгущаться{}, // сгущаться в воздухе
rus_verbs:храпеть{}, // храпеть во сне
rus_verbs:подержать{}, // подержать в руках
rus_verbs:накинуться{}, // накинуться в подворотне
rus_verbs:планироваться{}, // планироваться в закрытом режиме
rus_verbs:пробудить{}, // пробудить в себе
rus_verbs:побриться{}, // побриться в ванной
rus_verbs:сгинуть{}, // сгинуть в пучине
rus_verbs:окрестить{}, // окрестить в церкви
инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления
rus_verbs:замкнуться{}, // замкнуться в себе
rus_verbs:прибавлять{}, // прибавлять в весе
rus_verbs:проплыть{}, // проплыть в лодке
rus_verbs:растворяться{}, // растворяться в тумане
rus_verbs:упрекать{}, // упрекать в небрежности
rus_verbs:затеряться{}, // затеряться в лабиринте
rus_verbs:перечитывать{}, // перечитывать в поезде
rus_verbs:перелететь{}, // перелететь в вертолете
rus_verbs:оживать{}, // оживать в теплой воде
rus_verbs:заглохнуть{}, // заглохнуть в полете
rus_verbs:кольнуть{}, // кольнуть в боку
rus_verbs:копаться{}, // копаться в куче
rus_verbs:развлекаться{}, // развлекаться в клубе
rus_verbs:отливать{}, // отливать в кустах
rus_verbs:зажить{}, // зажить в деревне
rus_verbs:одолжить{}, // одолжить в соседнем кабинете
rus_verbs:заклинать{}, // заклинать в своей речи
rus_verbs:различаться{}, // различаться в мелочах
rus_verbs:печататься{}, // печататься в типографии
rus_verbs:угадываться{}, // угадываться в контурах
rus_verbs:обрывать{}, // обрывать в начале
rus_verbs:поглаживать{}, // поглаживать в кармане
rus_verbs:подписывать{}, // подписывать в присутствии понятых
rus_verbs:добывать{}, // добывать в разломе
rus_verbs:скопиться{}, // скопиться в воротах
rus_verbs:повстречать{}, // повстречать в бане
rus_verbs:совпасть{}, // совпасть в упрощенном виде
rus_verbs:разрываться{}, // разрываться в точке спайки
rus_verbs:улавливать{}, // улавливать в датчике
rus_verbs:повстречаться{}, // повстречаться в лифте
rus_verbs:отразить{}, // отразить в отчете
rus_verbs:пояснять{}, // пояснять в примечаниях
rus_verbs:накормить{}, // накормить в столовке
rus_verbs:поужинать{}, // поужинать в ресторане
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить в молоке
rus_verbs:освоить{}, // освоить в работе
rus_verbs:зародиться{}, // зародиться в голове
rus_verbs:отплыть{}, // отплыть в старой лодке
rus_verbs:отстаивать{}, // отстаивать в суде
rus_verbs:осуждать{}, // осуждать в своем выступлении
rus_verbs:переговорить{}, // переговорить в перерыве
rus_verbs:разгораться{}, // разгораться в сердце
rus_verbs:укрыть{}, // укрыть в шалаше
rus_verbs:томиться{}, // томиться в застенках
rus_verbs:клубиться{}, // клубиться в воздухе
rus_verbs:сжигать{}, // сжигать в топке
rus_verbs:позавтракать{}, // позавтракать в кафешке
rus_verbs:функционировать{}, // функционировать в лабораторных условиях
rus_verbs:смять{}, // смять в руке
rus_verbs:разместить{}, // разместить в интернете
rus_verbs:пронести{}, // пронести в потайном кармане
rus_verbs:руководствоваться{}, // руководствоваться в работе
rus_verbs:нашарить{}, // нашарить в потемках
rus_verbs:закрутить{}, // закрутить в вихре
rus_verbs:просматриваться{}, // просматриваться в дальней перспективе
rus_verbs:распознать{}, // распознать в незнакомце
rus_verbs:повеситься{}, // повеситься в камере
rus_verbs:обшарить{}, // обшарить в поисках наркотиков
rus_verbs:наполняться{}, // наполняется в карьере
rus_verbs:засвистеть{}, // засвистеть в воздухе
rus_verbs:процветать{}, // процветать в мягком климате
rus_verbs:шуршать{}, // шуршать в простенке
rus_verbs:подхватывать{}, // подхватывать в полете
инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе
прилагательное:роившийся{}, прилагательное:роящийся{},
// деепричастие:роясь{ aux stress="ро^ясь" },
rus_verbs:преобладать{}, // преобладать в тексте
rus_verbs:посветлеть{}, // посветлеть в лице
rus_verbs:игнорировать{}, // игнорировать в рекомендациях
rus_verbs:обсуждаться{}, // обсуждаться в кулуарах
rus_verbs:отказывать{}, // отказывать в визе
rus_verbs:ощупывать{}, // ощупывать в кармане
rus_verbs:разливаться{}, // разливаться в цеху
rus_verbs:расписаться{}, // расписаться в получении
rus_verbs:учинить{}, // учинить в казарме
rus_verbs:плестись{}, // плестись в хвосте
rus_verbs:объявляться{}, // объявляться в группе
rus_verbs:повышаться{}, // повышаться в первой части
rus_verbs:напрягать{}, // напрягать в паху
rus_verbs:разрабатывать{}, // разрабатывать в студии
rus_verbs:хлопотать{}, // хлопотать в мэрии
rus_verbs:прерывать{}, // прерывать в самом начале
rus_verbs:каяться{}, // каяться в грехах
rus_verbs:освоиться{}, // освоиться в кабине
rus_verbs:подплыть{}, // подплыть в лодке
rus_verbs:замигать{}, // замигать в темноте
rus_verbs:оскорблять{}, // оскорблять в выступлении
rus_verbs:торжествовать{}, // торжествовать в душе
rus_verbs:поправлять{}, // поправлять в прологе
rus_verbs:угадывать{}, // угадывать в размытом изображении
rus_verbs:потоптаться{}, // потоптаться в прихожей
rus_verbs:переправиться{}, // переправиться в лодочке
rus_verbs:увериться{}, // увериться в невиновности
rus_verbs:забрезжить{}, // забрезжить в конце тоннеля
rus_verbs:утвердиться{}, // утвердиться во мнении
rus_verbs:завывать{}, // завывать в трубе
rus_verbs:заварить{}, // заварить в заварнике
rus_verbs:скомкать{}, // скомкать в руке
rus_verbs:перемещаться{}, // перемещаться в капсуле
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле
rus_verbs:праздновать{}, // праздновать в баре
rus_verbs:мигать{}, // мигать в темноте
rus_verbs:обучить{}, // обучить в мастерской
rus_verbs:орудовать{}, // орудовать в кладовке
rus_verbs:упорствовать{}, // упорствовать в заблуждении
rus_verbs:переминаться{}, // переминаться в прихожей
rus_verbs:подрасти{}, // подрасти в теплице
rus_verbs:предписываться{}, // предписываться в законе
rus_verbs:приписать{}, // приписать в конце
rus_verbs:задаваться{}, // задаваться в своей статье
rus_verbs:чинить{}, // чинить в домашних условиях
rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке
rus_verbs:пообедать{}, // пообедать в ресторанчике
rus_verbs:жрать{}, // жрать в чуланчике
rus_verbs:исполняться{}, // исполняться в антракте
rus_verbs:гнить{}, // гнить в тюрьме
rus_verbs:глодать{}, // глодать в конуре
rus_verbs:прослушать{}, // прослушать в дороге
rus_verbs:истратить{}, // истратить в кабаке
rus_verbs:стареть{}, // стареть в одиночестве
rus_verbs:разжечь{}, // разжечь в сердце
rus_verbs:совещаться{}, // совещаться в кабинете
rus_verbs:покачивать{}, // покачивать в кроватке
rus_verbs:отсидеть{}, // отсидеть в одиночке
rus_verbs:формировать{}, // формировать в умах
rus_verbs:захрапеть{}, // захрапеть во сне
rus_verbs:петься{}, // петься в хоре
rus_verbs:объехать{}, // объехать в автобусе
rus_verbs:поселить{}, // поселить в гостинице
rus_verbs:предаться{}, // предаться в книге
rus_verbs:заворочаться{}, // заворочаться во сне
rus_verbs:напрятать{}, // напрятать в карманах
rus_verbs:очухаться{}, // очухаться в незнакомом месте
rus_verbs:ограничивать{}, // ограничивать в движениях
rus_verbs:завертеть{}, // завертеть в руках
rus_verbs:печатать{}, // печатать в редакторе
rus_verbs:теплиться{}, // теплиться в сердце
rus_verbs:увязнуть{}, // увязнуть в зыбучем песке
rus_verbs:усмотреть{}, // усмотреть в обращении
rus_verbs:отыскаться{}, // отыскаться в запасах
rus_verbs:потушить{}, // потушить в горле огонь
rus_verbs:поубавиться{}, // поубавиться в размере
rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти
rus_verbs:смыть{}, // смыть в ванной
rus_verbs:заместить{}, // заместить в кресле
rus_verbs:угасать{}, // угасать в одиночестве
rus_verbs:сразить{}, // сразить в споре
rus_verbs:фигурировать{}, // фигурировать в бюллетене
rus_verbs:расплываться{}, // расплываться в глазах
rus_verbs:сосчитать{}, // сосчитать в уме
rus_verbs:сгуститься{}, // сгуститься в воздухе
rus_verbs:цитировать{}, // цитировать в своей статье
rus_verbs:помяться{}, // помяться в давке
rus_verbs:затрагивать{}, // затрагивать в процессе выполнения
rus_verbs:обтереть{}, // обтереть в гараже
rus_verbs:подстрелить{}, // подстрелить в пойме реки
rus_verbs:растереть{}, // растереть в руке
rus_verbs:подавлять{}, // подавлять в зародыше
rus_verbs:смешиваться{}, // смешиваться в чане
инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке
rus_verbs:сократиться{}, // сократиться в обхвате
rus_verbs:занервничать{}, // занервничать в кабинете
rus_verbs:соприкоснуться{}, // соприкоснуться в полете
rus_verbs:обозначить{}, // обозначить в объявлении
rus_verbs:обучаться{}, // обучаться в училище
rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы
rus_verbs:лелеять{}, // лелеять в сердце
rus_verbs:поддерживаться{}, // поддерживаться в суде
rus_verbs:уплыть{}, // уплыть в лодочке
rus_verbs:резвиться{}, // резвиться в саду
rus_verbs:поерзать{}, // поерзать в гамаке
rus_verbs:оплатить{}, // оплатить в ресторане
rus_verbs:похвастаться{}, // похвастаться в компании
rus_verbs:знакомиться{}, // знакомиться в классе
rus_verbs:приплыть{}, // приплыть в подводной лодке
rus_verbs:зажигать{}, // зажигать в классе
rus_verbs:смыслить{}, // смыслить в математике
rus_verbs:закопать{}, // закопать в огороде
rus_verbs:порхать{}, // порхать в зарослях
rus_verbs:потонуть{}, // потонуть в бумажках
rus_verbs:стирать{}, // стирать в холодной воде
rus_verbs:подстерегать{}, // подстерегать в придорожных кустах
rus_verbs:погулять{}, // погулять в парке
rus_verbs:предвкушать{}, // предвкушать в воображении
rus_verbs:ошеломить{}, // ошеломить в бою
rus_verbs:удостовериться{}, // удостовериться в безопасности
rus_verbs:огласить{}, // огласить в заключительной части
rus_verbs:разбогатеть{}, // разбогатеть в деревне
rus_verbs:грохотать{}, // грохотать в мастерской
rus_verbs:реализоваться{}, // реализоваться в должности
rus_verbs:красть{}, // красть в магазине
rus_verbs:нарваться{}, // нарваться в коридоре
rus_verbs:застывать{}, // застывать в неудобной позе
rus_verbs:толкаться{}, // толкаться в тесной комнате
rus_verbs:извлекать{}, // извлекать в аппарате
rus_verbs:обжигать{}, // обжигать в печи
rus_verbs:запечатлеть{}, // запечатлеть в кинохронике
rus_verbs:тренироваться{}, // тренироваться в зале
rus_verbs:поспорить{}, // поспорить в кабинете
rus_verbs:рыскать{}, // рыскать в лесу
rus_verbs:надрываться{}, // надрываться в шахте
rus_verbs:сняться{}, // сняться в фильме
rus_verbs:закружить{}, // закружить в танце
rus_verbs:затонуть{}, // затонуть в порту
rus_verbs:побыть{}, // побыть в гостях
rus_verbs:почистить{}, // почистить в носу
rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре
rus_verbs:подслушивать{}, // подслушивать в классе
rus_verbs:сгорать{}, // сгорать в танке
rus_verbs:разочароваться{}, // разочароваться в артисте
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках
rus_verbs:мять{}, // мять в руках
rus_verbs:подраться{}, // подраться в классе
rus_verbs:замести{}, // замести в прихожей
rus_verbs:откладываться{}, // откладываться в печени
rus_verbs:обозначаться{}, // обозначаться в перечне
rus_verbs:просиживать{}, // просиживать в интернете
rus_verbs:соприкасаться{}, // соприкасаться в точке
rus_verbs:начертить{}, // начертить в тетрадке
rus_verbs:уменьшать{}, // уменьшать в поперечнике
rus_verbs:тормозить{}, // тормозить в облаке
rus_verbs:затевать{}, // затевать в лаборатории
rus_verbs:затопить{}, // затопить в бухте
rus_verbs:задерживать{}, // задерживать в лифте
rus_verbs:прогуляться{}, // прогуляться в лесу
rus_verbs:прорубить{}, // прорубить во льду
rus_verbs:очищать{}, // очищать в кислоте
rus_verbs:полулежать{}, // полулежать в гамаке
rus_verbs:исправить{}, // исправить в задании
rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи
rus_verbs:замучить{}, // замучить в плену
rus_verbs:разрушаться{}, // разрушаться в верхней части
rus_verbs:ерзать{}, // ерзать в кресле
rus_verbs:покопаться{}, // покопаться в залежах
rus_verbs:раскаяться{}, // раскаяться в содеянном
rus_verbs:пробежаться{}, // пробежаться в парке
rus_verbs:полежать{}, // полежать в гамаке
rus_verbs:позаимствовать{}, // позаимствовать в книге
rus_verbs:снижать{}, // снижать в несколько раз
rus_verbs:черпать{}, // черпать в поэзии
rus_verbs:заверять{}, // заверять в своей искренности
rus_verbs:проглядеть{}, // проглядеть в сумерках
rus_verbs:припарковать{}, // припарковать во дворе
rus_verbs:сверлить{}, // сверлить в стене
rus_verbs:здороваться{}, // здороваться в аудитории
rus_verbs:рожать{}, // рожать в воде
rus_verbs:нацарапать{}, // нацарапать в тетрадке
rus_verbs:затопать{}, // затопать в коридоре
rus_verbs:прописать{}, // прописать в правилах
rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах
rus_verbs:снизить{}, // снизить в несколько раз
rus_verbs:заблуждаться{}, // заблуждаться в своей теории
rus_verbs:откопать{}, // откопать в отвалах
rus_verbs:смастерить{}, // смастерить в лаборатории
rus_verbs:замедлиться{}, // замедлиться в парафине
rus_verbs:избивать{}, // избивать в участке
rus_verbs:мыться{}, // мыться в бане
rus_verbs:сварить{}, // сварить в кастрюльке
rus_verbs:раскопать{}, // раскопать в снегу
rus_verbs:крепиться{}, // крепиться в держателе
rus_verbs:дробить{}, // дробить в мельнице
rus_verbs:попить{}, // попить в ресторанчике
rus_verbs:затронуть{}, // затронуть в душе
rus_verbs:лязгнуть{}, // лязгнуть в тишине
rus_verbs:заправлять{}, // заправлять в полете
rus_verbs:размножаться{}, // размножаться в неволе
rus_verbs:потопить{}, // потопить в Тихом Океане
rus_verbs:кушать{}, // кушать в столовой
rus_verbs:замолкать{}, // замолкать в замешательстве
rus_verbs:измеряться{}, // измеряться в дюймах
rus_verbs:сбываться{}, // сбываться в мечтах
rus_verbs:задернуть{}, // задернуть в комнате
rus_verbs:затихать{}, // затихать в темноте
rus_verbs:прослеживаться{}, // прослеживается в журнале
rus_verbs:прерываться{}, // прерывается в начале
rus_verbs:изображаться{}, // изображается в любых фильмах
rus_verbs:фиксировать{}, // фиксировать в данной точке
rus_verbs:ослаблять{}, // ослаблять в поясе
rus_verbs:зреть{}, // зреть в теплице
rus_verbs:зеленеть{}, // зеленеть в огороде
rus_verbs:критиковать{}, // критиковать в статье
rus_verbs:облететь{}, // облететь в частном вертолете
rus_verbs:разбросать{}, // разбросать в комнате
rus_verbs:заразиться{}, // заразиться в людном месте
rus_verbs:рассеять{}, // рассеять в бою
rus_verbs:печься{}, // печься в духовке
rus_verbs:поспать{}, // поспать в палатке
rus_verbs:заступиться{}, // заступиться в драке
rus_verbs:сплетаться{}, // сплетаться в середине
rus_verbs:поместиться{}, // поместиться в мешке
rus_verbs:спереть{}, // спереть в лавке
// инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде
// инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш },
rus_verbs:проваляться{}, // проваляться в постели
rus_verbs:лечиться{}, // лечиться в стационаре
rus_verbs:определиться{}, // определиться в честном бою
rus_verbs:обработать{}, // обработать в растворе
rus_verbs:пробивать{}, // пробивать в стене
rus_verbs:перемешаться{}, // перемешаться в чане
rus_verbs:чесать{}, // чесать в паху
rus_verbs:пролечь{}, // пролечь в пустынной местности
rus_verbs:скитаться{}, // скитаться в дальних странах
rus_verbs:затрудняться{}, // затрудняться в выборе
rus_verbs:отряхнуться{}, // отряхнуться в коридоре
rus_verbs:разыгрываться{}, // разыгрываться в лотерее
rus_verbs:помолиться{}, // помолиться в церкви
rus_verbs:предписывать{}, // предписывать в рецепте
rus_verbs:порваться{}, // порваться в слабом месте
rus_verbs:греться{}, // греться в здании
rus_verbs:опровергать{}, // опровергать в своем выступлении
rus_verbs:помянуть{}, // помянуть в своем выступлении
rus_verbs:допросить{}, // допросить в прокуратуре
rus_verbs:материализоваться{}, // материализоваться в соседнем здании
rus_verbs:рассеиваться{}, // рассеиваться в воздухе
rus_verbs:перевозить{}, // перевозить в вагоне
rus_verbs:отбывать{}, // отбывать в тюрьме
rus_verbs:попахивать{}, // попахивать в отхожем месте
rus_verbs:перечислять{}, // перечислять в заключении
rus_verbs:зарождаться{}, // зарождаться в дебрях
rus_verbs:предъявлять{}, // предъявлять в своем письме
rus_verbs:распространять{}, // распространять в сети
rus_verbs:пировать{}, // пировать в соседнем селе
rus_verbs:начертать{}, // начертать в летописи
rus_verbs:расцветать{}, // расцветать в подходящих условиях
rus_verbs:царствовать{}, // царствовать в южной части материка
rus_verbs:накопить{}, // накопить в буфере
rus_verbs:закрутиться{}, // закрутиться в рутине
rus_verbs:отработать{}, // отработать в забое
rus_verbs:обокрасть{}, // обокрасть в автобусе
rus_verbs:прокладывать{}, // прокладывать в снегу
rus_verbs:ковырять{}, // ковырять в носу
rus_verbs:копить{}, // копить в очереди
rus_verbs:полечь{}, // полечь в степях
rus_verbs:щебетать{}, // щебетать в кустиках
rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении
rus_verbs:посеять{}, // посеять в огороде
rus_verbs:разъезжать{}, // разъезжать в кабриолете
rus_verbs:замечаться{}, // замечаться в лесу
rus_verbs:просчитать{}, // просчитать в уме
rus_verbs:маяться{}, // маяться в командировке
rus_verbs:выхватывать{}, // выхватывать в тексте
rus_verbs:креститься{}, // креститься в деревенской часовне
rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты
rus_verbs:настигать{}, // настигать в огороде
rus_verbs:разгуливать{}, // разгуливать в роще
rus_verbs:насиловать{}, // насиловать в квартире
rus_verbs:побороть{}, // побороть в себе
rus_verbs:учитывать{}, // учитывать в расчетах
rus_verbs:искажать{}, // искажать в заметке
rus_verbs:пропить{}, // пропить в кабаке
rus_verbs:катать{}, // катать в лодочке
rus_verbs:припрятать{}, // припрятать в кармашке
rus_verbs:запаниковать{}, // запаниковать в бою
rus_verbs:рассыпать{}, // рассыпать в траве
rus_verbs:застревать{}, // застревать в ограде
rus_verbs:зажигаться{}, // зажигаться в сумерках
rus_verbs:жарить{}, // жарить в масле
rus_verbs:накапливаться{}, // накапливаться в костях
rus_verbs:распуститься{}, // распуститься в горшке
rus_verbs:проголосовать{}, // проголосовать в передвижном пункте
rus_verbs:странствовать{}, // странствовать в автомобиле
rus_verbs:осматриваться{}, // осматриваться в хоромах
rus_verbs:разворачивать{}, // разворачивать в спортзале
rus_verbs:заскучать{}, // заскучать в самолете
rus_verbs:напутать{}, // напутать в расчете
rus_verbs:перекусить{}, // перекусить в столовой
rus_verbs:спасаться{}, // спасаться в автономной капсуле
rus_verbs:посовещаться{}, // посовещаться в комнате
rus_verbs:доказываться{}, // доказываться в статье
rus_verbs:познаваться{}, // познаваться в беде
rus_verbs:загрустить{}, // загрустить в одиночестве
rus_verbs:оживить{}, // оживить в памяти
rus_verbs:переворачиваться{}, // переворачиваться в гробу
rus_verbs:заприметить{}, // заприметить в лесу
rus_verbs:отравиться{}, // отравиться в забегаловке
rus_verbs:продержать{}, // продержать в клетке
rus_verbs:выявить{}, // выявить в костях
rus_verbs:заседать{}, // заседать в совете
rus_verbs:расплачиваться{}, // расплачиваться в первой кассе
rus_verbs:проломить{}, // проломить в двери
rus_verbs:подражать{}, // подражать в мелочах
rus_verbs:подсчитывать{}, // подсчитывать в уме
rus_verbs:опережать{}, // опережать во всем
rus_verbs:сформироваться{}, // сформироваться в облаке
rus_verbs:укрепиться{}, // укрепиться в мнении
rus_verbs:отстоять{}, // отстоять в очереди
rus_verbs:развертываться{}, // развертываться в месте испытания
rus_verbs:замерзать{}, // замерзать во льду
rus_verbs:утопать{}, // утопать в снегу
rus_verbs:раскаиваться{}, // раскаиваться в содеянном
rus_verbs:организовывать{}, // организовывать в пионерлагере
rus_verbs:перевестись{}, // перевестись в наших краях
rus_verbs:смешивать{}, // смешивать в блендере
rus_verbs:ютиться{}, // ютиться в тесной каморке
rus_verbs:прождать{}, // прождать в аудитории
rus_verbs:подыскивать{}, // подыскивать в женском общежитии
rus_verbs:замочить{}, // замочить в сортире
rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке
rus_verbs:растирать{}, // растирать в ступке
rus_verbs:замедлять{}, // замедлять в парафине
rus_verbs:переспать{}, // переспать в палатке
rus_verbs:рассекать{}, // рассекать в кабриолете
rus_verbs:отыскивать{}, // отыскивать в залежах
rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении
rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке
rus_verbs:укрываться{}, // укрываться в землянке
rus_verbs:запечься{}, // запечься в золе
rus_verbs:догорать{}, // догорать в темноте
rus_verbs:застилать{}, // застилать в коридоре
rus_verbs:сыскаться{}, // сыскаться в деревне
rus_verbs:переделать{}, // переделать в мастерской
rus_verbs:разъяснять{}, // разъяснять в своей лекции
rus_verbs:селиться{}, // селиться в центре
rus_verbs:оплачивать{}, // оплачивать в магазине
rus_verbs:переворачивать{}, // переворачивать в закрытой банке
rus_verbs:упражняться{}, // упражняться в остроумии
rus_verbs:пометить{}, // пометить в списке
rus_verbs:припомниться{}, // припомниться в завещании
rus_verbs:приютить{}, // приютить в амбаре
rus_verbs:натерпеться{}, // натерпеться в темнице
rus_verbs:затеваться{}, // затеваться в клубе
rus_verbs:уплывать{}, // уплывать в лодке
rus_verbs:скиснуть{}, // скиснуть в бидоне
rus_verbs:заколоть{}, // заколоть в боку
rus_verbs:замерцать{}, // замерцать в темноте
rus_verbs:фиксироваться{}, // фиксироваться в протоколе
rus_verbs:запираться{}, // запираться в комнате
rus_verbs:съезжаться{}, // съезжаться в каретах
rus_verbs:толочься{}, // толочься в ступе
rus_verbs:потанцевать{}, // потанцевать в клубе
rus_verbs:побродить{}, // побродить в парке
rus_verbs:назревать{}, // назревать в коллективе
rus_verbs:дохнуть{}, // дохнуть в питомнике
rus_verbs:крестить{}, // крестить в деревенской церквушке
rus_verbs:рассчитаться{}, // рассчитаться в банке
rus_verbs:припарковаться{}, // припарковаться во дворе
rus_verbs:отхватить{}, // отхватить в магазинчике
rus_verbs:остывать{}, // остывать в холодильнике
rus_verbs:составляться{}, // составляться в атмосфере тайны
rus_verbs:переваривать{}, // переваривать в тишине
rus_verbs:хвастать{}, // хвастать в казино
rus_verbs:отрабатывать{}, // отрабатывать в теплице
rus_verbs:разлечься{}, // разлечься в кровати
rus_verbs:прокручивать{}, // прокручивать в голове
rus_verbs:очертить{}, // очертить в воздухе
rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей
rus_verbs:выявлять{}, // выявлять в боевых условиях
rus_verbs:караулить{}, // караулить в лифте
rus_verbs:расставлять{}, // расставлять в бойницах
rus_verbs:прокрутить{}, // прокрутить в голове
rus_verbs:пересказывать{}, // пересказывать в первой главе
rus_verbs:задавить{}, // задавить в зародыше
rus_verbs:хозяйничать{}, // хозяйничать в холодильнике
rus_verbs:хвалиться{}, // хвалиться в детском садике
rus_verbs:оперировать{}, // оперировать в полевом госпитале
rus_verbs:формулировать{}, // формулировать в следующей главе
rus_verbs:застигнуть{}, // застигнуть в неприглядном виде
rus_verbs:замурлыкать{}, // замурлыкать в тепле
rus_verbs:поддакивать{}, // поддакивать в споре
rus_verbs:прочертить{}, // прочертить в воздухе
rus_verbs:отменять{}, // отменять в городе коменданский час
rus_verbs:колдовать{}, // колдовать в лаборатории
rus_verbs:отвозить{}, // отвозить в машине
rus_verbs:трахать{}, // трахать в гамаке
rus_verbs:повозиться{}, // повозиться в мешке
rus_verbs:ремонтировать{}, // ремонтировать в центре
rus_verbs:робеть{}, // робеть в гостях
rus_verbs:перепробовать{}, // перепробовать в деле
инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии
глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш },
rus_verbs:покаяться{}, // покаяться в церкви
rus_verbs:попрыгать{}, // попрыгать в бассейне
rus_verbs:умалчивать{}, // умалчивать в своем докладе
rus_verbs:ковыряться{}, // ковыряться в старой технике
rus_verbs:расписывать{}, // расписывать в деталях
rus_verbs:вязнуть{}, // вязнуть в песке
rus_verbs:погрязнуть{}, // погрязнуть в скандалах
rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу
rus_verbs:зажимать{}, // зажимать в углу
rus_verbs:стискивать{}, // стискивать в ладонях
rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса
rus_verbs:израсходовать{}, // израсходовать в полете
rus_verbs:клокотать{}, // клокотать в жерле
rus_verbs:обвиняться{}, // обвиняться в растрате
rus_verbs:уединиться{}, // уединиться в кладовке
rus_verbs:подохнуть{}, // подохнуть в болоте
rus_verbs:кипятиться{}, // кипятиться в чайнике
rus_verbs:уродиться{}, // уродиться в лесу
rus_verbs:продолжиться{}, // продолжиться в баре
rus_verbs:расшифровать{}, // расшифровать в специальном устройстве
rus_verbs:посапывать{}, // посапывать в кровати
rus_verbs:скрючиться{}, // скрючиться в мешке
rus_verbs:лютовать{}, // лютовать в отдаленных селах
rus_verbs:расписать{}, // расписать в статье
rus_verbs:публиковаться{}, // публиковаться в научном журнале
rus_verbs:зарегистрировать{}, // зарегистрировать в комитете
rus_verbs:прожечь{}, // прожечь в листе
rus_verbs:переждать{}, // переждать в окопе
rus_verbs:публиковать{}, // публиковать в журнале
rus_verbs:морщить{}, // морщить в уголках глаз
rus_verbs:спиться{}, // спиться в одиночестве
rus_verbs:изведать{}, // изведать в гареме
rus_verbs:обмануться{}, // обмануться в ожиданиях
rus_verbs:сочетать{}, // сочетать в себе
rus_verbs:подрабатывать{}, // подрабатывать в магазине
rus_verbs:репетировать{}, // репетировать в студии
rus_verbs:рябить{}, // рябить в глазах
rus_verbs:намочить{}, // намочить в луже
rus_verbs:скатать{}, // скатать в руке
rus_verbs:одевать{}, // одевать в магазине
rus_verbs:испечь{}, // испечь в духовке
rus_verbs:сбрить{}, // сбрить в подмышках
rus_verbs:зажужжать{}, // зажужжать в ухе
rus_verbs:сберечь{}, // сберечь в тайном месте
rus_verbs:согреться{}, // согреться в хижине
инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле
глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш },
rus_verbs:переплыть{}, // переплыть в лодочке
rus_verbs:передохнуть{}, // передохнуть в тени
rus_verbs:отсвечивать{}, // отсвечивать в зеркалах
rus_verbs:переправляться{}, // переправляться в лодках
rus_verbs:накупить{}, // накупить в магазине
rus_verbs:проторчать{}, // проторчать в очереди
rus_verbs:проскальзывать{}, // проскальзывать в сообщениях
rus_verbs:застукать{}, // застукать в солярии
rus_verbs:наесть{}, // наесть в отпуске
rus_verbs:подвизаться{}, // подвизаться в новом деле
rus_verbs:вычистить{}, // вычистить в саду
rus_verbs:кормиться{}, // кормиться в лесу
rus_verbs:покурить{}, // покурить в саду
rus_verbs:понизиться{}, // понизиться в ранге
rus_verbs:зимовать{}, // зимовать в избушке
rus_verbs:проверяться{}, // проверяться в службе безопасности
rus_verbs:подпирать{}, // подпирать в первом забое
rus_verbs:кувыркаться{}, // кувыркаться в постели
rus_verbs:похрапывать{}, // похрапывать в постели
rus_verbs:завязнуть{}, // завязнуть в песке
rus_verbs:трактовать{}, // трактовать в исследовательской статье
rus_verbs:замедляться{}, // замедляться в тяжелой воде
rus_verbs:шастать{}, // шастать в здании
rus_verbs:заночевать{}, // заночевать в пути
rus_verbs:наметиться{}, // наметиться в исследованиях рака
rus_verbs:освежить{}, // освежить в памяти
rus_verbs:оспаривать{}, // оспаривать в суде
rus_verbs:умещаться{}, // умещаться в ячейке
rus_verbs:искупить{}, // искупить в бою
rus_verbs:отсиживаться{}, // отсиживаться в тылу
rus_verbs:мчать{}, // мчать в кабриолете
rus_verbs:обличать{}, // обличать в своем выступлении
rus_verbs:сгнить{}, // сгнить в тюряге
rus_verbs:опробовать{}, // опробовать в деле
rus_verbs:тренировать{}, // тренировать в зале
rus_verbs:прославить{}, // прославить в академии
rus_verbs:учитываться{}, // учитываться в дипломной работе
rus_verbs:повеселиться{}, // повеселиться в лагере
rus_verbs:поумнеть{}, // поумнеть в карцере
rus_verbs:перестрелять{}, // перестрелять в воздухе
rus_verbs:проведать{}, // проведать в больнице
rus_verbs:измучиться{}, // измучиться в деревне
rus_verbs:прощупать{}, // прощупать в глубине
rus_verbs:изготовлять{}, // изготовлять в сарае
rus_verbs:свирепствовать{}, // свирепствовать в популяции
rus_verbs:иссякать{}, // иссякать в источнике
rus_verbs:гнездиться{}, // гнездиться в дупле
rus_verbs:разогнаться{}, // разогнаться в спортивной машине
rus_verbs:опознавать{}, // опознавать в неизвестном
rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде
rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках
rus_verbs:редактировать{}, // редактировать в редакторе
rus_verbs:покупаться{}, // покупаться в магазине
rus_verbs:промышлять{}, // промышлять в роще
rus_verbs:растягиваться{}, // растягиваться в коридоре
rus_verbs:приобретаться{}, // приобретаться в антикварных лавках
инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде
глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш },
rus_verbs:запечатлеться{}, // запечатлеться в мозгу
rus_verbs:укрывать{}, // укрывать в подвале
rus_verbs:закрепиться{}, // закрепиться в первой башне
rus_verbs:освежать{}, // освежать в памяти
rus_verbs:громыхать{}, // громыхать в ванной
инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати
глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш },
rus_verbs:добываться{}, // добываться в шахтах
rus_verbs:растворить{}, // растворить в кислоте
rus_verbs:приплясывать{}, // приплясывать в гримерке
rus_verbs:доживать{}, // доживать в доме престарелых
rus_verbs:отпраздновать{}, // отпраздновать в ресторане
rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях
rus_verbs:помыть{}, // помыть в проточной воде
инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке
глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш },
прилагательное:увязавший{ вид:несоверш },
rus_verbs:наличествовать{}, // наличествовать в запаснике
rus_verbs:нащупывать{}, // нащупывать в кармане
rus_verbs:повествоваться{}, // повествоваться в рассказе
rus_verbs:отремонтировать{}, // отремонтировать в техцентре
rus_verbs:покалывать{}, // покалывать в правом боку
rus_verbs:сиживать{}, // сиживать в саду
rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях
rus_verbs:укрепляться{}, // укрепляться в мнении
rus_verbs:разниться{}, // разниться во взглядах
rus_verbs:сполоснуть{}, // сполоснуть в водичке
rus_verbs:скупать{}, // скупать в магазине
rus_verbs:почесывать{}, // почесывать в паху
rus_verbs:оформлять{}, // оформлять в конторе
rus_verbs:распускаться{}, // распускаться в садах
rus_verbs:зарябить{}, // зарябить в глазах
rus_verbs:загореть{}, // загореть в Испании
rus_verbs:очищаться{}, // очищаться в баке
rus_verbs:остудить{}, // остудить в холодной воде
rus_verbs:разбомбить{}, // разбомбить в горах
rus_verbs:издохнуть{}, // издохнуть в бедности
rus_verbs:проехаться{}, // проехаться в новой машине
rus_verbs:задействовать{}, // задействовать в анализе
rus_verbs:произрастать{}, // произрастать в степи
rus_verbs:разуться{}, // разуться в прихожей
rus_verbs:сооружать{}, // сооружать в огороде
rus_verbs:зачитывать{}, // зачитывать в суде
rus_verbs:состязаться{}, // состязаться в остроумии
rus_verbs:ополоснуть{}, // ополоснуть в молоке
rus_verbs:уместиться{}, // уместиться в кармане
rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом
rus_verbs:стираться{}, // стираться в стиральной машине
rus_verbs:искупаться{}, // искупаться в прохладной реке
rus_verbs:курировать{}, // курировать в правительстве
rus_verbs:закупить{}, // закупить в магазине
rus_verbs:плодиться{}, // плодиться в подходящих условиях
rus_verbs:горланить{}, // горланить в парке
rus_verbs:першить{}, // першить в горле
rus_verbs:пригрезиться{}, // пригрезиться во сне
rus_verbs:исправлять{}, // исправлять в тетрадке
rus_verbs:расслабляться{}, // расслабляться в гамаке
rus_verbs:скапливаться{}, // скапливаться в нижней части
rus_verbs:сплетничать{}, // сплетничают в комнате
rus_verbs:раздевать{}, // раздевать в кабинке
rus_verbs:окопаться{}, // окопаться в лесу
rus_verbs:загорать{}, // загорать в Испании
rus_verbs:подпевать{}, // подпевать в церковном хоре
rus_verbs:прожужжать{}, // прожужжать в динамике
rus_verbs:изучаться{}, // изучаться в дикой природе
rus_verbs:заклубиться{}, // заклубиться в воздухе
rus_verbs:подметать{}, // подметать в зале
rus_verbs:подозреваться{}, // подозреваться в совершении кражи
rus_verbs:обогащать{}, // обогащать в специальном аппарате
rus_verbs:издаться{}, // издаться в другом издательстве
rus_verbs:справить{}, // справить в кустах нужду
rus_verbs:помыться{}, // помыться в бане
rus_verbs:проскакивать{}, // проскакивать в словах
rus_verbs:попивать{}, // попивать в кафе чай
rus_verbs:оформляться{}, // оформляться в регистратуре
rus_verbs:чирикать{}, // чирикать в кустах
rus_verbs:скупить{}, // скупить в магазинах
rus_verbs:переночевать{}, // переночевать в гостинице
rus_verbs:концентрироваться{}, // концентрироваться в пробирке
rus_verbs:одичать{}, // одичать в лесу
rus_verbs:ковырнуть{}, // ковырнуть в ухе
rus_verbs:затеплиться{}, // затеплиться в глубине души
rus_verbs:разгрести{}, // разгрести в задачах залежи
rus_verbs:застопориться{}, // застопориться в начале списка
rus_verbs:перечисляться{}, // перечисляться во введении
rus_verbs:покататься{}, // покататься в парке аттракционов
rus_verbs:изловить{}, // изловить в поле
rus_verbs:прославлять{}, // прославлять в стихах
rus_verbs:промочить{}, // промочить в луже
rus_verbs:поделывать{}, // поделывать в отпуске
rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии
rus_verbs:подстеречь{}, // подстеречь в подъезде
rus_verbs:прикупить{}, // прикупить в магазине
rus_verbs:перемешивать{}, // перемешивать в кастрюле
rus_verbs:тискать{}, // тискать в углу
rus_verbs:купать{}, // купать в теплой водичке
rus_verbs:завариться{}, // завариться в стакане
rus_verbs:притулиться{}, // притулиться в углу
rus_verbs:пострелять{}, // пострелять в тире
rus_verbs:навесить{}, // навесить в больнице
инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере
глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш },
rus_verbs:нежиться{}, // нежится в постельке
rus_verbs:притомиться{}, // притомиться в школе
rus_verbs:раздвоиться{}, // раздвоиться в глазах
rus_verbs:навалить{}, // навалить в углу
rus_verbs:замуровать{}, // замуровать в склепе
rus_verbs:поселяться{}, // поселяться в кроне дуба
rus_verbs:потягиваться{}, // потягиваться в кровати
rus_verbs:укачать{}, // укачать в поезде
rus_verbs:отлеживаться{}, // отлеживаться в гамаке
rus_verbs:разменять{}, // разменять в кассе
rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде
rus_verbs:ржаветь{}, // ржаветь в воде
rus_verbs:уличить{}, // уличить в плагиате
rus_verbs:мутиться{}, // мутиться в голове
rus_verbs:растворять{}, // растворять в бензоле
rus_verbs:двоиться{}, // двоиться в глазах
rus_verbs:оговорить{}, // оговорить в договоре
rus_verbs:подделать{}, // подделать в документе
rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети
rus_verbs:растолстеть{}, // растолстеть в талии
rus_verbs:повоевать{}, // повоевать в городских условиях
rus_verbs:прибраться{}, // гнушаться прибраться в хлеву
rus_verbs:поглощаться{}, // поглощаться в металлической фольге
rus_verbs:ухать{}, // ухать в лесу
rus_verbs:подписываться{}, // подписываться в петиции
rus_verbs:покатать{}, // покатать в машинке
rus_verbs:излечиться{}, // излечиться в клинике
rus_verbs:трепыхаться{}, // трепыхаться в мешке
rus_verbs:кипятить{}, // кипятить в кастрюле
rus_verbs:понастроить{}, // понастроить в прибрежной зоне
rus_verbs:перебывать{}, // перебывать во всех европейских столицах
rus_verbs:оглашать{}, // оглашать в итоговой части
rus_verbs:преуспевать{}, // преуспевать в новом бизнесе
rus_verbs:консультироваться{}, // консультироваться в техподдержке
rus_verbs:накапливать{}, // накапливать в печени
rus_verbs:перемешать{}, // перемешать в контейнере
rus_verbs:наследить{}, // наследить в коридоре
rus_verbs:выявиться{}, // выявиться в результе
rus_verbs:забулькать{}, // забулькать в болоте
rus_verbs:отваривать{}, // отваривать в молоке
rus_verbs:запутываться{}, // запутываться в веревках
rus_verbs:нагреться{}, // нагреться в микроволновой печке
rus_verbs:рыбачить{}, // рыбачить в открытом море
rus_verbs:укорениться{}, // укорениться в сознании широких народных масс
rus_verbs:умывать{}, // умывать в тазике
rus_verbs:защекотать{}, // защекотать в носу
rus_verbs:заходиться{}, // заходиться в плаче
инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке
глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш },
деепричастие:искупав{}, деепричастие:искупая{},
rus_verbs:заморозить{}, // заморозить в холодильнике
rus_verbs:закреплять{}, // закреплять в металлическом держателе
rus_verbs:расхватать{}, // расхватать в магазине
rus_verbs:истязать{}, // истязать в тюремном подвале
rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере
rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле
rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете
rus_verbs:подогреть{}, // подогрей в микроволновке
rus_verbs:подогревать{},
rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку
rus_verbs:проделать{}, // проделать в стене дыру
инфинитив:жениться{ вид:соверш }, // жениться в Техасе
инфинитив:жениться{ вид:несоверш },
глагол:жениться{ вид:соверш },
глагол:жениться{ вид:несоверш },
деепричастие:женившись{},
деепричастие:женясь{},
прилагательное:женатый{},
прилагательное:женившийся{вид:соверш},
прилагательное:женящийся{},
rus_verbs:всхрапнуть{}, // всхрапнуть во сне
rus_verbs:всхрапывать{}, // всхрапывать во сне
rus_verbs:ворочаться{}, // Собака ворочается во сне
rus_verbs:воссоздаваться{}, // воссоздаваться в памяти
rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах
инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу
инфинитив:атаковать{ вид:соверш },
глагол:атаковать{ вид:несоверш },
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{},
прилагательное:атаковавший{},
прилагательное:атакующий{},
инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени
инфинитив:аккумулировать{вид:соверш},
глагол:аккумулировать{вид:несоверш},
глагол:аккумулировать{вид:соверш},
прилагательное:аккумулированный{},
прилагательное:аккумулирующий{},
//прилагательное:аккумулировавший{ вид:несоверш },
прилагательное:аккумулировавший{ вид:соверш },
rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию
rus_verbs:вырасти{}, // Он вырос в глазах коллег.
rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо.
rus_verbs:убить{}, // убить в себе зверя
инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани
инфинитив:абсорбироваться{ вид:несоверш },
глагол:абсорбироваться{ вид:соверш },
глагол:абсорбироваться{ вид:несоверш },
rus_verbs:поставить{}, // поставить в углу
rus_verbs:сжимать{}, // сжимать в кулаке
rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах
rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях
инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы
инфинитив:активизироваться{ вид:соверш },
глагол:активизироваться{ вид:несоверш },
глагол:активизироваться{ вид:соверш },
rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера
rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе
rus_verbs:базировать{}, // установка будет базирована в лесу
rus_verbs:барахтаться{}, // дети барахтались в воде
rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка
rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне
rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе
rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины
rus_verbs:блуждать{}, // Туристы блуждали в лесу
rus_verbs:брать{}, // Жена берет деньги в тумбочке
rus_verbs:бродить{}, // парочки бродили в парке
rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге
rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США
rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде
rus_verbs:вариться{}, // Курица варится в кастрюле
rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году
rus_verbs:прокручиваться{}, // Ключ прокручивается в замке
rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке
rus_verbs:храниться{}, // Настройки хранятся в текстовом файле
rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле
rus_verbs:витать{}, // Мальчик витает в облаках
rus_verbs:владычествовать{}, // Король владычествует в стране
rus_verbs:властвовать{}, // Олигархи властвовали в стране
rus_verbs:возбудить{}, // возбудить в сердце тоску
rus_verbs:возбуждать{}, // возбуждать в сердце тоску
rus_verbs:возвыситься{}, // возвыситься в глазах современников
rus_verbs:возжечь{}, // возжечь в храме огонь
rus_verbs:возжечься{}, // Огонь возжёгся в храме
rus_verbs:возжигать{}, // возжигать в храме огонь
rus_verbs:возжигаться{}, // Огонь возжигается в храме
rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь
rus_verbs:вознамериться{}, // вознамериться уйти в монастырь
rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове
rus_verbs:возникнуть{}, // Новые идейки возникли в голове
rus_verbs:возродиться{}, // возродиться в новом качестве
rus_verbs:возрождать{}, // возрождать в новом качестве
rus_verbs:возрождаться{}, // возрождаться в новом амплуа
rus_verbs:ворошить{}, // ворошить в камине кочергой золу
rus_verbs:воспевать{}, // Поэты воспевают героев в одах
rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами
rus_verbs:воспеть{}, // Поэты воспели в этой оде героев
rus_verbs:воспретить{}, // воспретить в помещении азартные игры
rus_verbs:восславить{}, // Поэты восславили в одах
rus_verbs:восславлять{}, // Поэты восславляют в одах
rus_verbs:восславляться{}, // Героя восславляются в одах
rus_verbs:воссоздать{}, // воссоздает в памяти образ человека
rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека
rus_verbs:воссоздаться{}, // воссоздаться в памяти
rus_verbs:вскипятить{}, // вскипятить в чайнике воду
rus_verbs:вскипятиться{}, // вскипятиться в чайнике
rus_verbs:встретить{}, // встретить в классе старого приятеля
rus_verbs:встретиться{}, // встретиться в классе
rus_verbs:встречать{}, // встречать в лесу голодного медведя
rus_verbs:встречаться{}, // встречаться в кафе
rus_verbs:выбривать{}, // выбривать что-то в подмышках
rus_verbs:выбрить{}, // выбрить что-то в паху
rus_verbs:вывалять{}, // вывалять кого-то в грязи
rus_verbs:вываляться{}, // вываляться в грязи
rus_verbs:вываривать{}, // вываривать в молоке
rus_verbs:вывариваться{}, // вывариваться в молоке
rus_verbs:выварить{}, // выварить в молоке
rus_verbs:вывариться{}, // вывариться в молоке
rus_verbs:выгрызать{}, // выгрызать в сыре отверствие
rus_verbs:выгрызть{}, // выгрызть в сыре отверстие
rus_verbs:выгуливать{}, // выгуливать в парке собаку
rus_verbs:выгулять{}, // выгулять в парке собаку
rus_verbs:выдолбить{}, // выдолбить в стволе углубление
rus_verbs:выжить{}, // выжить в пустыне
rus_verbs:Выискать{}, // Выискать в программе ошибку
rus_verbs:выискаться{}, // Ошибка выискалась в программе
rus_verbs:выискивать{}, // выискивать в программе ошибку
rus_verbs:выискиваться{}, // выискиваться в программе
rus_verbs:выкраивать{}, // выкраивать в расписании время
rus_verbs:выкраиваться{}, // выкраиваться в расписании
инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере
глагол:выкупаться{вид:соверш},
rus_verbs:выловить{}, // выловить в пруду
rus_verbs:вымачивать{}, // вымачивать в молоке
rus_verbs:вымачиваться{}, // вымачиваться в молоке
rus_verbs:вынюхивать{}, // вынюхивать в траве следы
rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду
rus_verbs:выпачкаться{}, // выпачкаться в грязи
rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков
rus_verbs:выращивать{}, // выращивать в теплице помидоры
rus_verbs:выращиваться{}, // выращиваться в теплице
rus_verbs:вырыть{}, // вырыть в земле глубокую яму
rus_verbs:высадить{}, // высадить в пустынной местности
rus_verbs:высадиться{}, // высадиться в пустынной местности
rus_verbs:высаживать{}, // высаживать в пустыне
rus_verbs:высверливать{}, // высверливать в доске отверствие
rus_verbs:высверливаться{}, // высверливаться в стене
rus_verbs:высверлить{}, // высверлить в стене отверствие
rus_verbs:высверлиться{}, // высверлиться в стене
rus_verbs:выскоблить{}, // выскоблить в столешнице канавку
rus_verbs:высматривать{}, // высматривать в темноте
rus_verbs:заметить{}, // заметить в помещении
rus_verbs:оказаться{}, // оказаться в первых рядах
rus_verbs:душить{}, // душить в объятиях
rus_verbs:оставаться{}, // оставаться в классе
rus_verbs:появиться{}, // впервые появиться в фильме
rus_verbs:лежать{}, // лежать в футляре
rus_verbs:раздаться{}, // раздаться в плечах
rus_verbs:ждать{}, // ждать в здании вокзала
rus_verbs:жить{}, // жить в трущобах
rus_verbs:постелить{}, // постелить в прихожей
rus_verbs:оказываться{}, // оказываться в неприятной ситуации
rus_verbs:держать{}, // держать в голове
rus_verbs:обнаружить{}, // обнаружить в себе способность
rus_verbs:начинать{}, // начинать в лаборатории
rus_verbs:рассказывать{}, // рассказывать в лицах
rus_verbs:ожидать{}, // ожидать в помещении
rus_verbs:продолжить{}, // продолжить в помещении
rus_verbs:состоять{}, // состоять в группе
rus_verbs:родиться{}, // родиться в рубашке
rus_verbs:искать{}, // искать в кармане
rus_verbs:иметься{}, // иметься в наличии
rus_verbs:говориться{}, // говориться в среде панков
rus_verbs:клясться{}, // клясться в верности
rus_verbs:узнавать{}, // узнавать в нем своего сына
rus_verbs:признаться{}, // признаться в ошибке
rus_verbs:сомневаться{}, // сомневаться в искренности
rus_verbs:толочь{}, // толочь в ступе
rus_verbs:понадобиться{}, // понадобиться в суде
rus_verbs:служить{}, // служить в пехоте
rus_verbs:потолочь{}, // потолочь в ступе
rus_verbs:появляться{}, // появляться в театре
rus_verbs:сжать{}, // сжать в объятиях
rus_verbs:действовать{}, // действовать в постановке
rus_verbs:селить{}, // селить в гостинице
rus_verbs:поймать{}, // поймать в лесу
rus_verbs:увидать{}, // увидать в толпе
rus_verbs:подождать{}, // подождать в кабинете
rus_verbs:прочесть{}, // прочесть в глазах
rus_verbs:тонуть{}, // тонуть в реке
rus_verbs:ощущать{}, // ощущать в животе
rus_verbs:ошибиться{}, // ошибиться в расчетах
rus_verbs:отметить{}, // отметить в списке
rus_verbs:показывать{}, // показывать в динамике
rus_verbs:скрыться{}, // скрыться в траве
rus_verbs:убедиться{}, // убедиться в корректности
rus_verbs:прозвучать{}, // прозвучать в наушниках
rus_verbs:разговаривать{}, // разговаривать в фойе
rus_verbs:издать{}, // издать в России
rus_verbs:прочитать{}, // прочитать в газете
rus_verbs:попробовать{}, // попробовать в деле
rus_verbs:замечать{}, // замечать в программе ошибку
rus_verbs:нести{}, // нести в руках
rus_verbs:пропасть{}, // пропасть в плену
rus_verbs:носить{}, // носить в кармане
rus_verbs:гореть{}, // гореть в аду
rus_verbs:поправить{}, // поправить в программе
rus_verbs:застыть{}, // застыть в неудобной позе
rus_verbs:получать{}, // получать в кассе
rus_verbs:потребоваться{}, // потребоваться в работе
rus_verbs:спрятать{}, // спрятать в шкафу
rus_verbs:учиться{}, // учиться в институте
rus_verbs:развернуться{}, // развернуться в коридоре
rus_verbs:подозревать{}, // подозревать в мошенничестве
rus_verbs:играть{}, // играть в команде
rus_verbs:сыграть{}, // сыграть в команде
rus_verbs:строить{}, // строить в деревне
rus_verbs:устроить{}, // устроить в доме вечеринку
rus_verbs:находить{}, // находить в лесу
rus_verbs:нуждаться{}, // нуждаться в деньгах
rus_verbs:испытать{}, // испытать в рабочей обстановке
rus_verbs:мелькнуть{}, // мелькнуть в прицеле
rus_verbs:очутиться{}, // очутиться в закрытом помещении
инфинитив:использовать{вид:соверш}, // использовать в работе
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
глагол:использовать{вид:соверш},
rus_verbs:лететь{}, // лететь в самолете
rus_verbs:смеяться{}, // смеяться в цирке
rus_verbs:ездить{}, // ездить в лимузине
rus_verbs:заснуть{}, // заснуть в неудобной позе
rus_verbs:застать{}, // застать в неформальной обстановке
rus_verbs:очнуться{}, // очнуться в незнакомой обстановке
rus_verbs:твориться{}, // Что творится в закрытой зоне
rus_verbs:разглядеть{}, // разглядеть в темноте
rus_verbs:изучать{}, // изучать в естественных условиях
rus_verbs:удержаться{}, // удержаться в седле
rus_verbs:побывать{}, // побывать в зоопарке
rus_verbs:уловить{}, // уловить в словах нотку отчаяния
rus_verbs:приобрести{}, // приобрести в лавке
rus_verbs:исчезать{}, // исчезать в тумане
rus_verbs:уверять{}, // уверять в своей невиновности
rus_verbs:продолжаться{}, // продолжаться в воздухе
rus_verbs:открывать{}, // открывать в городе новый стадион
rus_verbs:поддержать{}, // поддержать в парке порядок
rus_verbs:солить{}, // солить в бочке
rus_verbs:прожить{}, // прожить в деревне
rus_verbs:создавать{}, // создавать в театре
rus_verbs:обсуждать{}, // обсуждать в коллективе
rus_verbs:заказать{}, // заказать в магазине
rus_verbs:отыскать{}, // отыскать в гараже
rus_verbs:уснуть{}, // уснуть в кресле
rus_verbs:задержаться{}, // задержаться в театре
rus_verbs:подобрать{}, // подобрать в коллекции
rus_verbs:пробовать{}, // пробовать в работе
rus_verbs:курить{}, // курить в закрытом помещении
rus_verbs:устраивать{}, // устраивать в лесу засаду
rus_verbs:установить{}, // установить в багажнике
rus_verbs:запереть{}, // запереть в сарае
rus_verbs:содержать{}, // содержать в достатке
rus_verbs:синеть{}, // синеть в кислородной атмосфере
rus_verbs:слышаться{}, // слышаться в голосе
rus_verbs:закрыться{}, // закрыться в здании
rus_verbs:скрываться{}, // скрываться в квартире
rus_verbs:родить{}, // родить в больнице
rus_verbs:описать{}, // описать в заметках
rus_verbs:перехватить{}, // перехватить в коридоре
rus_verbs:менять{}, // менять в магазине
rus_verbs:скрывать{}, // скрывать в чужой квартире
rus_verbs:стиснуть{}, // стиснуть в стальных объятиях
rus_verbs:останавливаться{}, // останавливаться в гостинице
rus_verbs:мелькать{}, // мелькать в телевизоре
rus_verbs:присутствовать{}, // присутствовать в аудитории
rus_verbs:украсть{}, // украсть в магазине
rus_verbs:победить{}, // победить в войне
rus_verbs:расположиться{}, // расположиться в гостинице
rus_verbs:упомянуть{}, // упомянуть в своей книге
rus_verbs:плыть{}, // плыть в старой бочке
rus_verbs:нащупать{}, // нащупать в глубине
rus_verbs:проявляться{}, // проявляться в работе
rus_verbs:затихнуть{}, // затихнуть в норе
rus_verbs:построить{}, // построить в гараже
rus_verbs:поддерживать{}, // поддерживать в исправном состоянии
rus_verbs:заработать{}, // заработать в стартапе
rus_verbs:сломать{}, // сломать в суставе
rus_verbs:снимать{}, // снимать в гардеробе
rus_verbs:сохранить{}, // сохранить в коллекции
rus_verbs:располагаться{}, // располагаться в отдельном кабинете
rus_verbs:сражаться{}, // сражаться в честном бою
rus_verbs:спускаться{}, // спускаться в батискафе
rus_verbs:уничтожить{}, // уничтожить в схроне
rus_verbs:изучить{}, // изучить в естественных условиях
rus_verbs:рождаться{}, // рождаться в муках
rus_verbs:пребывать{}, // пребывать в прострации
rus_verbs:прилететь{}, // прилететь в аэробусе
rus_verbs:догнать{}, // догнать в переулке
rus_verbs:изобразить{}, // изобразить в танце
rus_verbs:проехать{}, // проехать в легковушке
rus_verbs:убедить{}, // убедить в разумности
rus_verbs:приготовить{}, // приготовить в духовке
rus_verbs:собирать{}, // собирать в лесу
rus_verbs:поплыть{}, // поплыть в катере
rus_verbs:доверять{}, // доверять в управлении
rus_verbs:разобраться{}, // разобраться в законах
rus_verbs:ловить{}, // ловить в озере
rus_verbs:проесть{}, // проесть в куске металла отверстие
rus_verbs:спрятаться{}, // спрятаться в подвале
rus_verbs:провозгласить{}, // провозгласить в речи
rus_verbs:изложить{}, // изложить в своём выступлении
rus_verbs:замяться{}, // замяться в коридоре
rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях
rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна
rus_verbs:хранить{}, // хранить в шкатулке
rus_verbs:шутить{}, // шутить в классе
глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях
инфинитив:рассыпаться{ aux stress="рассып^аться" },
rus_verbs:чертить{}, // чертить в тетрадке
rus_verbs:отразиться{}, // отразиться в аттестате
rus_verbs:греть{}, // греть в микроволновке
rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса
rus_verbs:рассуждать{}, // Автор рассуждает в своей статье
rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда
rus_verbs:окружать{}, // окружать в лесу
rus_verbs:сопровождать{}, // сопровождать в операции
rus_verbs:заканчиваться{}, // заканчиваться в дороге
rus_verbs:поселиться{}, // поселиться в загородном доме
rus_verbs:охватывать{}, // охватывать в хронологии
rus_verbs:запеть{}, // запеть в кино
инфинитив:провозить{вид:несоверш}, // провозить в багаже
глагол:провозить{вид:несоверш},
rus_verbs:мочить{}, // мочить в сортире
rus_verbs:перевернуться{}, // перевернуться в полёте
rus_verbs:улететь{}, // улететь в теплые края
rus_verbs:сдержать{}, // сдержать в руках
rus_verbs:преследовать{}, // преследовать в любой другой стране
rus_verbs:драться{}, // драться в баре
rus_verbs:просидеть{}, // просидеть в классе
rus_verbs:убираться{}, // убираться в квартире
rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения
rus_verbs:пугать{}, // пугать в прессе
rus_verbs:отреагировать{}, // отреагировать в прессе
rus_verbs:проверять{}, // проверять в аппарате
rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив
rus_verbs:летать{}, // летать в комфортабельном частном самолёте
rus_verbs:толпиться{}, // толпиться в фойе
rus_verbs:плавать{}, // плавать в специальном костюме
rus_verbs:пробыть{}, // пробыть в воде слишком долго
rus_verbs:прикинуть{}, // прикинуть в уме
rus_verbs:застрять{}, // застрять в лифте
rus_verbs:метаться{}, // метаться в кровате
rus_verbs:сжечь{}, // сжечь в печке
rus_verbs:расслабиться{}, // расслабиться в ванной
rus_verbs:услыхать{}, // услыхать в автобусе
rus_verbs:удержать{}, // удержать в вертикальном положении
rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы
rus_verbs:рассмотреть{}, // рассмотреть в капле воды
rus_verbs:просмотреть{}, // просмотреть в браузере
rus_verbs:учесть{}, // учесть в планах
rus_verbs:уезжать{}, // уезжать в чьей-то машине
rus_verbs:похоронить{}, // похоронить в мерзлой земле
rus_verbs:растянуться{}, // растянуться в расслабленной позе
rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке
rus_verbs:гулять{}, // гулять в парке
rus_verbs:утонуть{}, // утонуть в реке
rus_verbs:зажать{}, // зажать в медвежьих объятиях
rus_verbs:усомниться{}, // усомниться в объективности
rus_verbs:танцевать{}, // танцевать в спортзале
rus_verbs:проноситься{}, // проноситься в голове
rus_verbs:трудиться{}, // трудиться в кооперативе
глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке
инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный },
rus_verbs:сушить{}, // сушить в сушильном шкафу
rus_verbs:зашевелиться{}, // зашевелиться в траве
rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке
rus_verbs:промелькнуть{}, // промелькнуть в окне
rus_verbs:поучаствовать{}, // поучаствовать в обсуждении
rus_verbs:закрыть{}, // закрыть в комнате
rus_verbs:запирать{}, // запирать в комнате
rus_verbs:закрывать{}, // закрывать в доме
rus_verbs:заблокировать{}, // заблокировать в доме
rus_verbs:зацвести{}, // В садах зацвела сирень
rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу.
rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе
rus_verbs:стоять{}, // войска, стоявшие в Риме
rus_verbs:закалить{}, // ветераны, закаленные в боях
rus_verbs:выступать{}, // пришлось выступать в тюрьме.
rus_verbs:выступить{}, // пришлось выступить в тюрьме.
rus_verbs:закопошиться{}, // Мыши закопошились в траве
rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре
rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре
rus_verbs:закрываться{}, // закрываться в комнате
rus_verbs:провалиться{}, // провалиться в прокате
деепричастие:авторизируясь{ вид:несоверш },
глагол:авторизироваться{ вид:несоверш },
инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе
rus_verbs:существовать{}, // существовать в вакууме
деепричастие:находясь{},
прилагательное:находившийся{},
прилагательное:находящийся{},
глагол:находиться{ вид:несоверш },
инфинитив:находиться{ вид:несоверш }, // находиться в вакууме
rus_verbs:регистрировать{}, // регистрировать в инспекции
глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш },
инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции
rus_verbs:поковыряться{}, // поковыряться в носу
rus_verbs:оттаять{}, // оттаять в кипятке
rus_verbs:распинаться{}, // распинаться в проклятиях
rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России
rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе
rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения.
прилагательное:несчастный{}, // Он очень несчастен в семейной жизни.
rus_verbs:объясниться{}, // Он объяснился в любви.
прилагательное:нетвердый{}, // Он нетвёрд в истории.
rus_verbs:заниматься{}, // Он занимается в читальном зале.
rus_verbs:вращаться{}, // Он вращается в учёных кругах.
прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне.
rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры.
rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения.
rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев.
rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия
rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях.
rus_verbs:продолжать{}, // Продолжайте в том же духе.
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:болтать{}, // Не болтай в присутствии начальника!
rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника!
rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей
rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию
rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине.
rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах
rus_verbs:сходиться{}, // Все дороги сходятся в Москве
rus_verbs:убирать{}, // убирать в комнате
rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста
rus_verbs:уединяться{}, // уединяться в пустыне
rus_verbs:уживаться{}, // уживаться в одном коллективе
rus_verbs:укорять{}, // укорять друга в забывчивости
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы
rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем
rus_verbs:работать{}, // Я работаю в театре.
rus_verbs:признать{}, // Я признал в нём старого друга.
rus_verbs:преподавать{}, // Я преподаю в университете.
rus_verbs:понимать{}, // Я плохо понимаю в живописи.
rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах
rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа
rus_verbs:замереть{}, // вся толпа замерла в восхищении
rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле.
rus_verbs:идти{}, // Я иду в неопределённом направлении.
rus_verbs:заболеть{}, // Я заболел в дороге.
rus_verbs:ехать{}, // Я еду в автобусе
rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю.
rus_verbs:провести{}, // Юные годы он провёл в Италии.
rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти.
rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении.
rus_verbs:произойти{}, // Это произошло в одном городе в Японии.
rus_verbs:привидеться{}, // Это мне привиделось во сне.
rus_verbs:держаться{}, // Это дело держится в большом секрете.
rus_verbs:привиться{}, // Это выражение не привилось в русском языке.
rus_verbs:восстановиться{}, // Эти писатели восстановились в правах.
rus_verbs:быть{}, // Эта книга есть в любом книжном магазине.
прилагательное:популярный{}, // Эта идея очень популярна в массах.
rus_verbs:шуметь{}, // Шумит в голове.
rus_verbs:остаться{}, // Шляпа осталась в поезде.
rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях.
rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе.
rus_verbs:пересохнуть{}, // У меня в горле пересохло.
rus_verbs:щекотать{}, // У меня в горле щекочет.
rus_verbs:колоть{}, // У меня в боку колет.
прилагательное:свежий{}, // Событие ещё свежо в памяти.
rus_verbs:собрать{}, // Соберите всех учеников во дворе.
rus_verbs:белеть{}, // Снег белеет в горах.
rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте?
rus_verbs:таять{}, // Сахар тает в кипятке.
rus_verbs:жать{}, // Сапог жмёт в подъёме.
rus_verbs:возиться{}, // Ребята возятся в углу.
rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме.
rus_verbs:кружиться{}, // Они кружились в вальсе.
rus_verbs:выставлять{}, // Они выставляют его в смешном виде.
rus_verbs:бывать{}, // Она часто бывает в обществе.
rus_verbs:петь{}, // Она поёт в опере.
rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях.
rus_verbs:валяться{}, // Вещи валялись в беспорядке.
rus_verbs:пройти{}, // Весь день прошёл в беготне.
rus_verbs:продавать{}, // В этом магазине продают обувь.
rus_verbs:заключаться{}, // В этом заключается вся сущность.
rus_verbs:звенеть{}, // В ушах звенит.
rus_verbs:проступить{}, // В тумане проступили очертания корабля.
rus_verbs:бить{}, // В саду бьёт фонтан.
rus_verbs:проскользнуть{}, // В речи проскользнул упрёк.
rus_verbs:оставить{}, // Не оставь товарища в опасности.
rus_verbs:прогулять{}, // Мы прогуляли час в парке.
rus_verbs:перебить{}, // Мы перебили врагов в бою.
rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице.
rus_verbs:видеть{}, // Он многое видел в жизни.
// глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере.
rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах.
rus_verbs:кинуть{}, // Он кинул меня в беде.
rus_verbs:приходить{}, // Приходи в сентябре
rus_verbs:воскрешать{}, // воскрешать в памяти
rus_verbs:соединять{}, // соединять в себе
rus_verbs:разбираться{}, // умение разбираться в вещах
rus_verbs:делать{}, // В её комнате делали обыск.
rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина.
rus_verbs:начаться{}, // В деревне начались полевые работы.
rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль.
rus_verbs:вертеться{}, // В голове вертится вчерашний разговор.
rus_verbs:веять{}, // В воздухе веет прохладой.
rus_verbs:висеть{}, // В воздухе висит зной.
rus_verbs:носиться{}, // В воздухе носятся комары.
rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее
rus_verbs:воскресить{}, // воскресить в памяти
rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне
rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина
прилагательное:уверенный{ причастие }, // Она уверена в своих силах.
прилагательное:постоянный{}, // Она постоянна во вкусах.
прилагательное:сильный{}, // Он не силён в математике.
прилагательное:повинный{}, // Он не повинен в этом.
прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары
rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории
прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве.
rus_verbs:сесть{}, // Она села в тени
rus_verbs:заливаться{}, // в нашем парке заливаются соловьи
rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло
rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени
// rus_verbs:расти{}, // дерево, растущее в лесу
rus_verbs:происходить{}, // что происходит в поликлиннике
rus_verbs:спать{}, // кто спит в моей кровати
rus_verbs:мыть{}, // мыть машину в саду
ГЛ_ИНФ(царить), // В воздухе царило безмолвие
ГЛ_ИНФ(мести), // мести в прихожей пол
ГЛ_ИНФ(прятать), // прятать в яме
ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне.
// ГЛ_ИНФ(собраться), // собраться в порту
ГЛ_ИНФ(случиться), // что-то случилось в больнице
ГЛ_ИНФ(зажечься), // в небе зажглись звёзды
ГЛ_ИНФ(купить), // купи молока в магазине
прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
}
// Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } }
then return true
}
// С локативом:
// собраться в порту
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } }
then return true
}
#endregion Предложный
#region Винительный
// Для глаголов движения с выраженным направлением действия может присоединяться
// предложный паттерн с винительным падежом.
wordentry_set Гл_В_Вин =
{
rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок.
глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе.
глагол:ввергать{},
инфинитив:ввергнуть{},
инфинитив:ввергать{},
rus_verbs:двинуться{}, // Двинулись в путь и мы.
rus_verbs:сплавать{}, // Сплавать в Россию!
rus_verbs:уложиться{}, // Уложиться в воскресенье.
rus_verbs:спешить{}, // Спешите в Лондон
rus_verbs:кинуть{}, // Киньте в море.
rus_verbs:проситься{}, // Просилась в Никарагуа.
rus_verbs:притопать{}, // Притопал в Будапешт.
rus_verbs:скататься{}, // Скатался в Красноярск.
rus_verbs:соскользнуть{}, // Соскользнул в пике.
rus_verbs:соскальзывать{},
rus_verbs:играть{}, // Играл в дутье.
глагол:айда{}, // Айда в каморы.
rus_verbs:отзывать{}, // Отзывали в Москву...
rus_verbs:сообщаться{}, // Сообщается в Лондон.
rus_verbs:вдуматься{}, // Вдумайтесь в них.
rus_verbs:проехать{}, // Проехать в Лунево...
rus_verbs:спрыгивать{}, // Спрыгиваем в него.
rus_verbs:верить{}, // Верю в вас!
rus_verbs:прибыть{}, // Прибыл в Подмосковье.
rus_verbs:переходить{}, // Переходите в школу.
rus_verbs:доложить{}, // Доложили в Москву.
rus_verbs:подаваться{}, // Подаваться в Россию?
rus_verbs:спрыгнуть{}, // Спрыгнул в него.
rus_verbs:вывезти{}, // Вывезли в Китай.
rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю.
rus_verbs:пропихнуть{},
rus_verbs:транспортироваться{},
rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения
rus_verbs:дуть{},
rus_verbs:БОГАТЕТЬ{}, //
rus_verbs:РАЗБОГАТЕТЬ{}, //
rus_verbs:ВОЗРАСТАТЬ{}, //
rus_verbs:ВОЗРАСТИ{}, //
rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ)
rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ)
rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ)
rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ)
rus_verbs:ЗАМАНИВАТЬ{},
rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ)
rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ)
rus_verbs:ВРУБАТЬСЯ{},
rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ)
rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ)
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ)
rus_verbs:ЗАХВАТЫВАТЬ{},
rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ)
rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ)
rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ)
rus_verbs:ПОСТРОИТЬСЯ{},
rus_verbs:ВЫСТРОИТЬСЯ{},
rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ)
rus_verbs:ВЫПУСКАТЬ{},
rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ)
rus_verbs:ВЦЕПИТЬСЯ{},
rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ)
rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ)
rus_verbs:ОТСТУПАТЬ{},
rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ)
rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ)
rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ)
rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ)
rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ)
rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин)
rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ)
rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ)
rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ)
rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ)
rus_verbs:СЖИМАТЬСЯ{},
rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение
rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ)
rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ)
rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ)
rus_verbs:ПОКРАСИТЬ{}, //
rus_verbs:ПЕРЕКРАСИТЬ{}, //
rus_verbs:ОКРАСИТЬ{}, //
rus_verbs:ЗАКРАСИТЬ{}, //
rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ)
rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ)
rus_verbs:СТЯНУТЬ{}, //
rus_verbs:ЗАТЯНУТЬ{}, //
rus_verbs:ВТЯНУТЬ{}, //
rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ)
деепричастие:придя{}, // Немного придя в себя
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ)
rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ)
rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ)
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ)
rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ)
rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку
rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин)
rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин)
rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин)
rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин)
rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин)
rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин)
rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин)
rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В)
rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В)
rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В)
rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В)
rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин)
rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В)
rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В)
rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин)
rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В)
rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В)
rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В)
rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В)
rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В)
rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В)
rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В)
rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В)
rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В)
rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны.
rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В)
rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям.
rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В)
rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в)
rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В)
rus_verbs:валить{}, // валить все в одну кучу (валить в)
rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в)
rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в)
rus_verbs:клониться{}, // он клонился в сторону (клониться в)
rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в)
rus_verbs:запасть{}, // Эти слова запали мне в душу.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:ездить{}, // Каждый день грузовик ездит в город.
rus_verbs:претвориться{}, // Замысел претворился в жизнь.
rus_verbs:разойтись{}, // Они разошлись в разные стороны.
rus_verbs:выйти{}, // Охотник вышел в поле с ружьём.
rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом.
rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны
rus_verbs:переодеваться{}, // переодеваться в женское платье
rus_verbs:перерастать{}, // перерастать в массовые беспорядки
rus_verbs:завязываться{}, // завязываться в узел
rus_verbs:похватать{}, // похватать в руки
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:помещать{}, // помещать в изолятор
rus_verbs:зыркнуть{}, // зыркнуть в окошко
rus_verbs:закатать{}, // закатать в асфальт
rus_verbs:усаживаться{}, // усаживаться в кресло
rus_verbs:загонять{}, // загонять в сарай
rus_verbs:подбрасывать{}, // подбрасывать в воздух
rus_verbs:телеграфировать{}, // телеграфировать в центр
rus_verbs:вязать{}, // вязать в стопы
rus_verbs:подлить{}, // подлить в огонь
rus_verbs:заполучить{}, // заполучить в распоряжение
rus_verbs:подогнать{}, // подогнать в док
rus_verbs:ломиться{}, // ломиться в открытую дверь
rus_verbs:переправить{}, // переправить в деревню
rus_verbs:затягиваться{}, // затягиваться в трубу
rus_verbs:разлетаться{}, // разлетаться в стороны
rus_verbs:кланяться{}, // кланяться в ножки
rus_verbs:устремляться{}, // устремляться в открытое море
rus_verbs:переместиться{}, // переместиться в другую аудиторию
rus_verbs:ложить{}, // ложить в ящик
rus_verbs:отвозить{}, // отвозить в аэропорт
rus_verbs:напрашиваться{}, // напрашиваться в гости
rus_verbs:напроситься{}, // напроситься в гости
rus_verbs:нагрянуть{}, // нагрянуть в гости
rus_verbs:заворачивать{}, // заворачивать в фольгу
rus_verbs:заковать{}, // заковать в кандалы
rus_verbs:свезти{}, // свезти в сарай
rus_verbs:притащиться{}, // притащиться в дом
rus_verbs:завербовать{}, // завербовать в разведку
rus_verbs:рубиться{}, // рубиться в компьютерные игры
rus_verbs:тыкаться{}, // тыкаться в материнскую грудь
инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер
глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш },
деепричастие:ссыпав{}, деепричастие:ссыпая{},
rus_verbs:засасывать{}, // засасывать в себя
rus_verbs:скакнуть{}, // скакнуть в будущее
rus_verbs:подвозить{}, // подвозить в театр
rus_verbs:переиграть{}, // переиграть в покер
rus_verbs:мобилизовать{}, // мобилизовать в действующую армию
rus_verbs:залетать{}, // залетать в закрытое воздушное пространство
rus_verbs:подышать{}, // подышать в трубочку
rus_verbs:смотаться{}, // смотаться в институт
rus_verbs:рассовать{}, // рассовать в кармашки
rus_verbs:захаживать{}, // захаживать в дом
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард
деепричастие:сгоняя{},
rus_verbs:посылаться{}, // посылаться в порт
rus_verbs:отлить{}, // отлить в кастрюлю
rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение
rus_verbs:поплакать{}, // поплакать в платочек
rus_verbs:обуться{}, // обуться в сапоги
rus_verbs:закапать{}, // закапать в глаза
инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации
глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш },
деепричастие:свозив{}, деепричастие:свозя{},
rus_verbs:преобразовать{}, // преобразовать в линейное уравнение
rus_verbs:кутаться{}, // кутаться в плед
rus_verbs:смещаться{}, // смещаться в сторону
rus_verbs:зазывать{}, // зазывать в свой магазин
инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон
глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш },
деепричастие:трансформируясь{}, деепричастие:трансформировавшись{},
rus_verbs:погружать{}, // погружать в кипящее масло
rus_verbs:обыграть{}, // обыграть в теннис
rus_verbs:закутать{}, // закутать в одеяло
rus_verbs:изливаться{}, // изливаться в воду
rus_verbs:закатывать{}, // закатывать в асфальт
rus_verbs:мотнуться{}, // мотнуться в банк
rus_verbs:избираться{}, // избираться в сенат
rus_verbs:наниматься{}, // наниматься в услужение
rus_verbs:настучать{}, // настучать в органы
rus_verbs:запихивать{}, // запихивать в печку
rus_verbs:закапывать{}, // закапывать в нос
rus_verbs:засобираться{}, // засобираться в поход
rus_verbs:копировать{}, // копировать в другую папку
rus_verbs:замуровать{}, // замуровать в стену
rus_verbs:упечь{}, // упечь в тюрьму
rus_verbs:зрить{}, // зрить в корень
rus_verbs:стягиваться{}, // стягиваться в одну точку
rus_verbs:усаживать{}, // усаживать в тренажер
rus_verbs:протолкнуть{}, // протолкнуть в отверстие
rus_verbs:расшибиться{}, // расшибиться в лепешку
rus_verbs:приглашаться{}, // приглашаться в кабинет
rus_verbs:садить{}, // садить в телегу
rus_verbs:уткнуть{}, // уткнуть в подушку
rus_verbs:протечь{}, // протечь в подвал
rus_verbs:перегнать{}, // перегнать в другую страну
rus_verbs:переползти{}, // переползти в тень
rus_verbs:зарываться{}, // зарываться в грунт
rus_verbs:переодеть{}, // переодеть в сухую одежду
rus_verbs:припуститься{}, // припуститься в пляс
rus_verbs:лопотать{}, // лопотать в микрофон
rus_verbs:прогнусавить{}, // прогнусавить в микрофон
rus_verbs:мочиться{}, // мочиться в штаны
rus_verbs:загружать{}, // загружать в патронник
rus_verbs:радировать{}, // радировать в центр
rus_verbs:промотать{}, // промотать в конец
rus_verbs:помчать{}, // помчать в школу
rus_verbs:съезжать{}, // съезжать в кювет
rus_verbs:завозить{}, // завозить в магазин
rus_verbs:заявляться{}, // заявляться в школу
rus_verbs:наглядеться{}, // наглядеться в зеркало
rus_verbs:сворачиваться{}, // сворачиваться в клубочек
rus_verbs:устремлять{}, // устремлять взор в будущее
rus_verbs:забредать{}, // забредать в глухие уголки
rus_verbs:перемотать{}, // перемотать в самое начало диалога
rus_verbs:сморкаться{}, // сморкаться в носовой платочек
rus_verbs:перетекать{}, // перетекать в другой сосуд
rus_verbs:закачать{}, // закачать в шарик
rus_verbs:запрятать{}, // запрятать в сейф
rus_verbs:пинать{}, // пинать в живот
rus_verbs:затрубить{}, // затрубить в горн
rus_verbs:подглядывать{}, // подглядывать в замочную скважину
инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье
глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш },
деепричастие:подсыпав{}, деепричастие:подсыпая{},
rus_verbs:засовывать{}, // засовывать в пенал
rus_verbs:отрядить{}, // отрядить в командировку
rus_verbs:справлять{}, // справлять в кусты
rus_verbs:поторапливаться{}, // поторапливаться в самолет
rus_verbs:скопировать{}, // скопировать в кэш
rus_verbs:подливать{}, // подливать в огонь
rus_verbs:запрячь{}, // запрячь в повозку
rus_verbs:окраситься{}, // окраситься в пурпур
rus_verbs:уколоть{}, // уколоть в шею
rus_verbs:слететься{}, // слететься в гнездо
rus_verbs:резаться{}, // резаться в карты
rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров
инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш)
деепричастие:задвигая{},
rus_verbs:доставляться{}, // доставляться в ресторан
rus_verbs:поплевать{}, // поплевать в чашку
rus_verbs:попереться{}, // попереться в магазин
rus_verbs:хаживать{}, // хаживать в церковь
rus_verbs:преображаться{}, // преображаться в королеву
rus_verbs:организоваться{}, // организоваться в группу
rus_verbs:ужалить{}, // ужалить в руку
rus_verbs:протискиваться{}, // протискиваться в аудиторию
rus_verbs:препроводить{}, // препроводить в закуток
rus_verbs:разъезжаться{}, // разъезжаться в разные стороны
rus_verbs:пропыхтеть{}, // пропыхтеть в трубку
rus_verbs:уволочь{}, // уволочь в нору
rus_verbs:отодвигаться{}, // отодвигаться в сторону
rus_verbs:разливать{}, // разливать в стаканы
rus_verbs:сбегаться{}, // сбегаться в актовый зал
rus_verbs:наведаться{}, // наведаться в кладовку
rus_verbs:перекочевать{}, // перекочевать в горы
rus_verbs:прощебетать{}, // прощебетать в трубку
rus_verbs:перекладывать{}, // перекладывать в другой карман
rus_verbs:углубляться{}, // углубляться в теорию
rus_verbs:переименовать{}, // переименовать в город
rus_verbs:переметнуться{}, // переметнуться в лагерь противника
rus_verbs:разносить{}, // разносить в щепки
rus_verbs:осыпаться{}, // осыпаться в холода
rus_verbs:попроситься{}, // попроситься в туалет
rus_verbs:уязвить{}, // уязвить в сердце
rus_verbs:перетащить{}, // перетащить в дом
rus_verbs:закутаться{}, // закутаться в плед
// rus_verbs:упаковать{}, // упаковать в бумагу
инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость
rus_verbs:хихикать{}, // хихикать в кулачок
rus_verbs:объединить{}, // объединить в сеть
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию
деепричастие:слетав{},
rus_verbs:заползти{}, // заползти в норку
rus_verbs:перерасти{}, // перерасти в крупную аферу
rus_verbs:списать{}, // списать в утиль
rus_verbs:просачиваться{}, // просачиваться в бункер
rus_verbs:пускаться{}, // пускаться в погоню
rus_verbs:согревать{}, // согревать в мороз
rus_verbs:наливаться{}, // наливаться в емкость
rus_verbs:унестись{}, // унестись в небо
rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф
rus_verbs:сигануть{}, // сигануть в воду
rus_verbs:окунуть{}, // окунуть в ледяную воду
rus_verbs:просочиться{}, // просочиться в сапог
rus_verbs:соваться{}, // соваться в толпу
rus_verbs:протолкаться{}, // протолкаться в гардероб
rus_verbs:заложить{}, // заложить в ломбард
rus_verbs:перекатить{}, // перекатить в сарай
rus_verbs:поставлять{}, // поставлять в Китай
rus_verbs:залезать{}, // залезать в долги
rus_verbs:отлучаться{}, // отлучаться в туалет
rus_verbs:сбиваться{}, // сбиваться в кучу
rus_verbs:зарыть{}, // зарыть в землю
rus_verbs:засадить{}, // засадить в тело
rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь
rus_verbs:переставить{}, // переставить в шкаф
rus_verbs:отчалить{}, // отчалить в плавание
rus_verbs:набираться{}, // набираться в команду
rus_verbs:лягнуть{}, // лягнуть в живот
rus_verbs:притворить{}, // притворить в жизнь
rus_verbs:проковылять{}, // проковылять в гардероб
rus_verbs:прикатить{}, // прикатить в гараж
rus_verbs:залететь{}, // залететь в окно
rus_verbs:переделать{}, // переделать в мопед
rus_verbs:протащить{}, // протащить в совет
rus_verbs:обмакнуть{}, // обмакнуть в воду
rus_verbs:отклоняться{}, // отклоняться в сторону
rus_verbs:запихать{}, // запихать в пакет
rus_verbs:избирать{}, // избирать в совет
rus_verbs:загрузить{}, // загрузить в буфер
rus_verbs:уплывать{}, // уплывать в Париж
rus_verbs:забивать{}, // забивать в мерзлоту
rus_verbs:потыкать{}, // потыкать в безжизненную тушу
rus_verbs:съезжаться{}, // съезжаться в санаторий
rus_verbs:залепить{}, // залепить в рыло
rus_verbs:набиться{}, // набиться в карманы
rus_verbs:уползти{}, // уползти в нору
rus_verbs:упрятать{}, // упрятать в камеру
rus_verbs:переместить{}, // переместить в камеру анабиоза
rus_verbs:закрасться{}, // закрасться в душу
rus_verbs:сместиться{}, // сместиться в инфракрасную область
rus_verbs:запускать{}, // запускать в серию
rus_verbs:потрусить{}, // потрусить в чащобу
rus_verbs:забрасывать{}, // забрасывать в чистую воду
rus_verbs:переселить{}, // переселить в отдаленную деревню
rus_verbs:переезжать{}, // переезжать в новую квартиру
rus_verbs:приподнимать{}, // приподнимать в воздух
rus_verbs:добавиться{}, // добавиться в конец очереди
rus_verbs:убыть{}, // убыть в часть
rus_verbs:передвигать{}, // передвигать в соседнюю клетку
rus_verbs:добавляться{}, // добавляться в очередь
rus_verbs:дописать{}, // дописать в перечень
rus_verbs:записываться{}, // записываться в кружок
rus_verbs:продаться{}, // продаться в кредитное рабство
rus_verbs:переписывать{}, // переписывать в тетрадку
rus_verbs:заплыть{}, // заплыть в территориальные воды
инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок
глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" },
rus_verbs:отбирать{}, // отбирать в гвардию
rus_verbs:нашептывать{}, // нашептывать в микрофон
rus_verbs:ковылять{}, // ковылять в стойло
rus_verbs:прилетать{}, // прилетать в Париж
rus_verbs:пролиться{}, // пролиться в канализацию
rus_verbs:запищать{}, // запищать в микрофон
rus_verbs:подвезти{}, // подвезти в больницу
rus_verbs:припереться{}, // припереться в театр
rus_verbs:утечь{}, // утечь в сеть
rus_verbs:прорываться{}, // прорываться в буфет
rus_verbs:увозить{}, // увозить в ремонт
rus_verbs:съедать{}, // съедать в обед
rus_verbs:просунуться{}, // просунуться в дверь
rus_verbs:перенестись{}, // перенестись в прошлое
rus_verbs:завезти{}, // завезти в магазин
rus_verbs:проложить{}, // проложить в деревню
rus_verbs:объединяться{}, // объединяться в профсоюз
rus_verbs:развиться{}, // развиться в бабочку
rus_verbs:засеменить{}, // засеменить в кабинку
rus_verbs:скатываться{}, // скатываться в яму
rus_verbs:завозиться{}, // завозиться в магазин
rus_verbs:нанимать{}, // нанимать в рейс
rus_verbs:поспеть{}, // поспеть в класс
rus_verbs:кидаться{}, // кинаться в крайности
rus_verbs:поспевать{}, // поспевать в оперу
rus_verbs:обернуть{}, // обернуть в фольгу
rus_verbs:обратиться{}, // обратиться в прокуратуру
rus_verbs:истолковать{}, // истолковать в свою пользу
rus_verbs:таращиться{}, // таращиться в дисплей
rus_verbs:прыснуть{}, // прыснуть в кулачок
rus_verbs:загнуть{}, // загнуть в другую сторону
rus_verbs:раздать{}, // раздать в разные руки
rus_verbs:назначить{}, // назначить в приемную комиссию
rus_verbs:кидать{}, // кидать в кусты
rus_verbs:увлекать{}, // увлекать в лес
rus_verbs:переселиться{}, // переселиться в чужое тело
rus_verbs:присылать{}, // присылать в город
rus_verbs:уплыть{}, // уплыть в Европу
rus_verbs:запричитать{}, // запричитать в полный голос
rus_verbs:утащить{}, // утащить в логово
rus_verbs:завернуться{}, // завернуться в плед
rus_verbs:заносить{}, // заносить в блокнот
rus_verbs:пятиться{}, // пятиться в дом
rus_verbs:наведываться{}, // наведываться в больницу
rus_verbs:нырять{}, // нырять в прорубь
rus_verbs:зачастить{}, // зачастить в бар
rus_verbs:назначаться{}, // назначается в комиссию
rus_verbs:мотаться{}, // мотаться в областной центр
rus_verbs:разыграть{}, // разыграть в карты
rus_verbs:пропищать{}, // пропищать в микрофон
rus_verbs:пихнуть{}, // пихнуть в бок
rus_verbs:эмигрировать{}, // эмигрировать в Канаду
rus_verbs:подключить{}, // подключить в сеть
rus_verbs:упереть{}, // упереть в фундамент
rus_verbs:уплатить{}, // уплатить в кассу
rus_verbs:потащиться{}, // потащиться в медпункт
rus_verbs:пригнать{}, // пригнать в стойло
rus_verbs:оттеснить{}, // оттеснить в фойе
rus_verbs:стучаться{}, // стучаться в ворота
rus_verbs:перечислить{}, // перечислить в фонд
rus_verbs:сомкнуть{}, // сомкнуть в круг
rus_verbs:закачаться{}, // закачаться в резервуар
rus_verbs:кольнуть{}, // кольнуть в бок
rus_verbs:накрениться{}, // накрениться в сторону берега
rus_verbs:подвинуться{}, // подвинуться в другую сторону
rus_verbs:разнести{}, // разнести в клочья
rus_verbs:отливать{}, // отливать в форму
rus_verbs:подкинуть{}, // подкинуть в карман
rus_verbs:уводить{}, // уводить в кабинет
rus_verbs:ускакать{}, // ускакать в школу
rus_verbs:ударять{}, // ударять в барабаны
rus_verbs:даться{}, // даться в руки
rus_verbs:поцеловаться{}, // поцеловаться в губы
rus_verbs:посветить{}, // посветить в подвал
rus_verbs:тыкать{}, // тыкать в арбуз
rus_verbs:соединяться{}, // соединяться в кольцо
rus_verbs:растянуть{}, // растянуть в тонкую ниточку
rus_verbs:побросать{}, // побросать в пыль
rus_verbs:стукнуться{}, // стукнуться в закрытую дверь
rus_verbs:проигрывать{}, // проигрывать в теннис
rus_verbs:дунуть{}, // дунуть в трубочку
rus_verbs:улетать{}, // улетать в Париж
rus_verbs:переводиться{}, // переводиться в филиал
rus_verbs:окунуться{}, // окунуться в водоворот событий
rus_verbs:попрятаться{}, // попрятаться в норы
rus_verbs:перевезти{}, // перевезти в соседнюю палату
rus_verbs:топать{}, // топать в школу
rus_verbs:относить{}, // относить в помещение
rus_verbs:укладывать{}, // укладывать в стопку
rus_verbs:укатить{}, // укатил в турне
rus_verbs:убирать{}, // убирать в сумку
rus_verbs:помалкивать{}, // помалкивать в тряпочку
rus_verbs:ронять{}, // ронять в грязь
rus_verbs:глазеть{}, // глазеть в бинокль
rus_verbs:преобразиться{}, // преобразиться в другого человека
rus_verbs:запрыгнуть{}, // запрыгнуть в поезд
rus_verbs:сгодиться{}, // сгодиться в суп
rus_verbs:проползти{}, // проползти в нору
rus_verbs:забираться{}, // забираться в коляску
rus_verbs:сбежаться{}, // сбежались в класс
rus_verbs:закатиться{}, // закатиться в угол
rus_verbs:плевать{}, // плевать в душу
rus_verbs:поиграть{}, // поиграть в демократию
rus_verbs:кануть{}, // кануть в небытие
rus_verbs:опаздывать{}, // опаздывать в школу
rus_verbs:отползти{}, // отползти в сторону
rus_verbs:стекаться{}, // стекаться в отстойник
rus_verbs:запихнуть{}, // запихнуть в пакет
rus_verbs:вышвырнуть{}, // вышвырнуть в коридор
rus_verbs:связываться{}, // связываться в плотный узел
rus_verbs:затолкать{}, // затолкать в ухо
rus_verbs:скрутить{}, // скрутить в трубочку
rus_verbs:сворачивать{}, // сворачивать в трубочку
rus_verbs:сплестись{}, // сплестись в узел
rus_verbs:заскочить{}, // заскочить в кабинет
rus_verbs:проваливаться{}, // проваливаться в сон
rus_verbs:уверовать{}, // уверовать в свою безнаказанность
rus_verbs:переписать{}, // переписать в тетрадку
rus_verbs:переноситься{}, // переноситься в мир фантазий
rus_verbs:заводить{}, // заводить в помещение
rus_verbs:сунуться{}, // сунуться в аудиторию
rus_verbs:устраиваться{}, // устраиваться в автомастерскую
rus_verbs:пропускать{}, // пропускать в зал
инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино
глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш },
деепричастие:сбегая{}, деепричастие:сбегав{},
rus_verbs:прибегать{}, // прибегать в школу
rus_verbs:съездить{}, // съездить в лес
rus_verbs:захлопать{}, // захлопать в ладошки
rus_verbs:опрокинуться{}, // опрокинуться в грязь
инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан
глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш },
деепричастие:насыпая{}, деепричастие:насыпав{},
rus_verbs:употреблять{}, // употреблять в пищу
rus_verbs:приводиться{}, // приводиться в действие
rus_verbs:пристроить{}, // пристроить в надежные руки
rus_verbs:юркнуть{}, // юркнуть в нору
rus_verbs:объединиться{}, // объединиться в банду
rus_verbs:сажать{}, // сажать в одиночку
rus_verbs:соединить{}, // соединить в кольцо
rus_verbs:забрести{}, // забрести в кафешку
rus_verbs:свернуться{}, // свернуться в клубочек
rus_verbs:пересесть{}, // пересесть в другой автобус
rus_verbs:постучаться{}, // постучаться в дверцу
rus_verbs:соединять{}, // соединять в кольцо
rus_verbs:приволочь{}, // приволочь в коморку
rus_verbs:смахивать{}, // смахивать в ящик стола
rus_verbs:забежать{}, // забежать в помещение
rus_verbs:целиться{}, // целиться в беглеца
rus_verbs:прокрасться{}, // прокрасться в хранилище
rus_verbs:заковылять{}, // заковылять в травтамологию
rus_verbs:прискакать{}, // прискакать в стойло
rus_verbs:колотить{}, // колотить в дверь
rus_verbs:смотреться{}, // смотреться в зеркало
rus_verbs:подложить{}, // подложить в салон
rus_verbs:пущать{}, // пущать в королевские покои
rus_verbs:согнуть{}, // согнуть в дугу
rus_verbs:забарабанить{}, // забарабанить в дверь
rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы
rus_verbs:убраться{}, // убраться в специальную нишу
rus_verbs:насмотреться{}, // насмотреться в зеркало
rus_verbs:чмокнуть{}, // чмокнуть в щечку
rus_verbs:усмехаться{}, // усмехаться в бороду
rus_verbs:передвинуть{}, // передвинуть в конец очереди
rus_verbs:допускаться{}, // допускаться в опочивальню
rus_verbs:задвинуть{}, // задвинуть в дальний угол
rus_verbs:отправлять{}, // отправлять в центр
rus_verbs:сбрасывать{}, // сбрасывать в жерло
rus_verbs:расстреливать{}, // расстреливать в момент обнаружения
rus_verbs:заволочь{}, // заволочь в закуток
rus_verbs:пролить{}, // пролить в воду
rus_verbs:зарыться{}, // зарыться в сено
rus_verbs:переливаться{}, // переливаться в емкость
rus_verbs:затащить{}, // затащить в клуб
rus_verbs:перебежать{}, // перебежать в лагерь врагов
rus_verbs:одеть{}, // одеть в новое платье
инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу
деепричастие:задвигаясь{},
rus_verbs:клюнуть{}, // клюнуть в темечко
rus_verbs:наливать{}, // наливать в кружку
rus_verbs:пролезть{}, // пролезть в ушко
rus_verbs:откладывать{}, // откладывать в ящик
rus_verbs:протянуться{}, // протянуться в соседний дом
rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь
rus_verbs:устанавливать{}, // устанавливать в машину
rus_verbs:употребляться{}, // употребляться в пищу
rus_verbs:переключиться{}, // переключиться в реверсный режим
rus_verbs:пискнуть{}, // пискнуть в микрофон
rus_verbs:заявиться{}, // заявиться в класс
rus_verbs:налиться{}, // налиться в стакан
rus_verbs:заливать{}, // заливать в бак
rus_verbs:ставиться{}, // ставиться в очередь
инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны
деепричастие:писаясь{},
rus_verbs:целоваться{}, // целоваться в губы
rus_verbs:наносить{}, // наносить в область сердца
rus_verbs:посмеяться{}, // посмеяться в кулачок
rus_verbs:употребить{}, // употребить в пищу
rus_verbs:прорваться{}, // прорваться в столовую
rus_verbs:укладываться{}, // укладываться в ровные стопки
rus_verbs:пробиться{}, // пробиться в финал
rus_verbs:забить{}, // забить в землю
rus_verbs:переложить{}, // переложить в другой карман
rus_verbs:опускать{}, // опускать в свежевырытую могилу
rus_verbs:поторопиться{}, // поторопиться в школу
rus_verbs:сдвинуться{}, // сдвинуться в сторону
rus_verbs:капать{}, // капать в смесь
rus_verbs:погружаться{}, // погружаться во тьму
rus_verbs:направлять{}, // направлять в кабинку
rus_verbs:погрузить{}, // погрузить во тьму
rus_verbs:примчаться{}, // примчаться в школу
rus_verbs:упираться{}, // упираться в дверь
rus_verbs:удаляться{}, // удаляться в комнату совещаний
rus_verbs:ткнуться{}, // ткнуться в окошко
rus_verbs:убегать{}, // убегать в чащу
rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру
rus_verbs:наговорить{}, // наговорить в микрофон
rus_verbs:переносить{}, // переносить в дом
rus_verbs:прилечь{}, // прилечь в кроватку
rus_verbs:поворачивать{}, // поворачивать в обратную сторону
rus_verbs:проскочить{}, // проскочить в щель
rus_verbs:совать{}, // совать в духовку
rus_verbs:переодеться{}, // переодеться в чистую одежду
rus_verbs:порвать{}, // порвать в лоскуты
rus_verbs:завязать{}, // завязать в бараний рог
rus_verbs:съехать{}, // съехать в кювет
rus_verbs:литься{}, // литься в канистру
rus_verbs:уклониться{}, // уклониться в левую сторону
rus_verbs:смахнуть{}, // смахнуть в мусорное ведро
rus_verbs:спускать{}, // спускать в шахту
rus_verbs:плеснуть{}, // плеснуть в воду
rus_verbs:подуть{}, // подуть в угольки
rus_verbs:набирать{}, // набирать в команду
rus_verbs:хлопать{}, // хлопать в ладошки
rus_verbs:ранить{}, // ранить в самое сердце
rus_verbs:посматривать{}, // посматривать в иллюминатор
rus_verbs:превращать{}, // превращать воду в вино
rus_verbs:толкать{}, // толкать в пучину
rus_verbs:отбыть{}, // отбыть в расположение части
rus_verbs:сгрести{}, // сгрести в карман
rus_verbs:удрать{}, // удрать в тайгу
rus_verbs:пристроиться{}, // пристроиться в хорошую фирму
rus_verbs:сбиться{}, // сбиться в плотную группу
rus_verbs:заключать{}, // заключать в объятия
rus_verbs:отпускать{}, // отпускать в поход
rus_verbs:устремить{}, // устремить взгляд в будущее
rus_verbs:обронить{}, // обронить в траву
rus_verbs:сливаться{}, // сливаться в речку
rus_verbs:стекать{}, // стекать в канаву
rus_verbs:свалить{}, // свалить в кучу
rus_verbs:подтянуть{}, // подтянуть в кабину
rus_verbs:скатиться{}, // скатиться в канаву
rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь
rus_verbs:заторопиться{}, // заторопиться в буфет
rus_verbs:протиснуться{}, // протиснуться в центр толпы
rus_verbs:прятать{}, // прятать в укромненькое местечко
rus_verbs:пропеть{}, // пропеть в микрофон
rus_verbs:углубиться{}, // углубиться в джунгли
rus_verbs:сползти{}, // сползти в яму
rus_verbs:записывать{}, // записывать в память
rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР)
rus_verbs:колотиться{}, // колотиться в дверь
rus_verbs:просунуть{}, // просунуть в отверстие
rus_verbs:провожать{}, // провожать в армию
rus_verbs:катить{}, // катить в гараж
rus_verbs:поражать{}, // поражать в самое сердце
rus_verbs:отлететь{}, // отлететь в дальний угол
rus_verbs:закинуть{}, // закинуть в речку
rus_verbs:катиться{}, // катиться в пропасть
rus_verbs:забросить{}, // забросить в дальний угол
rus_verbs:отвезти{}, // отвезти в лагерь
rus_verbs:втопить{}, // втопить педаль в пол
rus_verbs:втапливать{}, // втапливать педать в пол
rus_verbs:утопить{}, // утопить кнопку в панель
rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США
rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?)
rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег
rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег
rus_verbs:поскакать{}, // поскакать в атаку
rus_verbs:прицелиться{}, // прицелиться в бегущего зайца
rus_verbs:прыгать{}, // прыгать в кровать
rus_verbs:приглашать{}, // приглашать в дом
rus_verbs:понестись{}, // понестись в ворота
rus_verbs:заехать{}, // заехать в гаражный бокс
rus_verbs:опускаться{}, // опускаться в бездну
rus_verbs:переехать{}, // переехать в коттедж
rus_verbs:поместить{}, // поместить в карантин
rus_verbs:ползти{}, // ползти в нору
rus_verbs:добавлять{}, // добавлять в корзину
rus_verbs:уткнуться{}, // уткнуться в подушку
rus_verbs:продавать{}, // продавать в рабство
rus_verbs:спрятаться{}, // Белка спрячется в дупло.
rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию
rus_verbs:воткнуть{}, // воткни вилку в розетку
rus_verbs:нести{}, // нести в больницу
rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку
rus_verbs:впаивать{}, // впаивать деталь в плату
rus_verbs:впаиваться{}, // деталь впаивается в плату
rus_verbs:впархивать{}, // впархивать в помещение
rus_verbs:впаять{}, // впаять деталь в плату
rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат
rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат
rus_verbs:вперивать{}, // вперивать взгляд в экран
rus_verbs:впериваться{}, // впериваться в экран
rus_verbs:вперить{}, // вперить взгляд в экран
rus_verbs:впериться{}, // впериться в экран
rus_verbs:вперять{}, // вперять взгляд в экран
rus_verbs:вперяться{}, // вперяться в экран
rus_verbs:впечатать{}, // впечатать текст в первую главу
rus_verbs:впечататься{}, // впечататься в стену
rus_verbs:впечатывать{}, // впечатывать текст в первую главу
rus_verbs:впечатываться{}, // впечатываться в стену
rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами
rus_verbs:впитаться{}, // Жидкость впиталась в ткань
rus_verbs:впитываться{}, // Жидкость впитывается в ткань
rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы
rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку
rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник
rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник
rus_verbs:вплавиться{}, // Провод вплавился в плату
rus_verbs:вплеснуть{}, // вплеснуть краситель в бак
rus_verbs:вплести{}, // вплести ленту в волосы
rus_verbs:вплестись{}, // вплестись в волосы
rus_verbs:вплетать{}, // вплетать ленты в волосы
rus_verbs:вплывать{}, // корабль вплывает в порт
rus_verbs:вплыть{}, // яхта вплыла в бухту
rus_verbs:вползать{}, // дракон вползает в пещеру
rus_verbs:вползти{}, // дракон вполз в свою пещеру
rus_verbs:впорхнуть{}, // бабочка впорхнула в окно
rus_verbs:впрессовать{}, // впрессовать деталь в плиту
rus_verbs:впрессоваться{}, // впрессоваться в плиту
rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту
rus_verbs:впрессовываться{}, // впрессовываться в плиту
rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон
rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон
rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр
rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр
rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания
rus_verbs:впрягать{}, // впрягать лошадь в телегу
rus_verbs:впрягаться{}, // впрягаться в работу
rus_verbs:впрячь{}, // впрячь лошадь в телегу
rus_verbs:впрячься{}, // впрячься в работу
rus_verbs:впускать{}, // впускать посетителей в музей
rus_verbs:впускаться{}, // впускаться в помещение
rus_verbs:впустить{}, // впустить посетителей в музей
rus_verbs:впутать{}, // впутать кого-то во что-то
rus_verbs:впутаться{}, // впутаться во что-то
rus_verbs:впутывать{}, // впутывать кого-то во что-то
rus_verbs:впутываться{}, // впутываться во что-то
rus_verbs:врабатываться{}, // врабатываться в режим
rus_verbs:вработаться{}, // вработаться в режим
rus_verbs:врастать{}, // врастать в кожу
rus_verbs:врасти{}, // врасти в кожу
инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь
инфинитив:врезать{ вид:соверш },
глагол:врезать{ вид:несоверш },
глагол:врезать{ вид:соверш },
деепричастие:врезая{},
деепричастие:врезав{},
прилагательное:врезанный{},
инфинитив:врезаться{ вид:несоверш }, // врезаться в стену
инфинитив:врезаться{ вид:соверш },
глагол:врезаться{ вид:несоверш },
деепричастие:врезаясь{},
деепричастие:врезавшись{},
rus_verbs:врубить{}, // врубить в нагрузку
rus_verbs:врываться{}, // врываться в здание
rus_verbs:закачивать{}, // Насос закачивает топливо в бак
rus_verbs:ввезти{}, // Предприятие ввезло товар в страну
rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу
rus_verbs:ввивать{}, // Женщина ввивает полоску в косу
rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу
rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко
rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко
rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека
rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека
rus_verbs:вламываться{}, // Полиция вламывается в квартиру
rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом
rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом
rus_verbs:вовлечься{}, // вовлечься в занятие спортом
rus_verbs:спуститься{}, // спуститься в подвал
rus_verbs:спускаться{}, // спускаться в подвал
rus_verbs:отправляться{}, // отправляться в дальнее плавание
инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство
инфинитив:эмитировать{ вид:несоверш },
глагол:эмитировать{ вид:соверш },
глагол:эмитировать{ вид:несоверш },
деепричастие:эмитируя{},
деепричастие:эмитировав{},
прилагательное:эмитировавший{ вид:несоверш },
// прилагательное:эмитировавший{ вид:соверш },
прилагательное:эмитирующий{},
прилагательное:эмитируемый{},
прилагательное:эмитированный{},
инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию
инфинитив:этапировать{вид:соверш},
глагол:этапировать{вид:несоверш},
глагол:этапировать{вид:соверш},
деепричастие:этапируя{},
прилагательное:этапируемый{},
прилагательное:этапированный{},
rus_verbs:этапироваться{}, // Преступники этапируются в колонию
rus_verbs:баллотироваться{}, // они баллотировались в жюри
rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну
rus_verbs:бросать{}, // Они бросали в фонтан медные монетки
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:бросить{}, // Он бросил в фонтан медную монетку
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя
rus_verbs:буксировать{}, // Буксир буксирует танкер в порт
rus_verbs:буксироваться{}, // Сухогруз буксируется в порт
rus_verbs:вбегать{}, // Курьер вбегает в дверь
rus_verbs:вбежать{}, // Курьер вбежал в дверь
rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол
rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту
rus_verbs:вбиваться{}, // Штырь вбивается в плиту
rus_verbs:вбирать{}, // Вата вбирает в себя влагу
rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь
rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру
rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру
rus_verbs:вбросить{}, // Судья вбросил мяч в игру
rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон
rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон
rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект
rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача
rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру
rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта
rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту
rus_verbs:ввариваться{}, // Арматура вваривается в плиту
rus_verbs:вварить{}, // Робот вварил арматурину в плиту
rus_verbs:влезть{}, // Предприятие ввезло товар в страну
rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру
rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон
rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон
rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон
rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача
rus_verbs:вверяться{}, // Пациент вверяется в руки врача
rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров
rus_verbs:ввиваться{}, // полоска ввивается в косу
rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево
rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево
rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену
rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену
rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров
rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров
// rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье
rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну
rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон
rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон
rus_verbs:ввязаться{}, // Разведрота ввязалась в бой
rus_verbs:ввязываться{}, // Передовые части ввязываются в бой
rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор
rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор
rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию
rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида
rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида
rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали
rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку
rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку
rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь
rus_verbs:вдвинуться{}, // деталь вдвинулась в печь
rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку
rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко
rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко
rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко
rus_verbs:вделать{}, // мастер вделал розетку в стену
rus_verbs:вделывать{}, // мастер вделывает выключатель в стену
rus_verbs:вделываться{}, // кронштейн вделывается в стену
rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко
rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко
rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век
rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов
rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог
rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие
rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку
rus_verbs:вернуться{}, // Дети вернулись в библиотеку
rus_verbs:вжаться{}, // Водитель вжался в кресло
rus_verbs:вживаться{}, // Актер вживается в новую роль
rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента
rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента
rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента
rus_verbs:вживляться{}, // Стимулятор вживляется в тело
rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло
rus_verbs:вжиться{}, // Актер вжился в свою новую роль
rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо
rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо
rus_verbs:взвинтиться{}, // Цены взвинтились в небо
rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо
rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо
rus_verbs:взвиться{}, // Шарики взвились в небо
rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух
rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо
rus_verbs:взмывать{}, // шарики взмывают в небо
rus_verbs:взмыть{}, // Шарики взмыли в небо
rus_verbs:вильнуть{}, // Машина вильнула в левую сторону
rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену
rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену
rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю
rus_verbs:вкапываться{}, // Свая вкапывается в землю
rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж
rus_verbs:вкатиться{}, // машина вкатилась в гараж
rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж
rus_verbs:вкатываться{}, // машина вкатывается в гараж
rus_verbs:вкачать{}, // Механики вкачали в бак много топлива
rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак
rus_verbs:вкачиваться{}, // Топливо вкачивается в бак
rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер
rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер
rus_verbs:вкидываться{}, // Груз вкидывается в контейнер
rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции
rus_verbs:вкладываться{}, // Инвестор вкладывается в акции
rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь
rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь
rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь
rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь
rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист
rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист
rus_verbs:вклиниваться{}, // Машина вклинивается в поток
rus_verbs:вклиниться{}, // машина вклинилась в поток
rus_verbs:включать{}, // Команда включает компьютер в сеть
rus_verbs:включаться{}, // Машина включается в глобальную сеть
rus_verbs:включить{}, // Команда включила компьютер в сеть
rus_verbs:включиться{}, // Компьютер включился в сеть
rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску
rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску
rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску
rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство
rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю
rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты
rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку
rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку
rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты
rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон
rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон
rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон
rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон
rus_verbs:влазить{}, // Разъем влазит в отверствие
rus_verbs:вламывать{}, // Полиция вламывается в квартиру
rus_verbs:влетать{}, // Самолет влетает в грозовой фронт
rus_verbs:влететь{}, // Самолет влетел в грозовой фронт
rus_verbs:вливать{}, // Механик вливает масло в картер
rus_verbs:вливаться{}, // Масло вливается в картер
rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия
rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности
rus_verbs:влить{}, // Механик влил свежее масло в картер
rus_verbs:влиться{}, // Свежее масло влилось в бак
rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства
rus_verbs:вложиться{}, // Инвесторы вложились в эти акции
rus_verbs:влюбиться{}, // Коля влюбился в Олю
rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков
rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов
rus_verbs:вляпаться{}, // Коля вляпался в неприятность
rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности
rus_verbs:вменить{}, // вменить в вину
rus_verbs:вменять{}, // вменять в обязанность
rus_verbs:вмерзать{}, // Колеса вмерзают в лед
rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед
rus_verbs:вмести{}, // вмести в дом
rus_verbs:вместить{}, // вместить в ёмкость
rus_verbs:вместиться{}, // Прибор не вместился в зонд
rus_verbs:вмешаться{}, // Начальник вмешался в конфликт
rus_verbs:вмешивать{}, // Не вмешивай меня в это дело
rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры
rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус
rus_verbs:вминать{}, // вминать в корпус
rus_verbs:вминаться{}, // кронштейн вминается в корпус
rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы
rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда
rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт
rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт
rus_verbs:вморозить{}, // Установка вморозила сваи в грунт
rus_verbs:вмуровать{}, // Сейф был вмурован в стену
rus_verbs:вмуровывать{}, // вмуровывать сейф в стену
rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену
rus_verbs:внедрить{}, // внедрить инновацию в производство
rus_verbs:внедриться{}, // Шпион внедрился в руководство
rus_verbs:внедрять{}, // внедрять инновации в производство
rus_verbs:внедряться{}, // Шпионы внедряются в руководство
rus_verbs:внести{}, // внести коробку в дом
rus_verbs:внестись{}, // внестись в список приглашенных гостей
rus_verbs:вникать{}, // Разработчик вникает в детали задачи
rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи
rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев
rus_verbs:вноситься{}, // вноситься в список главных персонажей
rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса
rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом
rus_verbs:вогнать{}, // вогнал человека в тоску
rus_verbs:водворить{}, // водворить преступника в тюрьму
rus_verbs:возвернуть{}, // возвернуть в родную стихию
rus_verbs:возвернуться{}, // возвернуться в родную стихию
rus_verbs:возвести{}, // возвести число в четную степень
rus_verbs:возводить{}, // возводить число в четную степень
rus_verbs:возводиться{}, // число возводится в четную степень
rus_verbs:возвратить{}, // возвратить коров в стойло
rus_verbs:возвратиться{}, // возвратиться в родной дом
rus_verbs:возвращать{}, // возвращать коров в стойло
rus_verbs:возвращаться{}, // возвращаться в родной дом
rus_verbs:войти{}, // войти в галерею славы
rus_verbs:вонзать{}, // Коля вонзает вилку в котлету
rus_verbs:вонзаться{}, // Вилка вонзается в котлету
rus_verbs:вонзить{}, // Коля вонзил вилку в котлету
rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету
rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность
rus_verbs:воплотиться{}, // Мечты воплотились в реальность
rus_verbs:воплощать{}, // Коля воплощает мечты в реальность
rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность
rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь
rus_verbs:воспарить{}, // Душа воспарила в небо
rus_verbs:воспарять{}, // Душа воспаряет в небо
rus_verbs:врыть{}, // врыть опору в землю
rus_verbs:врыться{}, // врыться в землю
rus_verbs:всадить{}, // всадить пулю в сердце
rus_verbs:всаживать{}, // всаживать нож в бок
rus_verbs:всасывать{}, // всасывать воду в себя
rus_verbs:всасываться{}, // всасываться в ёмкость
rus_verbs:вселить{}, // вселить надежду в кого-либо
rus_verbs:вселиться{}, // вселиться в пустующее здание
rus_verbs:вселять{}, // вселять надежду в кого-то
rus_verbs:вселяться{}, // вселяться в пустующее здание
rus_verbs:вскидывать{}, // вскидывать руку в небо
rus_verbs:вскинуть{}, // вскинуть руку в небо
rus_verbs:вслушаться{}, // вслушаться в звуки
rus_verbs:вслушиваться{}, // вслушиваться в шорох
rus_verbs:всматриваться{}, // всматриваться в темноту
rus_verbs:всмотреться{}, // всмотреться в темень
rus_verbs:всовывать{}, // всовывать палец в отверстие
rus_verbs:всовываться{}, // всовываться в форточку
rus_verbs:всосать{}, // всосать жидкость в себя
rus_verbs:всосаться{}, // всосаться в кожу
rus_verbs:вставить{}, // вставить ключ в замок
rus_verbs:вставлять{}, // вставлять ключ в замок
rus_verbs:встраивать{}, // встраивать черный ход в систему защиты
rus_verbs:встраиваться{}, // встраиваться в систему безопасности
rus_verbs:встревать{}, // встревать в разговор
rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности
rus_verbs:встроиться{}, // встроиться в систему безопасности
rus_verbs:встрять{}, // встрять в разговор
rus_verbs:вступать{}, // вступать в действующую армию
rus_verbs:вступить{}, // вступить в действующую армию
rus_verbs:всунуть{}, // всунуть палец в отверстие
rus_verbs:всунуться{}, // всунуться в форточку
инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер
инфинитив:всыпать{вид:несоверш},
глагол:всыпать{вид:соверш},
глагол:всыпать{вид:несоверш},
деепричастие:всыпав{},
деепричастие:всыпая{},
прилагательное:всыпавший{ вид:соверш },
// прилагательное:всыпавший{ вид:несоверш },
прилагательное:всыпанный{},
// прилагательное:всыпающий{},
инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер
// инфинитив:всыпаться{ вид:соверш},
// глагол:всыпаться{ вид:соверш},
глагол:всыпаться{ вид:несоверш},
// деепричастие:всыпавшись{},
деепричастие:всыпаясь{},
// прилагательное:всыпавшийся{ вид:соверш },
// прилагательное:всыпавшийся{ вид:несоверш },
// прилагательное:всыпающийся{},
rus_verbs:вталкивать{}, // вталкивать деталь в ячейку
rus_verbs:вталкиваться{}, // вталкиваться в ячейку
rus_verbs:втаптывать{}, // втаптывать в грязь
rus_verbs:втаптываться{}, // втаптываться в грязь
rus_verbs:втаскивать{}, // втаскивать мешок в комнату
rus_verbs:втаскиваться{}, // втаскиваться в комнату
rus_verbs:втащить{}, // втащить мешок в комнату
rus_verbs:втащиться{}, // втащиться в комнату
rus_verbs:втекать{}, // втекать в бутылку
rus_verbs:втемяшивать{}, // втемяшивать в голову
rus_verbs:втемяшиваться{}, // втемяшиваться в голову
rus_verbs:втемяшить{}, // втемяшить в голову
rus_verbs:втемяшиться{}, // втемяшиться в голову
rus_verbs:втереть{}, // втереть крем в кожу
rus_verbs:втереться{}, // втереться в кожу
rus_verbs:втесаться{}, // втесаться в группу
rus_verbs:втесывать{}, // втесывать в группу
rus_verbs:втесываться{}, // втесываться в группу
rus_verbs:втечь{}, // втечь в бак
rus_verbs:втирать{}, // втирать крем в кожу
rus_verbs:втираться{}, // втираться в кожу
rus_verbs:втискивать{}, // втискивать сумку в вагон
rus_verbs:втискиваться{}, // втискиваться в переполненный вагон
rus_verbs:втиснуть{}, // втиснуть сумку в вагон
rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро
rus_verbs:втолкать{}, // втолкать коляску в лифт
rus_verbs:втолкаться{}, // втолкаться в вагон метро
rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт
rus_verbs:втолкнуться{}, // втолкнуться в вагон метро
rus_verbs:втолочь{}, // втолочь в смесь
rus_verbs:втоптать{}, // втоптать цветы в землю
rus_verbs:вторгаться{}, // вторгаться в чужую зону
rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь
rus_verbs:втравить{}, // втравить кого-то в неприятности
rus_verbs:втравливать{}, // втравливать кого-то в неприятности
rus_verbs:втрамбовать{}, // втрамбовать камни в землю
rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю
rus_verbs:втрамбовываться{}, // втрамбовываться в землю
rus_verbs:втрескаться{}, // втрескаться в кого-то
rus_verbs:втрескиваться{}, // втрескиваться в кого-либо
rus_verbs:втыкать{}, // втыкать вилку в котлетку
rus_verbs:втыкаться{}, // втыкаться в розетку
rus_verbs:втюриваться{}, // втюриваться в кого-либо
rus_verbs:втюриться{}, // втюриться в кого-либо
rus_verbs:втягивать{}, // втягивать что-то в себя
rus_verbs:втягиваться{}, // втягиваться в себя
rus_verbs:втянуться{}, // втянуться в себя
rus_verbs:вцементировать{}, // вцементировать сваю в фундамент
rus_verbs:вчеканить{}, // вчеканить надпись в лист
rus_verbs:вчитаться{}, // вчитаться внимательнее в текст
rus_verbs:вчитываться{}, // вчитываться внимательнее в текст
rus_verbs:вчувствоваться{}, // вчувствоваться в роль
rus_verbs:вшагивать{}, // вшагивать в новую жизнь
rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь
rus_verbs:вшивать{}, // вшивать заплату в рубашку
rus_verbs:вшиваться{}, // вшиваться в ткань
rus_verbs:вшить{}, // вшить заплату в ткань
rus_verbs:въедаться{}, // въедаться в мякоть
rus_verbs:въезжать{}, // въезжать в гараж
rus_verbs:въехать{}, // въехать в гараж
rus_verbs:выиграть{}, // Коля выиграл в шахматы
rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы
rus_verbs:выкладывать{}, // выкладывать в общий доступ
rus_verbs:выкладываться{}, // выкладываться в общий доступ
rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет
rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет
rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет
rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет
rus_verbs:вылезать{}, // вылезать в открытое пространство
rus_verbs:вылезти{}, // вылезти в открытое пространство
rus_verbs:выливать{}, // выливать в бутылку
rus_verbs:выливаться{}, // выливаться в ёмкость
rus_verbs:вылить{}, // вылить отходы в канализацию
rus_verbs:вылиться{}, // Топливо вылилось в воду
rus_verbs:выложить{}, // выложить в общий доступ
rus_verbs:выпадать{}, // выпадать в осадок
rus_verbs:выпрыгивать{}, // выпрыгивать в окно
rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно
rus_verbs:выродиться{}, // выродиться в жалкое подобие
rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков
rus_verbs:высеваться{}, // высеваться в землю
rus_verbs:высеять{}, // высеять в землю
rus_verbs:выслать{}, // выслать в страну постоянного пребывания
rus_verbs:высморкаться{}, // высморкаться в платок
rus_verbs:высморкнуться{}, // высморкнуться в платок
rus_verbs:выстреливать{}, // выстреливать в цель
rus_verbs:выстреливаться{}, // выстреливаться в цель
rus_verbs:выстрелить{}, // выстрелить в цель
rus_verbs:вытекать{}, // вытекать в озеро
rus_verbs:вытечь{}, // вытечь в воду
rus_verbs:смотреть{}, // смотреть в будущее
rus_verbs:подняться{}, // подняться в лабораторию
rus_verbs:послать{}, // послать в магазин
rus_verbs:слать{}, // слать в неизвестность
rus_verbs:добавить{}, // добавить в суп
rus_verbs:пройти{}, // пройти в лабораторию
rus_verbs:положить{}, // положить в ящик
rus_verbs:прислать{}, // прислать в полицию
rus_verbs:упасть{}, // упасть в пропасть
инфинитив:писать{ aux stress="пис^ать" }, // писать в газету
инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки
глагол:писать{ aux stress="п^исать" },
глагол:писать{ aux stress="пис^ать" },
деепричастие:писая{},
прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки
прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету
rus_verbs:собираться{}, // собираться в поход
rus_verbs:звать{}, // звать в ресторан
rus_verbs:направиться{}, // направиться в ресторан
rus_verbs:отправиться{}, // отправиться в ресторан
rus_verbs:поставить{}, // поставить в угол
rus_verbs:целить{}, // целить в мишень
rus_verbs:попасть{}, // попасть в переплет
rus_verbs:ударить{}, // ударить в больное место
rus_verbs:закричать{}, // закричать в микрофон
rus_verbs:опустить{}, // опустить в воду
rus_verbs:принести{}, // принести в дом бездомного щенка
rus_verbs:отдать{}, // отдать в хорошие руки
rus_verbs:ходить{}, // ходить в школу
rus_verbs:уставиться{}, // уставиться в экран
rus_verbs:приходить{}, // приходить в бешенство
rus_verbs:махнуть{}, // махнуть в Италию
rus_verbs:сунуть{}, // сунуть в замочную скважину
rus_verbs:явиться{}, // явиться в расположение части
rus_verbs:уехать{}, // уехать в город
rus_verbs:целовать{}, // целовать в лобик
rus_verbs:повести{}, // повести в бой
rus_verbs:опуститься{}, // опуститься в кресло
rus_verbs:передать{}, // передать в архив
rus_verbs:побежать{}, // побежать в школу
rus_verbs:стечь{}, // стечь в воду
rus_verbs:уходить{}, // уходить добровольцем в армию
rus_verbs:привести{}, // привести в дом
rus_verbs:шагнуть{}, // шагнуть в неизвестность
rus_verbs:собраться{}, // собраться в поход
rus_verbs:заглянуть{}, // заглянуть в основу
rus_verbs:поспешить{}, // поспешить в церковь
rus_verbs:поцеловать{}, // поцеловать в лоб
rus_verbs:перейти{}, // перейти в высшую лигу
rus_verbs:поверить{}, // поверить в искренность
rus_verbs:глянуть{}, // глянуть в оглавление
rus_verbs:зайти{}, // зайти в кафетерий
rus_verbs:подобрать{}, // подобрать в лесу
rus_verbs:проходить{}, // проходить в помещение
rus_verbs:глядеть{}, // глядеть в глаза
rus_verbs:пригласить{}, // пригласить в театр
rus_verbs:позвать{}, // позвать в класс
rus_verbs:усесться{}, // усесться в кресло
rus_verbs:поступить{}, // поступить в институт
rus_verbs:лечь{}, // лечь в постель
rus_verbs:поклониться{}, // поклониться в пояс
rus_verbs:потянуться{}, // потянуться в лес
rus_verbs:колоть{}, // колоть в ягодицу
rus_verbs:присесть{}, // присесть в кресло
rus_verbs:оглядеться{}, // оглядеться в зеркало
rus_verbs:поглядеть{}, // поглядеть в зеркало
rus_verbs:превратиться{}, // превратиться в лягушку
rus_verbs:принимать{}, // принимать во внимание
rus_verbs:звонить{}, // звонить в колокола
rus_verbs:привезти{}, // привезти в гостиницу
rus_verbs:рухнуть{}, // рухнуть в пропасть
rus_verbs:пускать{}, // пускать в дело
rus_verbs:отвести{}, // отвести в больницу
rus_verbs:сойти{}, // сойти в ад
rus_verbs:набрать{}, // набрать в команду
rus_verbs:собрать{}, // собрать в кулак
rus_verbs:двигаться{}, // двигаться в каюту
rus_verbs:падать{}, // падать в область нуля
rus_verbs:полезть{}, // полезть в драку
rus_verbs:направить{}, // направить в стационар
rus_verbs:приводить{}, // приводить в чувство
rus_verbs:толкнуть{}, // толкнуть в бок
rus_verbs:кинуться{}, // кинуться в драку
rus_verbs:ткнуть{}, // ткнуть в глаз
rus_verbs:заключить{}, // заключить в объятия
rus_verbs:подниматься{}, // подниматься в небо
rus_verbs:расти{}, // расти в глубину
rus_verbs:налить{}, // налить в кружку
rus_verbs:швырнуть{}, // швырнуть в бездну
rus_verbs:прыгнуть{}, // прыгнуть в дверь
rus_verbs:промолчать{}, // промолчать в тряпочку
rus_verbs:садиться{}, // садиться в кресло
rus_verbs:лить{}, // лить в кувшин
rus_verbs:дослать{}, // дослать деталь в держатель
rus_verbs:переслать{}, // переслать в обработчик
rus_verbs:удалиться{}, // удалиться в совещательную комнату
rus_verbs:разглядывать{}, // разглядывать в бинокль
rus_verbs:повесить{}, // повесить в шкаф
инфинитив:походить{ вид:соверш }, // походить в институт
глагол:походить{ вид:соверш },
деепричастие:походив{},
// прилагательное:походивший{вид:соверш},
rus_verbs:помчаться{}, // помчаться в класс
rus_verbs:свалиться{}, // свалиться в яму
rus_verbs:сбежать{}, // сбежать в Англию
rus_verbs:стрелять{}, // стрелять в цель
rus_verbs:обращать{}, // обращать в свою веру
rus_verbs:завести{}, // завести в дом
rus_verbs:приобрести{}, // приобрести в рассрочку
rus_verbs:сбросить{}, // сбросить в яму
rus_verbs:устроиться{}, // устроиться в крупную корпорацию
rus_verbs:погрузиться{}, // погрузиться в пучину
rus_verbs:течь{}, // течь в канаву
rus_verbs:произвести{}, // произвести в звание майора
rus_verbs:метать{}, // метать в цель
rus_verbs:пустить{}, // пустить в дело
rus_verbs:полететь{}, // полететь в Европу
rus_verbs:пропустить{}, // пропустить в здание
rus_verbs:рвануть{}, // рвануть в отпуск
rus_verbs:заходить{}, // заходить в каморку
rus_verbs:нырнуть{}, // нырнуть в прорубь
rus_verbs:рвануться{}, // рвануться в атаку
rus_verbs:приподняться{}, // приподняться в воздух
rus_verbs:превращаться{}, // превращаться в крупную величину
rus_verbs:прокричать{}, // прокричать в ухо
rus_verbs:записать{}, // записать в блокнот
rus_verbs:забраться{}, // забраться в шкаф
rus_verbs:приезжать{}, // приезжать в деревню
rus_verbs:продать{}, // продать в рабство
rus_verbs:проникнуть{}, // проникнуть в центр
rus_verbs:устремиться{}, // устремиться в открытое море
rus_verbs:посадить{}, // посадить в кресло
rus_verbs:упереться{}, // упереться в пол
rus_verbs:ринуться{}, // ринуться в буфет
rus_verbs:отдавать{}, // отдавать в кадетское училище
rus_verbs:отложить{}, // отложить в долгий ящик
rus_verbs:убежать{}, // убежать в приют
rus_verbs:оценить{}, // оценить в миллион долларов
rus_verbs:поднимать{}, // поднимать в стратосферу
rus_verbs:отослать{}, // отослать в квалификационную комиссию
rus_verbs:отодвинуть{}, // отодвинуть в дальний угол
rus_verbs:торопиться{}, // торопиться в школу
rus_verbs:попадаться{}, // попадаться в руки
rus_verbs:поразить{}, // поразить в самое сердце
rus_verbs:доставить{}, // доставить в квартиру
rus_verbs:заслать{}, // заслать в тыл
rus_verbs:сослать{}, // сослать в изгнание
rus_verbs:запустить{}, // запустить в космос
rus_verbs:удариться{}, // удариться в запой
rus_verbs:ударяться{}, // ударяться в крайность
rus_verbs:шептать{}, // шептать в лицо
rus_verbs:уронить{}, // уронить в унитаз
rus_verbs:прорычать{}, // прорычать в микрофон
rus_verbs:засунуть{}, // засунуть в глотку
rus_verbs:плыть{}, // плыть в открытое море
rus_verbs:перенести{}, // перенести в духовку
rus_verbs:светить{}, // светить в лицо
rus_verbs:мчаться{}, // мчаться в ремонт
rus_verbs:стукнуть{}, // стукнуть в лоб
rus_verbs:обрушиться{}, // обрушиться в котлован
rus_verbs:поглядывать{}, // поглядывать в экран
rus_verbs:уложить{}, // уложить в кроватку
инфинитив:попадать{ вид:несоверш }, // попадать в черный список
глагол:попадать{ вид:несоверш },
прилагательное:попадающий{ вид:несоверш },
прилагательное:попадавший{ вид:несоверш },
деепричастие:попадая{},
rus_verbs:провалиться{}, // провалиться в яму
rus_verbs:жаловаться{}, // жаловаться в комиссию
rus_verbs:опоздать{}, // опоздать в школу
rus_verbs:посылать{}, // посылать в парикмахерскую
rus_verbs:погнать{}, // погнать в хлев
rus_verbs:поступать{}, // поступать в институт
rus_verbs:усадить{}, // усадить в кресло
rus_verbs:проиграть{}, // проиграть в рулетку
rus_verbs:прилететь{}, // прилететь в страну
rus_verbs:повалиться{}, // повалиться в траву
rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ
rus_verbs:лезть{}, // лезть в чужие дела
rus_verbs:потащить{}, // потащить в суд
rus_verbs:направляться{}, // направляться в порт
rus_verbs:поползти{}, // поползти в другую сторону
rus_verbs:пуститься{}, // пуститься в пляс
rus_verbs:забиться{}, // забиться в нору
rus_verbs:залезть{}, // залезть в конуру
rus_verbs:сдать{}, // сдать в утиль
rus_verbs:тронуться{}, // тронуться в путь
rus_verbs:сыграть{}, // сыграть в шахматы
rus_verbs:перевернуть{}, // перевернуть в более удобную позу
rus_verbs:сжимать{}, // сжимать пальцы в кулак
rus_verbs:подтолкнуть{}, // подтолкнуть в бок
rus_verbs:отнести{}, // отнести животное в лечебницу
rus_verbs:одеться{}, // одеться в зимнюю одежду
rus_verbs:плюнуть{}, // плюнуть в колодец
rus_verbs:передавать{}, // передавать в прокуратуру
rus_verbs:отскочить{}, // отскочить в лоб
rus_verbs:призвать{}, // призвать в армию
rus_verbs:увезти{}, // увезти в деревню
rus_verbs:улечься{}, // улечься в кроватку
rus_verbs:отшатнуться{}, // отшатнуться в сторону
rus_verbs:ложиться{}, // ложиться в постель
rus_verbs:пролететь{}, // пролететь в конец
rus_verbs:класть{}, // класть в сейф
rus_verbs:доставлять{}, // доставлять в кабинет
rus_verbs:приобретать{}, // приобретать в кредит
rus_verbs:сводить{}, // сводить в театр
rus_verbs:унести{}, // унести в могилу
rus_verbs:покатиться{}, // покатиться в яму
rus_verbs:сходить{}, // сходить в магазинчик
rus_verbs:спустить{}, // спустить в канализацию
rus_verbs:проникать{}, // проникать в сердцевину
rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд
rus_verbs:пожаловаться{}, // пожаловаться в администрацию
rus_verbs:стучать{}, // стучать в металлическую дверь
rus_verbs:тащить{}, // тащить в ремонт
rus_verbs:заглядывать{}, // заглядывать в ответы
rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена
rus_verbs:увести{}, // увести в следующий кабинет
rus_verbs:успевать{}, // успевать в школу
rus_verbs:пробраться{}, // пробраться в собачью конуру
rus_verbs:подавать{}, // подавать в суд
rus_verbs:прибежать{}, // прибежать в конюшню
rus_verbs:рассмотреть{}, // рассмотреть в микроскоп
rus_verbs:пнуть{}, // пнуть в живот
rus_verbs:завернуть{}, // завернуть в декоративную пленку
rus_verbs:уезжать{}, // уезжать в деревню
rus_verbs:привлекать{}, // привлекать в свои ряды
rus_verbs:перебраться{}, // перебраться в прибрежный город
rus_verbs:долить{}, // долить в коктейль
rus_verbs:палить{}, // палить в нападающих
rus_verbs:отобрать{}, // отобрать в коллекцию
rus_verbs:улететь{}, // улететь в неизвестность
rus_verbs:выглянуть{}, // выглянуть в окно
rus_verbs:выглядывать{}, // выглядывать в окно
rus_verbs:пробираться{}, // грабитель, пробирающийся в дом
инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог
глагол:написать{ aux stress="напис^ать"},
прилагательное:написавший{ aux stress="напис^авший"},
rus_verbs:свернуть{}, // свернуть в колечко
инфинитив:сползать{ вид:несоверш }, // сползать в овраг
глагол:сползать{ вид:несоверш },
прилагательное:сползающий{ вид:несоверш },
прилагательное:сползавший{ вид:несоверш },
rus_verbs:барабанить{}, // барабанить в дверь
rus_verbs:дописывать{}, // дописывать в конец
rus_verbs:меняться{}, // меняться в лучшую сторону
rus_verbs:измениться{}, // измениться в лучшую сторону
rus_verbs:изменяться{}, // изменяться в лучшую сторону
rus_verbs:вписаться{}, // вписаться в поворот
rus_verbs:вписываться{}, // вписываться в повороты
rus_verbs:переработать{}, // переработать в удобрение
rus_verbs:перерабатывать{}, // перерабатывать в удобрение
rus_verbs:уползать{}, // уползать в тень
rus_verbs:заползать{}, // заползать в нору
rus_verbs:перепрятать{}, // перепрятать в укромное место
rus_verbs:заталкивать{}, // заталкивать в вагон
rus_verbs:преобразовывать{}, // преобразовывать в список
инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список
глагол:конвертировать{ вид:несоверш },
инфинитив:конвертировать{ вид:соверш },
глагол:конвертировать{ вид:соверш },
деепричастие:конвертировав{},
деепричастие:конвертируя{},
rus_verbs:изорвать{}, // Он изорвал газету в клочки.
rus_verbs:выходить{}, // Окна выходят в сад.
rus_verbs:говорить{}, // Он говорил в защиту своего отца.
rus_verbs:вырастать{}, // Он вырастает в большого художника.
rus_verbs:вывести{}, // Он вывел детей в сад.
// инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш },
// глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли.
// прилагательное:раненый{}, // Он был ранен в левую руку.
// прилагательное:одетый{}, // Он был одет в толстое осеннее пальто.
rus_verbs:бухнуться{}, // Он бухнулся в воду.
rus_verbs:склонять{}, // склонять защиту в свою пользу
rus_verbs:впиться{}, // Пиявка впилась в тело.
rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы
rus_verbs:сохранять{}, // сохранить данные в файл
rus_verbs:собирать{}, // собирать игрушки в ящик
rus_verbs:упаковывать{}, // упаковывать вещи в чемодан
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:стрельнуть{}, // стрельни в толпу!
rus_verbs:пулять{}, // пуляй в толпу
rus_verbs:пульнуть{}, // пульни в толпу
rus_verbs:становиться{}, // Становитесь в очередь.
rus_verbs:вписать{}, // Юля вписала свое имя в список.
rus_verbs:вписывать{}, // Мы вписывали свои имена в список
прилагательное:видный{}, // Планета Марс видна в обычный бинокль
rus_verbs:пойти{}, // Девочка рано пошла в школу
rus_verbs:отойти{}, // Эти обычаи отошли в историю.
rus_verbs:бить{}, // Холодный ветер бил ему в лицо.
rus_verbs:входить{}, // Это входит в его обязанности.
rus_verbs:принять{}, // меня приняли в пионеры
rus_verbs:уйти{}, // Правительство РФ ушло в отставку
rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году.
rus_verbs:посвятить{}, // Я посвятил друга в свою тайну.
инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока
rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза.
rus_verbs:идти{}, // Я иду гулять в парк.
rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт.
rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей.
rus_verbs:везти{}, // Учитель везёт детей в лагерь.
rus_verbs:качать{}, // Судно качает во все стороны.
rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами.
rus_verbs:связать{}, // Свяжите свои вещи в узелок.
rus_verbs:пронести{}, // Пронесите стол в дверь.
rus_verbs:вынести{}, // Надо вынести примечания в конец.
rus_verbs:устроить{}, // Она устроила сына в школу.
rus_verbs:угодить{}, // Она угодила головой в дверь.
rus_verbs:отвернуться{}, // Она резко отвернулась в сторону.
rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль.
rus_verbs:обратить{}, // Война обратила город в развалины.
rus_verbs:сойтись{}, // Мы сошлись в школьные годы.
rus_verbs:приехать{}, // Мы приехали в положенный час.
rus_verbs:встать{}, // Дети встали в круг.
rus_verbs:впасть{}, // Из-за болезни он впал в нужду.
rus_verbs:придти{}, // придти в упадок
rus_verbs:заявить{}, // Надо заявить в милицию о краже.
rus_verbs:заявлять{}, // заявлять в полицию
rus_verbs:ехать{}, // Мы будем ехать в Орёл
rus_verbs:окрашиваться{}, // окрашиваться в красный цвет
rus_verbs:решить{}, // Дело решено в пользу истца.
rus_verbs:сесть{}, // Она села в кресло
rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало.
rus_verbs:влезать{}, // он влезает в мою квартирку
rus_verbs:попасться{}, // в мою ловушку попалась мышь
rus_verbs:лететь{}, // Мы летим в Орёл
ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень
ГЛ_ИНФ(взять), // Коля взял в руку камень
ГЛ_ИНФ(поехать), // поехать в круиз
ГЛ_ИНФ(подать), // подать в отставку
инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик
инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик
ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море
ГЛ_ИНФ(постучать) // постучать в дверь
}
// Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } }
then return true
}
#endregion Винительный
// Все остальные варианты по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:в{} * }
then return false,-5
}
#endregion Предлог_В
#region Предлог_НА
// ------------------- С ПРЕДЛОГОМ 'НА' ---------------------------
#region ПРЕДЛОЖНЫЙ
// НА+предложный падеж:
// ЛЕЖАТЬ НА СТОЛЕ
#region VerbList
wordentry_set Гл_НА_Предл=
{
rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета
rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ)
rus_verbs:ПРОСТУПИТЬ{}, //
rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ)
rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ)
rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив)
rus_verbs:ЗАМИРАТЬ{}, //
rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ)
rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ)
rus_verbs:УПОЛЗАТЬ{}, //
rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ)
rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ)
rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ)
rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ)
rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ)
rus_verbs:искриться{},
rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ)
rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ)
rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ)
rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ)
rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ)
rus_verbs:отвести{}, // отвести душу на людях
rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра
rus_verbs:сойтись{},
rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ)
rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ)
rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ)
глагол:ДОСТИЧЬ{},
инфинитив:ДОСТИЧЬ{},
rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте
rus_verbs:РАСКЛАДЫВАТЬ{},
rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ)
rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ)
rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ)
rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ)
rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ)
rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ)
rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта
rus_verbs:подпрыгивать{},
rus_verbs:высветиться{}, // на компьютере высветится твоя подпись
rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах
rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе
rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА)
rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл)
rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл)
rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА)
rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл)
rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл)
rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл)
rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл)
rus_verbs:ОТТОЧИТЬ{},
rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА)
rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл)
инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл)
глагол:НАХОДИТЬСЯ{ вид:несоверш },
прилагательное:находившийся{ вид:несоверш },
прилагательное:находящийся{ вид:несоверш },
деепричастие:находясь{},
rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл)
rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА)
rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА)
rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл)
rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА)
rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл)
rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА)
rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА)
rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА)
rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА)
rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА)
rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА)
rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл)
rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА)
rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА)
rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА)
rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА)
rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА)
rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл)
rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл)
rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на)
rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к)
rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на)
глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте)
деепричастие:вычитав{},
rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на)
rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере
rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере
rus_verbs:развалиться{}, // Антонио развалился на диване
rus_verbs:улечься{}, // Антонио улегся на полу
rus_verbs:зарубить{}, // Заруби себе на носу.
rus_verbs:ценить{}, // Его ценят на заводе.
rus_verbs:вернуться{}, // Отец вернулся на закате.
rus_verbs:шить{}, // Вы умеете шить на машинке?
rus_verbs:бить{}, // Скот бьют на бойне.
rus_verbs:выехать{}, // Мы выехали на рассвете.
rus_verbs:валяться{}, // На полу валяется бумага.
rus_verbs:разложить{}, // она разложила полотенце на песке
rus_verbs:заниматься{}, // я занимаюсь на тренажере
rus_verbs:позаниматься{},
rus_verbs:порхать{}, // порхать на лугу
rus_verbs:пресекать{}, // пресекать на корню
rus_verbs:изъясняться{}, // изъясняться на непонятном языке
rus_verbs:развесить{}, // развесить на столбах
rus_verbs:обрасти{}, // обрасти на южной части
rus_verbs:откладываться{}, // откладываться на стенках артерий
rus_verbs:уносить{}, // уносить на носилках
rus_verbs:проплыть{}, // проплыть на плоту
rus_verbs:подъезжать{}, // подъезжать на повозках
rus_verbs:пульсировать{}, // пульсировать на лбу
rus_verbs:рассесться{}, // птицы расселись на ветках
rus_verbs:застопориться{}, // застопориться на первом пункте
rus_verbs:изловить{}, // изловить на окраинах
rus_verbs:покататься{}, // покататься на машинках
rus_verbs:залопотать{}, // залопотать на неизвестном языке
rus_verbs:растягивать{}, // растягивать на станке
rus_verbs:поделывать{}, // поделывать на пляже
rus_verbs:подстеречь{}, // подстеречь на площадке
rus_verbs:проектировать{}, // проектировать на компьютере
rus_verbs:притулиться{}, // притулиться на кушетке
rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище
rus_verbs:пострелять{}, // пострелять на испытательном полигоне
rus_verbs:засиживаться{}, // засиживаться на работе
rus_verbs:нежиться{}, // нежиться на солнышке
rus_verbs:притомиться{}, // притомиться на рабочем месте
rus_verbs:поселяться{}, // поселяться на чердаке
rus_verbs:потягиваться{}, // потягиваться на земле
rus_verbs:отлеживаться{}, // отлеживаться на койке
rus_verbs:протаранить{}, // протаранить на танке
rus_verbs:гарцевать{}, // гарцевать на коне
rus_verbs:облупиться{}, // облупиться на носу
rus_verbs:оговорить{}, // оговорить на собеседовании
rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте
rus_verbs:отпечатать{}, // отпечатать на картоне
rus_verbs:сэкономить{}, // сэкономить на мелочах
rus_verbs:покатать{}, // покатать на пони
rus_verbs:колесить{}, // колесить на старой машине
rus_verbs:понастроить{}, // понастроить на участках
rus_verbs:поджарить{}, // поджарить на костре
rus_verbs:узнаваться{}, // узнаваться на фотографии
rus_verbs:отощать{}, // отощать на казенных харчах
rus_verbs:редеть{}, // редеть на макушке
rus_verbs:оглашать{}, // оглашать на общем собрании
rus_verbs:лопотать{}, // лопотать на иврите
rus_verbs:пригреть{}, // пригреть на груди
rus_verbs:консультироваться{}, // консультироваться на форуме
rus_verbs:приноситься{}, // приноситься на одежде
rus_verbs:сушиться{}, // сушиться на балконе
rus_verbs:наследить{}, // наследить на полу
rus_verbs:нагреться{}, // нагреться на солнце
rus_verbs:рыбачить{}, // рыбачить на озере
rus_verbs:прокатить{}, // прокатить на выборах
rus_verbs:запинаться{}, // запинаться на ровном месте
rus_verbs:отрубиться{}, // отрубиться на мягкой подушке
rus_verbs:заморозить{}, // заморозить на улице
rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе
rus_verbs:просохнуть{}, // просохнуть на батарее
rus_verbs:развозить{}, // развозить на велосипеде
rus_verbs:прикорнуть{}, // прикорнуть на диванчике
rus_verbs:отпечататься{}, // отпечататься на коже
rus_verbs:выявлять{}, // выявлять на таможне
rus_verbs:расставлять{}, // расставлять на башнях
rus_verbs:прокрутить{}, // прокрутить на пальце
rus_verbs:умываться{}, // умываться на улице
rus_verbs:пересказывать{}, // пересказывать на страницах романа
rus_verbs:удалять{}, // удалять на пуховике
rus_verbs:хозяйничать{}, // хозяйничать на складе
rus_verbs:оперировать{}, // оперировать на поле боя
rus_verbs:поносить{}, // поносить на голове
rus_verbs:замурлыкать{}, // замурлыкать на коленях
rus_verbs:передвигать{}, // передвигать на тележке
rus_verbs:прочертить{}, // прочертить на земле
rus_verbs:колдовать{}, // колдовать на кухне
rus_verbs:отвозить{}, // отвозить на казенном транспорте
rus_verbs:трахать{}, // трахать на природе
rus_verbs:мастерить{}, // мастерить на кухне
rus_verbs:ремонтировать{}, // ремонтировать на коленке
rus_verbs:развезти{}, // развезти на велосипеде
rus_verbs:робеть{}, // робеть на сцене
инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте
глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш },
деепричастие:реализовав{}, деепричастие:реализуя{},
rus_verbs:покаяться{}, // покаяться на смертном одре
rus_verbs:специализироваться{}, // специализироваться на тестировании
rus_verbs:попрыгать{}, // попрыгать на батуте
rus_verbs:переписывать{}, // переписывать на столе
rus_verbs:расписывать{}, // расписывать на доске
rus_verbs:зажимать{}, // зажимать на запястье
rus_verbs:практиковаться{}, // практиковаться на мышах
rus_verbs:уединиться{}, // уединиться на чердаке
rus_verbs:подохнуть{}, // подохнуть на чужбине
rus_verbs:приподниматься{}, // приподниматься на руках
rus_verbs:уродиться{}, // уродиться на полях
rus_verbs:продолжиться{}, // продолжиться на улице
rus_verbs:посапывать{}, // посапывать на диване
rus_verbs:ободрать{}, // ободрать на спине
rus_verbs:скрючиться{}, // скрючиться на песке
rus_verbs:тормознуть{}, // тормознуть на перекрестке
rus_verbs:лютовать{}, // лютовать на хуторе
rus_verbs:зарегистрировать{}, // зарегистрировать на сайте
rus_verbs:переждать{}, // переждать на вершине холма
rus_verbs:доминировать{}, // доминировать на территории
rus_verbs:публиковать{}, // публиковать на сайте
rus_verbs:морщить{}, // морщить на лбу
rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном
rus_verbs:подрабатывать{}, // подрабатывать на рынке
rus_verbs:репетировать{}, // репетировать на заднем дворе
rus_verbs:подвернуть{}, // подвернуть на брусчатке
rus_verbs:зашелестеть{}, // зашелестеть на ветру
rus_verbs:расчесывать{}, // расчесывать на спине
rus_verbs:одевать{}, // одевать на рынке
rus_verbs:испечь{}, // испечь на углях
rus_verbs:сбрить{}, // сбрить на затылке
rus_verbs:согреться{}, // согреться на печке
rus_verbs:замаячить{}, // замаячить на горизонте
rus_verbs:пересчитывать{}, // пересчитывать на пальцах
rus_verbs:галдеть{}, // галдеть на крыльце
rus_verbs:переплыть{}, // переплыть на плоту
rus_verbs:передохнуть{}, // передохнуть на скамейке
rus_verbs:прижиться{}, // прижиться на ферме
rus_verbs:переправляться{}, // переправляться на плотах
rus_verbs:накупить{}, // накупить на блошином рынке
rus_verbs:проторчать{}, // проторчать на виду
rus_verbs:мокнуть{}, // мокнуть на улице
rus_verbs:застукать{}, // застукать на камбузе
rus_verbs:завязывать{}, // завязывать на ботинках
rus_verbs:повисать{}, // повисать на ветке
rus_verbs:подвизаться{}, // подвизаться на государственной службе
rus_verbs:кормиться{}, // кормиться на болоте
rus_verbs:покурить{}, // покурить на улице
rus_verbs:зимовать{}, // зимовать на болотах
rus_verbs:застегивать{}, // застегивать на гимнастерке
rus_verbs:поигрывать{}, // поигрывать на гитаре
rus_verbs:погореть{}, // погореть на махинациях с землей
rus_verbs:кувыркаться{}, // кувыркаться на батуте
rus_verbs:похрапывать{}, // похрапывать на диване
rus_verbs:пригревать{}, // пригревать на груди
rus_verbs:завязнуть{}, // завязнуть на болоте
rus_verbs:шастать{}, // шастать на втором этаже
rus_verbs:заночевать{}, // заночевать на сеновале
rus_verbs:отсиживаться{}, // отсиживаться на чердаке
rus_verbs:мчать{}, // мчать на байке
rus_verbs:сгнить{}, // сгнить на урановых рудниках
rus_verbs:тренировать{}, // тренировать на манекенах
rus_verbs:повеселиться{}, // повеселиться на празднике
rus_verbs:измучиться{}, // измучиться на болоте
rus_verbs:увянуть{}, // увянуть на подоконнике
rus_verbs:раскрутить{}, // раскрутить на оси
rus_verbs:выцвести{}, // выцвести на солнечном свету
rus_verbs:изготовлять{}, // изготовлять на коленке
rus_verbs:гнездиться{}, // гнездиться на вершине дерева
rus_verbs:разогнаться{}, // разогнаться на мотоцикле
rus_verbs:излагаться{}, // излагаться на страницах доклада
rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге
rus_verbs:расчесать{}, // расчесать на макушке
rus_verbs:плавиться{}, // плавиться на солнце
rus_verbs:редактировать{}, // редактировать на ноутбуке
rus_verbs:подскакивать{}, // подскакивать на месте
rus_verbs:покупаться{}, // покупаться на рынке
rus_verbs:промышлять{}, // промышлять на мелководье
rus_verbs:приобретаться{}, // приобретаться на распродажах
rus_verbs:наигрывать{}, // наигрывать на банджо
rus_verbs:маневрировать{}, // маневрировать на флангах
rus_verbs:запечатлеться{}, // запечатлеться на записях камер
rus_verbs:укрывать{}, // укрывать на чердаке
rus_verbs:подорваться{}, // подорваться на фугасе
rus_verbs:закрепиться{}, // закрепиться на занятых позициях
rus_verbs:громыхать{}, // громыхать на кухне
инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу
деепричастие:подвигавшись{},
rus_verbs:добываться{}, // добываться на территории Анголы
rus_verbs:приплясывать{}, // приплясывать на сцене
rus_verbs:доживать{}, // доживать на больничной койке
rus_verbs:отпраздновать{}, // отпраздновать на работе
rus_verbs:сгубить{}, // сгубить на корню
rus_verbs:схоронить{}, // схоронить на кладбище
rus_verbs:тускнеть{}, // тускнеть на солнце
rus_verbs:скопить{}, // скопить на счету
rus_verbs:помыть{}, // помыть на своем этаже
rus_verbs:пороть{}, // пороть на конюшне
rus_verbs:наличествовать{}, // наличествовать на складе
rus_verbs:нащупывать{}, // нащупывать на полке
rus_verbs:змеиться{}, // змеиться на дне
rus_verbs:пожелтеть{}, // пожелтеть на солнце
rus_verbs:заостриться{}, // заостриться на конце
rus_verbs:свезти{}, // свезти на поле
rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре
rus_verbs:подкрутить{}, // подкрутить на приборной панели
rus_verbs:рубиться{}, // рубиться на мечах
rus_verbs:сиживать{}, // сиживать на крыльце
rus_verbs:тараторить{}, // тараторить на иностранном языке
rus_verbs:теплеть{}, // теплеть на сердце
rus_verbs:покачаться{}, // покачаться на ветке
rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче
rus_verbs:развязывать{}, // развязывать на ботинках
rus_verbs:подвозить{}, // подвозить на мотороллере
rus_verbs:вышивать{}, // вышивать на рубашке
rus_verbs:скупать{}, // скупать на открытом рынке
rus_verbs:оформлять{}, // оформлять на встрече
rus_verbs:распускаться{}, // распускаться на клумбах
rus_verbs:прогореть{}, // прогореть на спекуляциях
rus_verbs:приползти{}, // приползти на коленях
rus_verbs:загореть{}, // загореть на пляже
rus_verbs:остудить{}, // остудить на балконе
rus_verbs:нарвать{}, // нарвать на поляне
rus_verbs:издохнуть{}, // издохнуть на болоте
rus_verbs:разгружать{}, // разгружать на дороге
rus_verbs:произрастать{}, // произрастать на болотах
rus_verbs:разуться{}, // разуться на коврике
rus_verbs:сооружать{}, // сооружать на площади
rus_verbs:зачитывать{}, // зачитывать на митинге
rus_verbs:уместиться{}, // уместиться на ладони
rus_verbs:закупить{}, // закупить на рынке
rus_verbs:горланить{}, // горланить на улице
rus_verbs:экономить{}, // экономить на спичках
rus_verbs:исправлять{}, // исправлять на доске
rus_verbs:расслабляться{}, // расслабляться на лежаке
rus_verbs:скапливаться{}, // скапливаться на крыше
rus_verbs:сплетничать{}, // сплетничать на скамеечке
rus_verbs:отъезжать{}, // отъезжать на лимузине
rus_verbs:отчитывать{}, // отчитывать на собрании
rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке
rus_verbs:потчевать{}, // потчевать на лаврах
rus_verbs:окопаться{}, // окопаться на окраине
rus_verbs:загорать{}, // загорать на пляже
rus_verbs:обгореть{}, // обгореть на солнце
rus_verbs:распознавать{}, // распознавать на фотографии
rus_verbs:заплетаться{}, // заплетаться на макушке
rus_verbs:перегреться{}, // перегреться на жаре
rus_verbs:подметать{}, // подметать на крыльце
rus_verbs:нарисоваться{}, // нарисоваться на горизонте
rus_verbs:проскакивать{}, // проскакивать на экране
rus_verbs:попивать{}, // попивать на балконе чай
rus_verbs:отплывать{}, // отплывать на лодке
rus_verbs:чирикать{}, // чирикать на ветках
rus_verbs:скупить{}, // скупить на оптовых базах
rus_verbs:наколоть{}, // наколоть на коже картинку
rus_verbs:созревать{}, // созревать на ветке
rus_verbs:проколоться{}, // проколоться на мелочи
rus_verbs:крутнуться{}, // крутнуться на заднем колесе
rus_verbs:переночевать{}, // переночевать на постоялом дворе
rus_verbs:концентрироваться{}, // концентрироваться на фильтре
rus_verbs:одичать{}, // одичать на хуторе
rus_verbs:спасаться{}, // спасаются на лодке
rus_verbs:доказываться{}, // доказываться на страницах книги
rus_verbs:познаваться{}, // познаваться на ринге
rus_verbs:замыкаться{}, // замыкаться на металлическом предмете
rus_verbs:заприметить{}, // заприметить на пригорке
rus_verbs:продержать{}, // продержать на морозе
rus_verbs:форсировать{}, // форсировать на плотах
rus_verbs:сохнуть{}, // сохнуть на солнце
rus_verbs:выявить{}, // выявить на поверхности
rus_verbs:заседать{}, // заседать на кафедре
rus_verbs:расплачиваться{}, // расплачиваться на выходе
rus_verbs:светлеть{}, // светлеть на горизонте
rus_verbs:залепетать{}, // залепетать на незнакомом языке
rus_verbs:подсчитывать{}, // подсчитывать на пальцах
rus_verbs:зарыть{}, // зарыть на пустыре
rus_verbs:сформироваться{}, // сформироваться на месте
rus_verbs:развертываться{}, // развертываться на площадке
rus_verbs:набивать{}, // набивать на манекенах
rus_verbs:замерзать{}, // замерзать на ветру
rus_verbs:схватывать{}, // схватывать на лету
rus_verbs:перевестись{}, // перевестись на Руси
rus_verbs:смешивать{}, // смешивать на блюдце
rus_verbs:прождать{}, // прождать на входе
rus_verbs:мерзнуть{}, // мерзнуть на ветру
rus_verbs:растирать{}, // растирать на коже
rus_verbs:переспать{}, // переспал на сеновале
rus_verbs:рассекать{}, // рассекать на скутере
rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне
rus_verbs:дрыхнуть{}, // дрыхнуть на диване
rus_verbs:распять{}, // распять на кресте
rus_verbs:запечься{}, // запечься на костре
rus_verbs:застилать{}, // застилать на балконе
rus_verbs:сыскаться{}, // сыскаться на огороде
rus_verbs:разориться{}, // разориться на продаже спичек
rus_verbs:переделать{}, // переделать на станке
rus_verbs:разъяснять{}, // разъяснять на страницах газеты
rus_verbs:поседеть{}, // поседеть на висках
rus_verbs:протащить{}, // протащить на спине
rus_verbs:осуществиться{}, // осуществиться на деле
rus_verbs:селиться{}, // селиться на окраине
rus_verbs:оплачивать{}, // оплачивать на первой кассе
rus_verbs:переворачивать{}, // переворачивать на сковородке
rus_verbs:упражняться{}, // упражняться на батуте
rus_verbs:испробовать{}, // испробовать на себе
rus_verbs:разгладиться{}, // разгладиться на спине
rus_verbs:рисоваться{}, // рисоваться на стекле
rus_verbs:продрогнуть{}, // продрогнуть на морозе
rus_verbs:пометить{}, // пометить на доске
rus_verbs:приютить{}, // приютить на чердаке
rus_verbs:избирать{}, // избирать на первых свободных выборах
rus_verbs:затеваться{}, // затеваться на матче
rus_verbs:уплывать{}, // уплывать на катере
rus_verbs:замерцать{}, // замерцать на рекламном щите
rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне
rus_verbs:запираться{}, // запираться на чердаке
rus_verbs:загубить{}, // загубить на корню
rus_verbs:развеяться{}, // развеяться на природе
rus_verbs:съезжаться{}, // съезжаться на лимузинах
rus_verbs:потанцевать{}, // потанцевать на могиле
rus_verbs:дохнуть{}, // дохнуть на солнце
rus_verbs:припарковаться{}, // припарковаться на газоне
rus_verbs:отхватить{}, // отхватить на распродаже
rus_verbs:остывать{}, // остывать на улице
rus_verbs:переваривать{}, // переваривать на высокой ветке
rus_verbs:подвесить{}, // подвесить на веревке
rus_verbs:хвастать{}, // хвастать на работе
rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая
rus_verbs:разлечься{}, // разлечься на полу
rus_verbs:очертить{}, // очертить на полу
rus_verbs:председательствовать{}, // председательствовать на собрании
rus_verbs:сконфузиться{}, // сконфузиться на сцене
rus_verbs:выявляться{}, // выявляться на ринге
rus_verbs:крутануться{}, // крутануться на заднем колесе
rus_verbs:караулить{}, // караулить на входе
rus_verbs:перечислять{}, // перечислять на пальцах
rus_verbs:обрабатывать{}, // обрабатывать на станке
rus_verbs:настигать{}, // настигать на берегу
rus_verbs:разгуливать{}, // разгуливать на берегу
rus_verbs:насиловать{}, // насиловать на пляже
rus_verbs:поредеть{}, // поредеть на макушке
rus_verbs:учитывать{}, // учитывать на балансе
rus_verbs:зарождаться{}, // зарождаться на большой глубине
rus_verbs:распространять{}, // распространять на сайтах
rus_verbs:пировать{}, // пировать на вершине холма
rus_verbs:начертать{}, // начертать на стене
rus_verbs:расцветать{}, // расцветать на подоконнике
rus_verbs:умнеть{}, // умнеть на глазах
rus_verbs:царствовать{}, // царствовать на окраине
rus_verbs:закрутиться{}, // закрутиться на работе
rus_verbs:отработать{}, // отработать на шахте
rus_verbs:полечь{}, // полечь на поле брани
rus_verbs:щебетать{}, // щебетать на ветке
rus_verbs:подчеркиваться{}, // подчеркиваться на сайте
rus_verbs:посеять{}, // посеять на другом поле
rus_verbs:замечаться{}, // замечаться на пастбище
rus_verbs:просчитать{}, // просчитать на пальцах
rus_verbs:голосовать{}, // голосовать на трассе
rus_verbs:маяться{}, // маяться на пляже
rus_verbs:сколотить{}, // сколотить на службе
rus_verbs:обретаться{}, // обретаться на чужбине
rus_verbs:обливаться{}, // обливаться на улице
rus_verbs:катать{}, // катать на лошадке
rus_verbs:припрятать{}, // припрятать на теле
rus_verbs:запаниковать{}, // запаниковать на экзамене
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете
деепричастие:слетав{},
rus_verbs:срубить{}, // срубить денег на спекуляциях
rus_verbs:зажигаться{}, // зажигаться на улице
rus_verbs:жарить{}, // жарить на углях
rus_verbs:накапливаться{}, // накапливаться на счету
rus_verbs:распуститься{}, // распуститься на грядке
rus_verbs:рассаживаться{}, // рассаживаться на местах
rus_verbs:странствовать{}, // странствовать на лошади
rus_verbs:осматриваться{}, // осматриваться на месте
rus_verbs:разворачивать{}, // разворачивать на завоеванной территории
rus_verbs:согревать{}, // согревать на вершине горы
rus_verbs:заскучать{}, // заскучать на вахте
rus_verbs:перекусить{}, // перекусить на бегу
rus_verbs:приплыть{}, // приплыть на тримаране
rus_verbs:зажигать{}, // зажигать на танцах
rus_verbs:закопать{}, // закопать на поляне
rus_verbs:стирать{}, // стирать на берегу
rus_verbs:подстерегать{}, // подстерегать на подходе
rus_verbs:погулять{}, // погулять на свадьбе
rus_verbs:огласить{}, // огласить на митинге
rus_verbs:разбогатеть{}, // разбогатеть на прииске
rus_verbs:грохотать{}, // грохотать на чердаке
rus_verbs:расположить{}, // расположить на границе
rus_verbs:реализоваться{}, // реализоваться на новой работе
rus_verbs:застывать{}, // застывать на морозе
rus_verbs:запечатлеть{}, // запечатлеть на пленке
rus_verbs:тренироваться{}, // тренироваться на манекене
rus_verbs:поспорить{}, // поспорить на совещании
rus_verbs:затягивать{}, // затягивать на поясе
rus_verbs:зиждиться{}, // зиждиться на твердой основе
rus_verbs:построиться{}, // построиться на песке
rus_verbs:надрываться{}, // надрываться на работе
rus_verbs:закипать{}, // закипать на плите
rus_verbs:затонуть{}, // затонуть на мелководье
rus_verbs:побыть{}, // побыть на фазенде
rus_verbs:сгорать{}, // сгорать на солнце
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице
деепричастие:пописав{ aux stress="поп^исав" },
rus_verbs:подраться{}, // подраться на сцене
rus_verbs:заправить{}, // заправить на последней заправке
rus_verbs:обозначаться{}, // обозначаться на карте
rus_verbs:просиживать{}, // просиживать на берегу
rus_verbs:начертить{}, // начертить на листке
rus_verbs:тормозить{}, // тормозить на льду
rus_verbs:затевать{}, // затевать на космической базе
rus_verbs:задерживать{}, // задерживать на таможне
rus_verbs:прилетать{}, // прилетать на частном самолете
rus_verbs:полулежать{}, // полулежать на травке
rus_verbs:ерзать{}, // ерзать на табуретке
rus_verbs:покопаться{}, // покопаться на складе
rus_verbs:подвезти{}, // подвезти на машине
rus_verbs:полежать{}, // полежать на водном матрасе
rus_verbs:стыть{}, // стыть на улице
rus_verbs:стынуть{}, // стынуть на улице
rus_verbs:скреститься{}, // скреститься на груди
rus_verbs:припарковать{}, // припарковать на стоянке
rus_verbs:здороваться{}, // здороваться на кафедре
rus_verbs:нацарапать{}, // нацарапать на парте
rus_verbs:откопать{}, // откопать на поляне
rus_verbs:смастерить{}, // смастерить на коленках
rus_verbs:довезти{}, // довезти на машине
rus_verbs:избивать{}, // избивать на крыше
rus_verbs:сварить{}, // сварить на костре
rus_verbs:истребить{}, // истребить на корню
rus_verbs:раскопать{}, // раскопать на болоте
rus_verbs:попить{}, // попить на кухне
rus_verbs:заправлять{}, // заправлять на базе
rus_verbs:кушать{}, // кушать на кухне
rus_verbs:замолкать{}, // замолкать на половине фразы
rus_verbs:измеряться{}, // измеряться на весах
rus_verbs:сбываться{}, // сбываться на самом деле
rus_verbs:изображаться{}, // изображается на сцене
rus_verbs:фиксировать{}, // фиксировать на данной высоте
rus_verbs:ослаблять{}, // ослаблять на шее
rus_verbs:зреть{}, // зреть на грядке
rus_verbs:зеленеть{}, // зеленеть на грядке
rus_verbs:критиковать{}, // критиковать на страницах газеты
rus_verbs:облететь{}, // облететь на самолете
rus_verbs:заразиться{}, // заразиться на работе
rus_verbs:рассеять{}, // рассеять на территории
rus_verbs:печься{}, // печься на костре
rus_verbs:поспать{}, // поспать на земле
rus_verbs:сплетаться{}, // сплетаться на макушке
rus_verbs:удерживаться{}, // удерживаться на расстоянии
rus_verbs:помешаться{}, // помешаться на чистоте
rus_verbs:ликвидировать{}, // ликвидировать на полигоне
rus_verbs:проваляться{}, // проваляться на диване
rus_verbs:лечиться{}, // лечиться на дому
rus_verbs:обработать{}, // обработать на станке
rus_verbs:защелкнуть{}, // защелкнуть на руках
rus_verbs:разносить{}, // разносить на одежде
rus_verbs:чесать{}, // чесать на груди
rus_verbs:наладить{}, // наладить на конвейере выпуск
rus_verbs:отряхнуться{}, // отряхнуться на улице
rus_verbs:разыгрываться{}, // разыгрываться на скачках
rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях
rus_verbs:греться{}, // греться на вокзале
rus_verbs:засидеться{}, // засидеться на одном месте
rus_verbs:материализоваться{}, // материализоваться на границе
rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин
rus_verbs:перевозить{}, // перевозить на платформе
rus_verbs:поиграть{}, // поиграть на скрипке
rus_verbs:потоптаться{}, // потоптаться на одном месте
rus_verbs:переправиться{}, // переправиться на плоту
rus_verbs:забрезжить{}, // забрезжить на горизонте
rus_verbs:завывать{}, // завывать на опушке
rus_verbs:заваривать{}, // заваривать на кухоньке
rus_verbs:перемещаться{}, // перемещаться на спасательном плоту
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке
rus_verbs:праздновать{}, // праздновать на улицах
rus_verbs:обучить{}, // обучить на корте
rus_verbs:орудовать{}, // орудовать на складе
rus_verbs:подрасти{}, // подрасти на глядке
rus_verbs:шелестеть{}, // шелестеть на ветру
rus_verbs:раздеваться{}, // раздеваться на публике
rus_verbs:пообедать{}, // пообедать на газоне
rus_verbs:жрать{}, // жрать на помойке
rus_verbs:исполняться{}, // исполняться на флейте
rus_verbs:похолодать{}, // похолодать на улице
rus_verbs:гнить{}, // гнить на каторге
rus_verbs:прослушать{}, // прослушать на концерте
rus_verbs:совещаться{}, // совещаться на заседании
rus_verbs:покачивать{}, // покачивать на волнах
rus_verbs:отсидеть{}, // отсидеть на гаупвахте
rus_verbs:формировать{}, // формировать на секретной базе
rus_verbs:захрапеть{}, // захрапеть на кровати
rus_verbs:объехать{}, // объехать на попутке
rus_verbs:поселить{}, // поселить на верхних этажах
rus_verbs:заворочаться{}, // заворочаться на сене
rus_verbs:напрятать{}, // напрятать на теле
rus_verbs:очухаться{}, // очухаться на земле
rus_verbs:полистать{}, // полистать на досуге
rus_verbs:завертеть{}, // завертеть на шесте
rus_verbs:печатать{}, // печатать на ноуте
rus_verbs:отыскаться{}, // отыскаться на складе
rus_verbs:зафиксировать{}, // зафиксировать на пленке
rus_verbs:расстилаться{}, // расстилаться на столе
rus_verbs:заместить{}, // заместить на посту
rus_verbs:угасать{}, // угасать на неуправляемом корабле
rus_verbs:сразить{}, // сразить на ринге
rus_verbs:расплываться{}, // расплываться на жаре
rus_verbs:сосчитать{}, // сосчитать на пальцах
rus_verbs:сгуститься{}, // сгуститься на небольшой высоте
rus_verbs:цитировать{}, // цитировать на плите
rus_verbs:ориентироваться{}, // ориентироваться на местности
rus_verbs:расширить{}, // расширить на другом конце
rus_verbs:обтереть{}, // обтереть на стоянке
rus_verbs:подстрелить{}, // подстрелить на охоте
rus_verbs:растереть{}, // растереть на твердой поверхности
rus_verbs:подавлять{}, // подавлять на первом этапе
rus_verbs:смешиваться{}, // смешиваться на поверхности
// инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте
// деепричастие:вычитав{},
rus_verbs:сократиться{}, // сократиться на втором этапе
rus_verbs:занервничать{}, // занервничать на экзамене
rus_verbs:соприкоснуться{}, // соприкоснуться на трассе
rus_verbs:обозначить{}, // обозначить на плане
rus_verbs:обучаться{}, // обучаться на производстве
rus_verbs:снизиться{}, // снизиться на большой высоте
rus_verbs:простудиться{}, // простудиться на ветру
rus_verbs:поддерживаться{}, // поддерживается на встрече
rus_verbs:уплыть{}, // уплыть на лодочке
rus_verbs:резвиться{}, // резвиться на песочке
rus_verbs:поерзать{}, // поерзать на скамеечке
rus_verbs:похвастаться{}, // похвастаться на встрече
rus_verbs:знакомиться{}, // знакомиться на уроке
rus_verbs:проплывать{}, // проплывать на катере
rus_verbs:засесть{}, // засесть на чердаке
rus_verbs:подцепить{}, // подцепить на дискотеке
rus_verbs:обыскать{}, // обыскать на входе
rus_verbs:оправдаться{}, // оправдаться на суде
rus_verbs:раскрываться{}, // раскрываться на сцене
rus_verbs:одеваться{}, // одеваться на вещевом рынке
rus_verbs:засветиться{}, // засветиться на фотографиях
rus_verbs:употребляться{}, // употребляться на птицефабриках
rus_verbs:грабить{}, // грабить на пустыре
rus_verbs:гонять{}, // гонять на повышенных оборотах
rus_verbs:развеваться{}, // развеваться на древке
rus_verbs:основываться{}, // основываться на безусловных фактах
rus_verbs:допрашивать{}, // допрашивать на базе
rus_verbs:проработать{}, // проработать на стройке
rus_verbs:сосредоточить{}, // сосредоточить на месте
rus_verbs:сочинять{}, // сочинять на ходу
rus_verbs:ползать{}, // ползать на камне
rus_verbs:раскинуться{}, // раскинуться на пустыре
rus_verbs:уставать{}, // уставать на работе
rus_verbs:укрепить{}, // укрепить на конце
rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь
rus_verbs:одобрять{}, // одобрять на словах
rus_verbs:приговорить{}, // приговорить на заседании тройки
rus_verbs:чернеть{}, // чернеть на свету
rus_verbs:гнуть{}, // гнуть на станке
rus_verbs:размещаться{}, // размещаться на бирже
rus_verbs:соорудить{}, // соорудить на даче
rus_verbs:пастись{}, // пастись на лугу
rus_verbs:формироваться{}, // формироваться на дне
rus_verbs:таить{}, // таить на дне
rus_verbs:приостановиться{}, // приостановиться на середине
rus_verbs:топтаться{}, // топтаться на месте
rus_verbs:громить{}, // громить на подступах
rus_verbs:вычислить{}, // вычислить на бумажке
rus_verbs:заказывать{}, // заказывать на сайте
rus_verbs:осуществить{}, // осуществить на практике
rus_verbs:обосноваться{}, // обосноваться на верхушке
rus_verbs:пытать{}, // пытать на электрическом стуле
rus_verbs:совершиться{}, // совершиться на заседании
rus_verbs:свернуться{}, // свернуться на медленном огне
rus_verbs:пролетать{}, // пролетать на дельтаплане
rus_verbs:сбыться{}, // сбыться на самом деле
rus_verbs:разговориться{}, // разговориться на уроке
rus_verbs:разворачиваться{}, // разворачиваться на перекрестке
rus_verbs:преподнести{}, // преподнести на блюдечке
rus_verbs:напечатать{}, // напечатать на лазернике
rus_verbs:прорвать{}, // прорвать на периферии
rus_verbs:раскачиваться{}, // раскачиваться на доске
rus_verbs:задерживаться{}, // задерживаться на старте
rus_verbs:угощать{}, // угощать на вечеринке
rus_verbs:шарить{}, // шарить на столе
rus_verbs:увеличивать{}, // увеличивать на первом этапе
rus_verbs:рехнуться{}, // рехнуться на старости лет
rus_verbs:расцвести{}, // расцвести на грядке
rus_verbs:закипеть{}, // закипеть на плите
rus_verbs:подлететь{}, // подлететь на параплане
rus_verbs:рыться{}, // рыться на свалке
rus_verbs:добираться{}, // добираться на попутках
rus_verbs:продержаться{}, // продержаться на вершине
rus_verbs:разыскивать{}, // разыскивать на выставках
rus_verbs:освобождать{}, // освобождать на заседании
rus_verbs:передвигаться{}, // передвигаться на самокате
rus_verbs:проявиться{}, // проявиться на свету
rus_verbs:заскользить{}, // заскользить на льду
rus_verbs:пересказать{}, // пересказать на сцене студенческого театра
rus_verbs:протестовать{}, // протестовать на улице
rus_verbs:указываться{}, // указываться на табличках
rus_verbs:прискакать{}, // прискакать на лошадке
rus_verbs:копошиться{}, // копошиться на свежем воздухе
rus_verbs:подсчитать{}, // подсчитать на бумажке
rus_verbs:разволноваться{}, // разволноваться на экзамене
rus_verbs:завертеться{}, // завертеться на полу
rus_verbs:ознакомиться{}, // ознакомиться на ходу
rus_verbs:ржать{}, // ржать на уроке
rus_verbs:раскинуть{}, // раскинуть на грядках
rus_verbs:разгромить{}, // разгромить на ринге
rus_verbs:подслушать{}, // подслушать на совещании
rus_verbs:описываться{}, // описываться на страницах книги
rus_verbs:качаться{}, // качаться на стуле
rus_verbs:усилить{}, // усилить на флангах
rus_verbs:набросать{}, // набросать на клочке картона
rus_verbs:расстреливать{}, // расстреливать на подходе
rus_verbs:запрыгать{}, // запрыгать на одной ноге
rus_verbs:сыскать{}, // сыскать на чужбине
rus_verbs:подтвердиться{}, // подтвердиться на практике
rus_verbs:плескаться{}, // плескаться на мелководье
rus_verbs:расширяться{}, // расширяться на конце
rus_verbs:подержать{}, // подержать на солнце
rus_verbs:планироваться{}, // планироваться на общем собрании
rus_verbs:сгинуть{}, // сгинуть на чужбине
rus_verbs:замкнуться{}, // замкнуться на точке
rus_verbs:закачаться{}, // закачаться на ветру
rus_verbs:перечитывать{}, // перечитывать на ходу
rus_verbs:перелететь{}, // перелететь на дельтаплане
rus_verbs:оживать{}, // оживать на солнце
rus_verbs:женить{}, // женить на богатой невесте
rus_verbs:заглохнуть{}, // заглохнуть на старте
rus_verbs:копаться{}, // копаться на полу
rus_verbs:развлекаться{}, // развлекаться на дискотеке
rus_verbs:печататься{}, // печататься на струйном принтере
rus_verbs:обрываться{}, // обрываться на полуслове
rus_verbs:ускакать{}, // ускакать на лошадке
rus_verbs:подписывать{}, // подписывать на столе
rus_verbs:добывать{}, // добывать на выработке
rus_verbs:скопиться{}, // скопиться на выходе
rus_verbs:повстречать{}, // повстречать на пути
rus_verbs:поцеловаться{}, // поцеловаться на площади
rus_verbs:растянуть{}, // растянуть на столе
rus_verbs:подаваться{}, // подаваться на благотворительном обеде
rus_verbs:повстречаться{}, // повстречаться на митинге
rus_verbs:примоститься{}, // примоститься на ступеньках
rus_verbs:отразить{}, // отразить на страницах доклада
rus_verbs:пояснять{}, // пояснять на страницах приложения
rus_verbs:накормить{}, // накормить на кухне
rus_verbs:поужинать{}, // поужинать на веранде
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге
деепричастие:спев{},
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить на мелководье
rus_verbs:освоить{}, // освоить на практике
rus_verbs:распластаться{}, // распластаться на травке
rus_verbs:отплыть{}, // отплыть на старом каяке
rus_verbs:улетать{}, // улетать на любом самолете
rus_verbs:отстаивать{}, // отстаивать на корте
rus_verbs:осуждать{}, // осуждать на словах
rus_verbs:переговорить{}, // переговорить на обеде
rus_verbs:укрыть{}, // укрыть на чердаке
rus_verbs:томиться{}, // томиться на привязи
rus_verbs:сжигать{}, // сжигать на полигоне
rus_verbs:позавтракать{}, // позавтракать на лоне природы
rus_verbs:функционировать{}, // функционирует на солнечной энергии
rus_verbs:разместить{}, // разместить на сайте
rus_verbs:пронести{}, // пронести на теле
rus_verbs:нашарить{}, // нашарить на столе
rus_verbs:корчиться{}, // корчиться на полу
rus_verbs:распознать{}, // распознать на снимке
rus_verbs:повеситься{}, // повеситься на шнуре
rus_verbs:обозначиться{}, // обозначиться на картах
rus_verbs:оступиться{}, // оступиться на скользком льду
rus_verbs:подносить{}, // подносить на блюдечке
rus_verbs:расстелить{}, // расстелить на газоне
rus_verbs:обсуждаться{}, // обсуждаться на собрании
rus_verbs:расписаться{}, // расписаться на бланке
rus_verbs:плестись{}, // плестись на привязи
rus_verbs:объявиться{}, // объявиться на сцене
rus_verbs:повышаться{}, // повышаться на первом датчике
rus_verbs:разрабатывать{}, // разрабатывать на заводе
rus_verbs:прерывать{}, // прерывать на середине
rus_verbs:каяться{}, // каяться на публике
rus_verbs:освоиться{}, // освоиться на лошади
rus_verbs:подплыть{}, // подплыть на плоту
rus_verbs:оскорбить{}, // оскорбить на митинге
rus_verbs:торжествовать{}, // торжествовать на пьедестале
rus_verbs:поправлять{}, // поправлять на одежде
rus_verbs:отражать{}, // отражать на картине
rus_verbs:дремать{}, // дремать на кушетке
rus_verbs:применяться{}, // применяться на производстве стали
rus_verbs:поражать{}, // поражать на большой дистанции
rus_verbs:расстрелять{}, // расстрелять на окраине хутора
rus_verbs:рассчитать{}, // рассчитать на калькуляторе
rus_verbs:записывать{}, // записывать на ленте
rus_verbs:перебирать{}, // перебирать на ладони
rus_verbs:разбиться{}, // разбиться на катере
rus_verbs:поискать{}, // поискать на ферме
rus_verbs:прятать{}, // прятать на заброшенном складе
rus_verbs:пропеть{}, // пропеть на эстраде
rus_verbs:замелькать{}, // замелькать на экране
rus_verbs:грустить{}, // грустить на веранде
rus_verbs:крутить{}, // крутить на оси
rus_verbs:подготовить{}, // подготовить на конспиративной квартире
rus_verbs:различать{}, // различать на картинке
rus_verbs:киснуть{}, // киснуть на чужбине
rus_verbs:оборваться{}, // оборваться на полуслове
rus_verbs:запутаться{}, // запутаться на простейшем тесте
rus_verbs:общаться{}, // общаться на уроке
rus_verbs:производиться{}, // производиться на фабрике
rus_verbs:сочинить{}, // сочинить на досуге
rus_verbs:давить{}, // давить на лице
rus_verbs:разработать{}, // разработать на секретном предприятии
rus_verbs:качать{}, // качать на качелях
rus_verbs:тушить{}, // тушить на крыше пожар
rus_verbs:охранять{}, // охранять на территории базы
rus_verbs:приметить{}, // приметить на взгорке
rus_verbs:скрыть{}, // скрыть на теле
rus_verbs:удерживать{}, // удерживать на руке
rus_verbs:усвоить{}, // усвоить на уроке
rus_verbs:растаять{}, // растаять на солнечной стороне
rus_verbs:красоваться{}, // красоваться на виду
rus_verbs:сохраняться{}, // сохраняться на холоде
rus_verbs:лечить{}, // лечить на дому
rus_verbs:прокатиться{}, // прокатиться на уницикле
rus_verbs:договариваться{}, // договариваться на нейтральной территории
rus_verbs:качнуться{}, // качнуться на одной ноге
rus_verbs:опубликовать{}, // опубликовать на сайте
rus_verbs:отражаться{}, // отражаться на поверхности воды
rus_verbs:обедать{}, // обедать на веранде
rus_verbs:посидеть{}, // посидеть на лавочке
rus_verbs:сообщаться{}, // сообщаться на официальном сайте
rus_verbs:свершиться{}, // свершиться на заседании
rus_verbs:ночевать{}, // ночевать на даче
rus_verbs:темнеть{}, // темнеть на свету
rus_verbs:гибнуть{}, // гибнуть на территории полигона
rus_verbs:усиливаться{}, // усиливаться на территории округа
rus_verbs:проживать{}, // проживать на даче
rus_verbs:исследовать{}, // исследовать на большой глубине
rus_verbs:обитать{}, // обитать на громадной глубине
rus_verbs:сталкиваться{}, // сталкиваться на большой высоте
rus_verbs:таиться{}, // таиться на большой глубине
rus_verbs:спасать{}, // спасать на пожаре
rus_verbs:сказываться{}, // сказываться на общем результате
rus_verbs:заблудиться{}, // заблудиться на стройке
rus_verbs:пошарить{}, // пошарить на полках
rus_verbs:планировать{}, // планировать на бумаге
rus_verbs:ранить{}, // ранить на полигоне
rus_verbs:хлопать{}, // хлопать на сцене
rus_verbs:основать{}, // основать на горе новый монастырь
rus_verbs:отбить{}, // отбить на столе
rus_verbs:отрицать{}, // отрицать на заседании комиссии
rus_verbs:устоять{}, // устоять на ногах
rus_verbs:отзываться{}, // отзываться на страницах отчёта
rus_verbs:притормозить{}, // притормозить на обочине
rus_verbs:читаться{}, // читаться на лице
rus_verbs:заиграть{}, // заиграть на саксофоне
rus_verbs:зависнуть{}, // зависнуть на игровой площадке
rus_verbs:сознаться{}, // сознаться на допросе
rus_verbs:выясняться{}, // выясняться на очной ставке
rus_verbs:наводить{}, // наводить на столе порядок
rus_verbs:покоиться{}, // покоиться на кладбище
rus_verbs:значиться{}, // значиться на бейджике
rus_verbs:съехать{}, // съехать на санках
rus_verbs:познакомить{}, // познакомить на свадьбе
rus_verbs:завязать{}, // завязать на спине
rus_verbs:грохнуть{}, // грохнуть на площади
rus_verbs:разъехаться{}, // разъехаться на узкой дороге
rus_verbs:столпиться{}, // столпиться на крыльце
rus_verbs:порыться{}, // порыться на полках
rus_verbs:ослабить{}, // ослабить на шее
rus_verbs:оправдывать{}, // оправдывать на суде
rus_verbs:обнаруживаться{}, // обнаруживаться на складе
rus_verbs:спастись{}, // спастись на дереве
rus_verbs:прерваться{}, // прерваться на полуслове
rus_verbs:строиться{}, // строиться на пустыре
rus_verbs:познать{}, // познать на практике
rus_verbs:путешествовать{}, // путешествовать на поезде
rus_verbs:побеждать{}, // побеждать на ринге
rus_verbs:рассматриваться{}, // рассматриваться на заседании
rus_verbs:продаваться{}, // продаваться на открытом рынке
rus_verbs:разместиться{}, // разместиться на базе
rus_verbs:завыть{}, // завыть на холме
rus_verbs:настигнуть{}, // настигнуть на окраине
rus_verbs:укрыться{}, // укрыться на чердаке
rus_verbs:расплакаться{}, // расплакаться на заседании комиссии
rus_verbs:заканчивать{}, // заканчивать на последнем задании
rus_verbs:пролежать{}, // пролежать на столе
rus_verbs:громоздиться{}, // громоздиться на полу
rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе
rus_verbs:поскользнуться{}, // поскользнуться на льду
rus_verbs:таскать{}, // таскать на спине
rus_verbs:просматривать{}, // просматривать на сайте
rus_verbs:обдумать{}, // обдумать на досуге
rus_verbs:гадать{}, // гадать на кофейной гуще
rus_verbs:останавливать{}, // останавливать на выходе
rus_verbs:обозначать{}, // обозначать на странице
rus_verbs:долететь{}, // долететь на спортивном байке
rus_verbs:тесниться{}, // тесниться на чердачке
rus_verbs:хоронить{}, // хоронить на частном кладбище
rus_verbs:установиться{}, // установиться на юге
rus_verbs:прикидывать{}, // прикидывать на клочке бумаги
rus_verbs:затаиться{}, // затаиться на дереве
rus_verbs:раздобыть{}, // раздобыть на складе
rus_verbs:перебросить{}, // перебросить на вертолетах
rus_verbs:захватывать{}, // захватывать на базе
rus_verbs:сказаться{}, // сказаться на итоговых оценках
rus_verbs:покачиваться{}, // покачиваться на волнах
rus_verbs:крутиться{}, // крутиться на кухне
rus_verbs:помещаться{}, // помещаться на полке
rus_verbs:питаться{}, // питаться на помойке
rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле
rus_verbs:кататься{}, // кататься на велике
rus_verbs:поработать{}, // поработать на стройке
rus_verbs:ограбить{}, // ограбить на пустыре
rus_verbs:зарабатывать{}, // зарабатывать на бирже
rus_verbs:преуспеть{}, // преуспеть на ниве искусства
rus_verbs:заерзать{}, // заерзать на стуле
rus_verbs:разъяснить{}, // разъяснить на полях
rus_verbs:отчеканить{}, // отчеканить на медной пластине
rus_verbs:торговать{}, // торговать на рынке
rus_verbs:поколебаться{}, // поколебаться на пороге
rus_verbs:прикинуть{}, // прикинуть на бумажке
rus_verbs:рассечь{}, // рассечь на тупом конце
rus_verbs:посмеяться{}, // посмеяться на переменке
rus_verbs:остыть{}, // остыть на морозном воздухе
rus_verbs:запереться{}, // запереться на чердаке
rus_verbs:обогнать{}, // обогнать на повороте
rus_verbs:подтянуться{}, // подтянуться на турнике
rus_verbs:привозить{}, // привозить на машине
rus_verbs:подбирать{}, // подбирать на полу
rus_verbs:уничтожать{}, // уничтожать на подходе
rus_verbs:притаиться{}, // притаиться на вершине
rus_verbs:плясать{}, // плясать на костях
rus_verbs:поджидать{}, // поджидать на вокзале
rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!)
rus_verbs:смениться{}, // смениться на посту
rus_verbs:посчитать{}, // посчитать на пальцах
rus_verbs:прицелиться{}, // прицелиться на бегу
rus_verbs:нарисовать{}, // нарисовать на стене
rus_verbs:прыгать{}, // прыгать на сцене
rus_verbs:повертеть{}, // повертеть на пальце
rus_verbs:попрощаться{}, // попрощаться на панихиде
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване
rus_verbs:разобрать{}, // разобрать на столе
rus_verbs:помереть{}, // помереть на чужбине
rus_verbs:различить{}, // различить на нечеткой фотографии
rus_verbs:рисовать{}, // рисовать на доске
rus_verbs:проследить{}, // проследить на экране
rus_verbs:задремать{}, // задремать на диване
rus_verbs:ругаться{}, // ругаться на людях
rus_verbs:сгореть{}, // сгореть на работе
rus_verbs:зазвучать{}, // зазвучать на коротких волнах
rus_verbs:задохнуться{}, // задохнуться на вершине горы
rus_verbs:порождать{}, // порождать на поверхности небольшую рябь
rus_verbs:отдыхать{}, // отдыхать на курорте
rus_verbs:образовать{}, // образовать на дне толстый слой
rus_verbs:поправиться{}, // поправиться на дармовых харчах
rus_verbs:отмечать{}, // отмечать на календаре
rus_verbs:реять{}, // реять на флагштоке
rus_verbs:ползти{}, // ползти на коленях
rus_verbs:продавать{}, // продавать на аукционе
rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче
rus_verbs:рыскать{}, // мышки рыскали на кухне
rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы
rus_verbs:напасть{}, // напасть на территории другого государства
rus_verbs:издать{}, // издать на западе
rus_verbs:оставаться{}, // оставаться на страже порядка
rus_verbs:появиться{}, // наконец появиться на экране
rus_verbs:лежать{}, // лежать на столе
rus_verbs:ждать{}, // ждать на берегу
инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге
глагол:писать{aux stress="пис^ать"},
rus_verbs:оказываться{}, // оказываться на полу
rus_verbs:поставить{}, // поставить на столе
rus_verbs:держать{}, // держать на крючке
rus_verbs:выходить{}, // выходить на остановке
rus_verbs:заговорить{}, // заговорить на китайском языке
rus_verbs:ожидать{}, // ожидать на стоянке
rus_verbs:закричать{}, // закричал на минарете муэдзин
rus_verbs:простоять{}, // простоять на посту
rus_verbs:продолжить{}, // продолжить на первом этаже
rus_verbs:ощутить{}, // ощутить на себе влияние кризиса
rus_verbs:состоять{}, // состоять на учете
rus_verbs:готовиться{},
инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте
глагол:акклиматизироваться{вид:несоверш},
rus_verbs:арестовать{}, // грабители были арестованы на месте преступления
rus_verbs:схватить{}, // грабители были схвачены на месте преступления
инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{ вид:соверш },
прилагательное:атаковавший{ вид:соверш },
rus_verbs:базировать{}, // установка будет базирована на границе
rus_verbs:базироваться{}, // установка базируется на границе
rus_verbs:барахтаться{}, // дети барахтались на мелководье
rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке
rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке
rus_verbs:бренчать{}, // парень что-то бренчал на гитаре
rus_verbs:бренькать{}, // парень что-то бренькает на гитаре
rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории.
rus_verbs:буксовать{}, // Колеса буксуют на льду
rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле
rus_verbs:взвести{}, // Боец взвел на оружии предохранитель
rus_verbs:вилять{}, // Машина сильно виляла на дороге
rus_verbs:висеть{}, // Яблоко висит на ветке
rus_verbs:возлежать{}, // возлежать на лежанке
rus_verbs:подниматься{}, // Мы поднимаемся на лифте
rus_verbs:подняться{}, // Мы поднимемся на лифте
rus_verbs:восседать{}, // Коля восседает на лошади
rus_verbs:воссиять{}, // Луна воссияла на небе
rus_verbs:воцариться{}, // Мир воцарился на всей земле
rus_verbs:воцаряться{}, // Мир воцаряется на всей земле
rus_verbs:вращать{}, // вращать на поясе
rus_verbs:вращаться{}, // вращаться на поясе
rus_verbs:встретить{}, // встретить друга на улице
rus_verbs:встретиться{}, // встретиться на занятиях
rus_verbs:встречать{}, // встречать на занятиях
rus_verbs:въебывать{}, // въебывать на работе
rus_verbs:въезжать{}, // въезжать на автомобиле
rus_verbs:въехать{}, // въехать на автомобиле
rus_verbs:выгорать{}, // ткань выгорает на солнце
rus_verbs:выгореть{}, // ткань выгорела на солнце
rus_verbs:выгравировать{}, // выгравировать на табличке надпись
rus_verbs:выжить{}, // выжить на необитаемом острове
rus_verbs:вылежаться{}, // помидоры вылежались на солнце
rus_verbs:вылеживаться{}, // вылеживаться на солнце
rus_verbs:выместить{}, // выместить на ком-то злобу
rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение
rus_verbs:вымещаться{}, // вымещаться на ком-то
rus_verbs:выращивать{}, // выращивать на грядке помидоры
rus_verbs:выращиваться{}, // выращиваться на грядке
инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись
глагол:вырезать{вид:соверш},
инфинитив:вырезать{вид:несоверш},
глагол:вырезать{вид:несоверш},
rus_verbs:вырисоваться{}, // вырисоваться на графике
rus_verbs:вырисовываться{}, // вырисовываться на графике
rus_verbs:высаживать{}, // высаживать на необитаемом острове
rus_verbs:высаживаться{}, // высаживаться на острове
rus_verbs:высвечивать{}, // высвечивать на дисплее температуру
rus_verbs:высвечиваться{}, // высвечиваться на дисплее
rus_verbs:выстроить{}, // выстроить на фундаменте
rus_verbs:выстроиться{}, // выстроиться на плацу
rus_verbs:выстудить{}, // выстудить на морозе
rus_verbs:выстудиться{}, // выстудиться на морозе
rus_verbs:выстужать{}, // выстужать на морозе
rus_verbs:выстуживать{}, // выстуживать на морозе
rus_verbs:выстуживаться{}, // выстуживаться на морозе
rus_verbs:выстукать{}, // выстукать на клавиатуре
rus_verbs:выстукивать{}, // выстукивать на клавиатуре
rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре
rus_verbs:выступать{}, // выступать на сцене
rus_verbs:выступить{}, // выступить на сцене
rus_verbs:выстучать{}, // выстучать на клавиатуре
rus_verbs:выстывать{}, // выстывать на морозе
rus_verbs:выстыть{}, // выстыть на морозе
rus_verbs:вытатуировать{}, // вытатуировать на руке якорь
rus_verbs:говорить{}, // говорить на повышенных тонах
rus_verbs:заметить{}, // заметить на берегу
rus_verbs:стоять{}, // твёрдо стоять на ногах
rus_verbs:оказаться{}, // оказаться на передовой линии
rus_verbs:почувствовать{}, // почувствовать на своей шкуре
rus_verbs:остановиться{}, // остановиться на первом пункте
rus_verbs:показаться{}, // показаться на горизонте
rus_verbs:чувствовать{}, // чувствовать на своей шкуре
rus_verbs:искать{}, // искать на открытом пространстве
rus_verbs:иметься{}, // иметься на складе
rus_verbs:клясться{}, // клясться на Коране
rus_verbs:прервать{}, // прервать на полуслове
rus_verbs:играть{}, // играть на чувствах
rus_verbs:спуститься{}, // спуститься на парашюте
rus_verbs:понадобиться{}, // понадобиться на экзамене
rus_verbs:служить{}, // служить на флоте
rus_verbs:подобрать{}, // подобрать на улице
rus_verbs:появляться{}, // появляться на сцене
rus_verbs:селить{}, // селить на чердаке
rus_verbs:поймать{}, // поймать на границе
rus_verbs:увидать{}, // увидать на опушке
rus_verbs:подождать{}, // подождать на перроне
rus_verbs:прочесть{}, // прочесть на полях
rus_verbs:тонуть{}, // тонуть на мелководье
rus_verbs:ощущать{}, // ощущать на коже
rus_verbs:отметить{}, // отметить на полях
rus_verbs:показывать{}, // показывать на графике
rus_verbs:разговаривать{}, // разговаривать на иностранном языке
rus_verbs:прочитать{}, // прочитать на сайте
rus_verbs:попробовать{}, // попробовать на практике
rus_verbs:замечать{}, // замечать на коже грязь
rus_verbs:нести{}, // нести на плечах
rus_verbs:носить{}, // носить на голове
rus_verbs:гореть{}, // гореть на работе
rus_verbs:застыть{}, // застыть на пороге
инфинитив:жениться{ вид:соверш }, // жениться на королеве
глагол:жениться{ вид:соверш },
прилагательное:женатый{},
прилагательное:женившийся{},
rus_verbs:спрятать{}, // спрятать на чердаке
rus_verbs:развернуться{}, // развернуться на плацу
rus_verbs:строить{}, // строить на песке
rus_verbs:устроить{}, // устроить на даче тестральный вечер
rus_verbs:настаивать{}, // настаивать на выполнении приказа
rus_verbs:находить{}, // находить на берегу
rus_verbs:мелькнуть{}, // мелькнуть на экране
rus_verbs:очутиться{}, // очутиться на опушке леса
инфинитив:использовать{вид:соверш}, // использовать на работе
глагол:использовать{вид:соверш},
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
прилагательное:использованный{},
прилагательное:использующий{},
прилагательное:использовавший{},
rus_verbs:лететь{}, // лететь на воздушном шаре
rus_verbs:смеяться{}, // смеяться на сцене
rus_verbs:ездить{}, // ездить на мопеде
rus_verbs:заснуть{}, // заснуть на диване
rus_verbs:застать{}, // застать на рабочем месте
rus_verbs:очнуться{}, // очнуться на больничной койке
rus_verbs:разглядеть{}, // разглядеть на фотографии
rus_verbs:обойти{}, // обойти на вираже
rus_verbs:удержаться{}, // удержаться на троне
rus_verbs:побывать{}, // побывать на другой планете
rus_verbs:заняться{}, // заняться на выходных делом
rus_verbs:вянуть{}, // вянуть на солнце
rus_verbs:постоять{}, // постоять на голове
rus_verbs:приобрести{}, // приобрести на распродаже
rus_verbs:попасться{}, // попасться на краже
rus_verbs:продолжаться{}, // продолжаться на земле
rus_verbs:открывать{}, // открывать на арене
rus_verbs:создавать{}, // создавать на сцене
rus_verbs:обсуждать{}, // обсуждать на кухне
rus_verbs:отыскать{}, // отыскать на полу
rus_verbs:уснуть{}, // уснуть на диване
rus_verbs:задержаться{}, // задержаться на работе
rus_verbs:курить{}, // курить на свежем воздухе
rus_verbs:приподняться{}, // приподняться на локтях
rus_verbs:установить{}, // установить на вершине
rus_verbs:запереть{}, // запереть на балконе
rus_verbs:синеть{}, // синеть на воздухе
rus_verbs:убивать{}, // убивать на нейтральной территории
rus_verbs:скрываться{}, // скрываться на даче
rus_verbs:родить{}, // родить на полу
rus_verbs:описать{}, // описать на страницах книги
rus_verbs:перехватить{}, // перехватить на подлете
rus_verbs:скрывать{}, // скрывать на даче
rus_verbs:сменить{}, // сменить на посту
rus_verbs:мелькать{}, // мелькать на экране
rus_verbs:присутствовать{}, // присутствовать на мероприятии
rus_verbs:украсть{}, // украсть на рынке
rus_verbs:победить{}, // победить на ринге
rus_verbs:упомянуть{}, // упомянуть на страницах романа
rus_verbs:плыть{}, // плыть на старой лодке
rus_verbs:повиснуть{}, // повиснуть на перекладине
rus_verbs:нащупать{}, // нащупать на дне
rus_verbs:затихнуть{}, // затихнуть на дне
rus_verbs:построить{}, // построить на участке
rus_verbs:поддерживать{}, // поддерживать на поверхности
rus_verbs:заработать{}, // заработать на бирже
rus_verbs:провалиться{}, // провалиться на экзамене
rus_verbs:сохранить{}, // сохранить на диске
rus_verbs:располагаться{}, // располагаться на софе
rus_verbs:поклясться{}, // поклясться на библии
rus_verbs:сражаться{}, // сражаться на арене
rus_verbs:спускаться{}, // спускаться на дельтаплане
rus_verbs:уничтожить{}, // уничтожить на подступах
rus_verbs:изучить{}, // изучить на практике
rus_verbs:рождаться{}, // рождаться на праздниках
rus_verbs:прилететь{}, // прилететь на самолете
rus_verbs:догнать{}, // догнать на перекрестке
rus_verbs:изобразить{}, // изобразить на бумаге
rus_verbs:проехать{}, // проехать на тракторе
rus_verbs:приготовить{}, // приготовить на масле
rus_verbs:споткнуться{}, // споткнуться на полу
rus_verbs:собирать{}, // собирать на берегу
rus_verbs:отсутствовать{}, // отсутствовать на тусовке
rus_verbs:приземлиться{}, // приземлиться на военном аэродроме
rus_verbs:сыграть{}, // сыграть на трубе
rus_verbs:прятаться{}, // прятаться на даче
rus_verbs:спрятаться{}, // спрятаться на чердаке
rus_verbs:провозгласить{}, // провозгласить на митинге
rus_verbs:изложить{}, // изложить на бумаге
rus_verbs:использоваться{}, // использоваться на практике
rus_verbs:замяться{}, // замяться на входе
rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота
rus_verbs:сверкнуть{}, // сверкнуть на солнце
rus_verbs:сверкать{}, // сверкать на свету
rus_verbs:задержать{}, // задержать на митинге
rus_verbs:осечься{}, // осечься на первом слове
rus_verbs:хранить{}, // хранить на банковском счету
rus_verbs:шутить{}, // шутить на уроке
rus_verbs:кружиться{}, // кружиться на балу
rus_verbs:чертить{}, // чертить на доске
rus_verbs:отразиться{}, // отразиться на оценках
rus_verbs:греть{}, // греть на солнце
rus_verbs:рассуждать{}, // рассуждать на страницах своей книги
rus_verbs:окружать{}, // окружать на острове
rus_verbs:сопровождать{}, // сопровождать на охоте
rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте
rus_verbs:содержаться{}, // содержаться на приусадебном участке
rus_verbs:поселиться{}, // поселиться на даче
rus_verbs:запеть{}, // запеть на сцене
инфинитив:провозить{ вид:несоверш }, // провозить на теле
глагол:провозить{ вид:несоверш },
прилагательное:провезенный{},
прилагательное:провозивший{вид:несоверш},
прилагательное:провозящий{вид:несоверш},
деепричастие:провозя{},
rus_verbs:мочить{}, // мочить на месте
rus_verbs:преследовать{}, // преследовать на территории другого штата
rus_verbs:пролететь{}, // пролетел на параплане
rus_verbs:драться{}, // драться на рапирах
rus_verbs:просидеть{}, // просидеть на занятиях
rus_verbs:убираться{}, // убираться на балконе
rus_verbs:таять{}, // таять на солнце
rus_verbs:проверять{}, // проверять на полиграфе
rus_verbs:убеждать{}, // убеждать на примере
rus_verbs:скользить{}, // скользить на льду
rus_verbs:приобретать{}, // приобретать на распродаже
rus_verbs:летать{}, // летать на метле
rus_verbs:толпиться{}, // толпиться на перроне
rus_verbs:плавать{}, // плавать на надувном матрасе
rus_verbs:описывать{}, // описывать на страницах повести
rus_verbs:пробыть{}, // пробыть на солнце слишком долго
rus_verbs:застрять{}, // застрять на верхнем этаже
rus_verbs:метаться{}, // метаться на полу
rus_verbs:сжечь{}, // сжечь на костре
rus_verbs:расслабиться{}, // расслабиться на кушетке
rus_verbs:услыхать{}, // услыхать на рынке
rus_verbs:удержать{}, // удержать на прежнем уровне
rus_verbs:образоваться{}, // образоваться на дне
rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа
rus_verbs:уезжать{}, // уезжать на попутке
rus_verbs:похоронить{}, // похоронить на закрытом кладбище
rus_verbs:настоять{}, // настоять на пересмотре оценок
rus_verbs:растянуться{}, // растянуться на горячем песке
rus_verbs:покрутить{}, // покрутить на шесте
rus_verbs:обнаружиться{}, // обнаружиться на болоте
rus_verbs:гулять{}, // гулять на свадьбе
rus_verbs:утонуть{}, // утонуть на курорте
rus_verbs:храниться{}, // храниться на депозите
rus_verbs:танцевать{}, // танцевать на свадьбе
rus_verbs:трудиться{}, // трудиться на заводе
инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати
глагол:засыпать{переходность:непереходный вид:несоверш},
деепричастие:засыпая{переходность:непереходный вид:несоверш},
прилагательное:засыпавший{переходность:непереходный вид:несоверш},
прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках
rus_verbs:сушить{}, // сушить на открытом воздухе
rus_verbs:зашевелиться{}, // зашевелиться на чердаке
rus_verbs:обдумывать{}, // обдумывать на досуге
rus_verbs:докладывать{}, // докладывать на научной конференции
rus_verbs:промелькнуть{}, // промелькнуть на экране
// прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории
прилагательное:написанный{}, // слово, написанное на заборе
rus_verbs:умещаться{}, // компьютер, умещающийся на ладони
rus_verbs:открыть{}, // книга, открытая на последней странице
rus_verbs:спать{}, // йог, спящий на гвоздях
rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте
rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте
rus_verbs:отобразиться{}, // удивление, отобразившееся на лице
rus_verbs:увидеть{}, // на полу я увидел чьи-то следы
rus_verbs:видеть{}, // на полу я вижу чьи-то следы
rus_verbs:оставить{}, // Мел оставил на доске белый след.
rus_verbs:оставлять{}, // Мел оставляет на доске белый след.
rus_verbs:встречаться{}, // встречаться на лекциях
rus_verbs:познакомиться{}, // познакомиться на занятиях
rus_verbs:устроиться{}, // она устроилась на кровати
rus_verbs:ложиться{}, // ложись на полу
rus_verbs:останавливаться{}, // останавливаться на достигнутом
rus_verbs:спотыкаться{}, // спотыкаться на ровном месте
rus_verbs:распечатать{}, // распечатать на бумаге
rus_verbs:распечатывать{}, // распечатывать на бумаге
rus_verbs:просмотреть{}, // просмотреть на бумаге
rus_verbs:закрепляться{}, // закрепляться на плацдарме
rus_verbs:погреться{}, // погреться на солнышке
rus_verbs:мешать{}, // Он мешал краски на палитре.
rus_verbs:занять{}, // Он занял первое место на соревнованиях.
rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках.
деепричастие:женившись{ вид:соверш },
rus_verbs:везти{}, // Он везёт песок на тачке.
прилагательное:казненный{}, // Он был казнён на электрическом стуле.
rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче.
rus_verbs:принести{}, // Официантка принесла нам обед на подносе.
rus_verbs:переписать{}, // Перепишите эту рукопись на машинке.
rus_verbs:идти{}, // Поезд идёт на малой скорости.
rus_verbs:петь{}, // птички поют на рассвете
rus_verbs:смотреть{}, // Смотри на обороте.
rus_verbs:прибрать{}, // прибрать на столе
rus_verbs:прибраться{}, // прибраться на столе
rus_verbs:растить{}, // растить капусту на огороде
rus_verbs:тащить{}, // тащить ребенка на руках
rus_verbs:убирать{}, // убирать на столе
rus_verbs:простыть{}, // Я простыл на морозе.
rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе.
rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде
rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках.
rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге.
rus_verbs:вскочить{}, // У него вскочил прыщ на носу.
rus_verbs:свить{}, // У нас на балконе воробей свил гнездо.
rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица.
rus_verbs:восходить{}, // Солнце восходит на востоке.
rus_verbs:блестеть{}, // Снег блестит на солнце.
rus_verbs:побить{}, // Рысак побил всех лошадей на скачках.
rus_verbs:литься{}, // Реки крови льются на войне.
rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах.
rus_verbs:клубиться{}, // Пыль клубится на дороге.
инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке
глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке.
// глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути
// инфинитив:находиться{вид:несоверш},
rus_verbs:жить{}, // Было интересно жить на курорте.
rus_verbs:повидать{}, // Он много повидал на своём веку.
rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду.
rus_verbs:расположиться{}, // Оба села расположились на берегу реки.
rus_verbs:объясняться{}, // Они объясняются на иностранном языке.
rus_verbs:прощаться{}, // Они долго прощались на вокзале.
rus_verbs:работать{}, // Она работает на ткацкой фабрике.
rus_verbs:купить{}, // Она купила молоко на рынке.
rus_verbs:поместиться{}, // Все книги поместились на полке.
глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике.
rus_verbs:пожить{}, // Недолго она пожила на свете.
rus_verbs:краснеть{}, // Небо краснеет на закате.
rus_verbs:бывать{}, // На Волге бывает сильное волнение.
rus_verbs:ехать{}, // Мы туда ехали на автобусе.
rus_verbs:провести{}, // Мы провели месяц на даче.
rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице.
rus_verbs:расти{}, // Арбузы растут теперь не только на юге.
ГЛ_ИНФ(сидеть), // три больших пса сидят на траве
ГЛ_ИНФ(сесть), // три больших пса сели на траву
ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль
ГЛ_ИНФ(повезти), // я повезу тебя на машине
ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси
ГЛ_ИНФ(пить), // пить на кухне чай
ГЛ_ИНФ(найти), // найти на острове
ГЛ_ИНФ(быть), // на этих костях есть следы зубов
ГЛ_ИНФ(высадиться), // помощники высадились на острове
ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове
ГЛ_ИНФ(случиться), // это случилось на опушке леса
ГЛ_ИНФ(продать),
ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: смотреть на youtube
fact гл_предл
{
if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} }
then return true
}
// локатив
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} }
then return true
}
#endregion ПРЕДЛОЖНЫЙ
#region ВИНИТЕЛЬНЫЙ
// НА+винительный падеж:
// ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ
#region VerbList
wordentry_set Гл_НА_Вин=
{
rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили.
rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку.
rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай.
rus_verbs:умножить{}, // Умножьте это количество примерно на 10.
//rus_verbs:умножать{},
rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу.
rus_verbs:откатывать{},
rus_verbs:доносить{}, // Вот и побежали на вас доносить.
rus_verbs:донести{},
rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
безлич_глагол:хватит{}, // - На одну атаку хватит.
rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты.
rus_verbs:поскупиться{}, // Не поскупись на похвалы!
rus_verbs:подыматься{},
rus_verbs:транспортироваться{},
rus_verbs:бахнуть{}, // Бахнуть стакан на пол
rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ)
rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ)
rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ)
rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ)
rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ)
rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ)
rus_verbs:БРЫЗГАТЬ{},
rus_verbs:БРЫЗНУТЬ{},
rus_verbs:КАПНУТЬ{},
rus_verbs:КАПАТЬ{},
rus_verbs:ПОКАПАТЬ{},
rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ)
rus_verbs:ОХОТИТЬСЯ{}, //
rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ)
rus_verbs:НАРВАТЬСЯ{}, //
rus_verbs:НАТОЛКНУТЬСЯ{}, //
rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ)
прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ)
rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ)
rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ)
rus_verbs:СТАЛКИВАТЬ{}, //
rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ)
rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ)
rus_verbs:ПЕРЕБРОСИТЬ{}, //
rus_verbs:НАБРАСЫВАТЬ{}, //
rus_verbs:НАБРОСИТЬ{}, //
rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ)
rus_verbs:СВОРАЧИВАТЬ{}, // //
rus_verbs:ПОВЕРНУТЬ{}, //
rus_verbs:ПОВОРАЧИВАТЬ{}, //
rus_verbs:наорать{},
rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ)
rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ)
rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:перегонять{},
rus_verbs:выгонять{},
rus_verbs:выгнать{},
rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ)
rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ)
rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ)
rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ)
rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций
rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин)
rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА)
// rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА)
rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА)
rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин)
rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА)
rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА)
rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин)
rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА)
rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА)
прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА)
rus_verbs:посыпаться{}, // на Нину посыпались снежинки
инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод.
глагол:нарезаться{ вид:несоверш },
rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу
rus_verbs:показать{}, // Вадим показал на Колю
rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА)
rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на)
rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА)
rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА)
rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на)
rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА)
rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА)
rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на)
rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на)
rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на)
rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на)
rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на)
rus_verbs:верить{}, // верить людям на слово (верить на слово)
rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру.
rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору.
rus_verbs:пасть{}, // Жребий пал на меня.
rus_verbs:ездить{}, // Вчера мы ездили на оперу.
rus_verbs:влезть{}, // Мальчик влез на дерево.
rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу.
rus_verbs:разбиться{}, // окно разбилось на мелкие осколки
rus_verbs:бежать{}, // я бегу на урок
rus_verbs:сбегаться{}, // сбегаться на происшествие
rus_verbs:присылать{}, // присылать на испытание
rus_verbs:надавить{}, // надавить на педать
rus_verbs:внести{}, // внести законопроект на рассмотрение
rus_verbs:вносить{}, // вносить законопроект на рассмотрение
rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов
rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров
rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова
rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек.
rus_verbs:оглядываться{}, // оглядываться на девушек
rus_verbs:расходиться{}, // расходиться на отдых
rus_verbs:поскакать{}, // поскакать на службу
rus_verbs:прыгать{}, // прыгать на сцену
rus_verbs:приглашать{}, // приглашать на обед
rus_verbs:рваться{}, // Кусок ткани рвется на части
rus_verbs:понестись{}, // понестись на волю
rus_verbs:распространяться{}, // распространяться на всех жителей штата
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш },
деепричастие:просыпавшись{}, деепричастие:просыпаясь{},
rus_verbs:заехать{}, // заехать на пандус
rus_verbs:разобрать{}, // разобрать на составляющие
rus_verbs:опускаться{}, // опускаться на колени
rus_verbs:переехать{}, // переехать на конспиративную квартиру
rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов
rus_verbs:поместить{}, // поместить на поднос
rus_verbs:отходить{}, // отходить на подготовленные позиции
rus_verbs:сыпаться{}, // сыпаться на плечи
rus_verbs:отвезти{}, // отвезти на занятия
rus_verbs:накинуть{}, // накинуть на плечи
rus_verbs:отлететь{}, // отлететь на пол
rus_verbs:закинуть{}, // закинуть на чердак
rus_verbs:зашипеть{}, // зашипеть на собаку
rus_verbs:прогреметь{}, // прогреметь на всю страну
rus_verbs:повалить{}, // повалить на стол
rus_verbs:опереть{}, // опереть на фундамент
rus_verbs:забросить{}, // забросить на антресоль
rus_verbs:подействовать{}, // подействовать на материал
rus_verbs:разделять{}, // разделять на части
rus_verbs:прикрикнуть{}, // прикрикнуть на детей
rus_verbs:разложить{}, // разложить на множители
rus_verbs:провожать{}, // провожать на работу
rus_verbs:катить{}, // катить на стройку
rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью
rus_verbs:сохранять{}, // сохранять на память
rus_verbs:злиться{}, // злиться на друга
rus_verbs:оборачиваться{}, // оборачиваться на свист
rus_verbs:сползти{}, // сползти на землю
rus_verbs:записывать{}, // записывать на ленту
rus_verbs:загнать{}, // загнать на дерево
rus_verbs:забормотать{}, // забормотать на ухо
rus_verbs:протиснуться{}, // протиснуться на самый край
rus_verbs:заторопиться{}, // заторопиться на вручение премии
rus_verbs:гаркнуть{}, // гаркнуть на шалунов
rus_verbs:навалиться{}, // навалиться на виновника всей толпой
rus_verbs:проскользнуть{}, // проскользнуть на крышу дома
rus_verbs:подтянуть{}, // подтянуть на палубу
rus_verbs:скатиться{}, // скатиться на двойки
rus_verbs:давить{}, // давить на жалость
rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства
rus_verbs:замахнуться{}, // замахнуться на святое
rus_verbs:заменить{}, // заменить на свежую салфетку
rus_verbs:свалить{}, // свалить на землю
rus_verbs:стекать{}, // стекать на оголенные провода
rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов
rus_verbs:развалиться{}, // развалиться на части
rus_verbs:сердиться{}, // сердиться на товарища
rus_verbs:обронить{}, // обронить на пол
rus_verbs:подсесть{}, // подсесть на наркоту
rus_verbs:реагировать{}, // реагировать на импульсы
rus_verbs:отпускать{}, // отпускать на волю
rus_verbs:прогнать{}, // прогнать на рабочее место
rus_verbs:ложить{}, // ложить на стол
rus_verbs:рвать{}, // рвать на части
rus_verbs:разлететься{}, // разлететься на кусочки
rus_verbs:превышать{}, // превышать на существенную величину
rus_verbs:сбиться{}, // сбиться на рысь
rus_verbs:пристроиться{}, // пристроиться на хорошую работу
rus_verbs:удрать{}, // удрать на пастбище
rus_verbs:толкать{}, // толкать на преступление
rus_verbs:посматривать{}, // посматривать на экран
rus_verbs:набирать{}, // набирать на судно
rus_verbs:отступать{}, // отступать на дерево
rus_verbs:подуть{}, // подуть на молоко
rus_verbs:плеснуть{}, // плеснуть на голову
rus_verbs:соскользнуть{}, // соскользнуть на землю
rus_verbs:затаить{}, // затаить на кого-то обиду
rus_verbs:обижаться{}, // обижаться на Колю
rus_verbs:смахнуть{}, // смахнуть на пол
rus_verbs:застегнуть{}, // застегнуть на все пуговицы
rus_verbs:спускать{}, // спускать на землю
rus_verbs:греметь{}, // греметь на всю округу
rus_verbs:скосить{}, // скосить на соседа глаз
rus_verbs:отважиться{}, // отважиться на прыжок
rus_verbs:литься{}, // литься на землю
rus_verbs:порвать{}, // порвать на тряпки
rus_verbs:проследовать{}, // проследовать на сцену
rus_verbs:надевать{}, // надевать на голову
rus_verbs:проскочить{}, // проскочить на красный свет
rus_verbs:прилечь{}, // прилечь на диванчик
rus_verbs:разделиться{}, // разделиться на небольшие группы
rus_verbs:завыть{}, // завыть на луну
rus_verbs:переносить{}, // переносить на другую машину
rus_verbs:наговорить{}, // наговорить на сотню рублей
rus_verbs:намекать{}, // намекать на новые обстоятельства
rus_verbs:нападать{}, // нападать на охранников
rus_verbs:убегать{}, // убегать на другое место
rus_verbs:тратить{}, // тратить на развлечения
rus_verbs:присаживаться{}, // присаживаться на корточки
rus_verbs:переместиться{}, // переместиться на вторую линию
rus_verbs:завалиться{}, // завалиться на диван
rus_verbs:удалиться{}, // удалиться на покой
rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов
rus_verbs:обрушить{}, // обрушить на голову
rus_verbs:резать{}, // резать на части
rus_verbs:умчаться{}, // умчаться на юг
rus_verbs:навернуться{}, // навернуться на камень
rus_verbs:примчаться{}, // примчаться на матч
rus_verbs:издавать{}, // издавать на собственные средства
rus_verbs:переключить{}, // переключить на другой язык
rus_verbs:отправлять{}, // отправлять на пенсию
rus_verbs:залечь{}, // залечь на дно
rus_verbs:установиться{}, // установиться на диск
rus_verbs:направлять{}, // направлять на дополнительное обследование
rus_verbs:разрезать{}, // разрезать на части
rus_verbs:оскалиться{}, // оскалиться на прохожего
rus_verbs:рычать{}, // рычать на пьяных
rus_verbs:погружаться{}, // погружаться на дно
rus_verbs:опираться{}, // опираться на костыли
rus_verbs:поторопиться{}, // поторопиться на учебу
rus_verbs:сдвинуться{}, // сдвинуться на сантиметр
rus_verbs:увеличить{}, // увеличить на процент
rus_verbs:опускать{}, // опускать на землю
rus_verbs:созвать{}, // созвать на митинг
rus_verbs:делить{}, // делить на части
rus_verbs:пробиться{}, // пробиться на заключительную часть
rus_verbs:простираться{}, // простираться на много миль
rus_verbs:забить{}, // забить на учебу
rus_verbs:переложить{}, // переложить на чужие плечи
rus_verbs:грохнуться{}, // грохнуться на землю
rus_verbs:прорваться{}, // прорваться на сцену
rus_verbs:разлить{}, // разлить на землю
rus_verbs:укладываться{}, // укладываться на ночевку
rus_verbs:уволить{}, // уволить на пенсию
rus_verbs:наносить{}, // наносить на кожу
rus_verbs:набежать{}, // набежать на берег
rus_verbs:заявиться{}, // заявиться на стрельбище
rus_verbs:налиться{}, // налиться на крышку
rus_verbs:надвигаться{}, // надвигаться на берег
rus_verbs:распустить{}, // распустить на каникулы
rus_verbs:переключиться{}, // переключиться на другую задачу
rus_verbs:чихнуть{}, // чихнуть на окружающих
rus_verbs:шлепнуться{}, // шлепнуться на спину
rus_verbs:устанавливать{}, // устанавливать на крышу
rus_verbs:устанавливаться{}, // устанавливаться на крышу
rus_verbs:устраиваться{}, // устраиваться на работу
rus_verbs:пропускать{}, // пропускать на стадион
инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш },
деепричастие:сбегав{}, деепричастие:сбегая{},
rus_verbs:показываться{}, // показываться на глаза
rus_verbs:прибегать{}, // прибегать на урок
rus_verbs:съездить{}, // съездить на ферму
rus_verbs:прославиться{}, // прославиться на всю страну
rus_verbs:опрокинуться{}, // опрокинуться на спину
rus_verbs:насыпать{}, // насыпать на землю
rus_verbs:употреблять{}, // употреблять на корм скоту
rus_verbs:пристроить{}, // пристроить на работу
rus_verbs:заворчать{}, // заворчать на вошедшего
rus_verbs:завязаться{}, // завязаться на поставщиков
rus_verbs:сажать{}, // сажать на стул
rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры
rus_verbs:заменять{}, // заменять на исправную
rus_verbs:нацепить{}, // нацепить на голову
rus_verbs:сыпать{}, // сыпать на землю
rus_verbs:закрываться{}, // закрываться на ремонт
rus_verbs:распространиться{}, // распространиться на всю популяцию
rus_verbs:поменять{}, // поменять на велосипед
rus_verbs:пересесть{}, // пересесть на велосипеды
rus_verbs:подоспеть{}, // подоспеть на разбор
rus_verbs:шипеть{}, // шипеть на собак
rus_verbs:поделить{}, // поделить на части
rus_verbs:подлететь{}, // подлететь на расстояние выстрела
rus_verbs:нажимать{}, // нажимать на все кнопки
rus_verbs:распасться{}, // распасться на части
rus_verbs:приволочь{}, // приволочь на диван
rus_verbs:пожить{}, // пожить на один доллар
rus_verbs:устремляться{}, // устремляться на свободу
rus_verbs:смахивать{}, // смахивать на пол
rus_verbs:забежать{}, // забежать на обед
rus_verbs:увеличиться{}, // увеличиться на существенную величину
rus_verbs:прокрасться{}, // прокрасться на склад
rus_verbs:пущать{}, // пущать на постой
rus_verbs:отклонить{}, // отклонить на несколько градусов
rus_verbs:насмотреться{}, // насмотреться на безобразия
rus_verbs:настроить{}, // настроить на короткие волны
rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров
rus_verbs:поменяться{}, // поменяться на другую книжку
rus_verbs:расколоться{}, // расколоться на части
rus_verbs:разлиться{}, // разлиться на землю
rus_verbs:срываться{}, // срываться на жену
rus_verbs:осудить{}, // осудить на пожизненное заключение
rus_verbs:передвинуть{}, // передвинуть на первое место
rus_verbs:допускаться{}, // допускаться на полигон
rus_verbs:задвинуть{}, // задвинуть на полку
rus_verbs:повлиять{}, // повлиять на оценку
rus_verbs:отбавлять{}, // отбавлять на осмотр
rus_verbs:сбрасывать{}, // сбрасывать на землю
rus_verbs:накинуться{}, // накинуться на случайных прохожих
rus_verbs:пролить{}, // пролить на кожу руки
rus_verbs:затащить{}, // затащить на сеновал
rus_verbs:перебежать{}, // перебежать на сторону противника
rus_verbs:наливать{}, // наливать на скатерть
rus_verbs:пролезть{}, // пролезть на сцену
rus_verbs:откладывать{}, // откладывать на черный день
rus_verbs:распадаться{}, // распадаться на небольшие фрагменты
rus_verbs:перечислить{}, // перечислить на счет
rus_verbs:закачаться{}, // закачаться на верхний уровень
rus_verbs:накрениться{}, // накрениться на правый борт
rus_verbs:подвинуться{}, // подвинуться на один уровень
rus_verbs:разнести{}, // разнести на мелкие кусочки
rus_verbs:зажить{}, // зажить на широкую ногу
rus_verbs:оглохнуть{}, // оглохнуть на правое ухо
rus_verbs:посетовать{}, // посетовать на бюрократизм
rus_verbs:уводить{}, // уводить на осмотр
rus_verbs:ускакать{}, // ускакать на забег
rus_verbs:посветить{}, // посветить на стену
rus_verbs:разрываться{}, // разрываться на части
rus_verbs:побросать{}, // побросать на землю
rus_verbs:карабкаться{}, // карабкаться на скалу
rus_verbs:нахлынуть{}, // нахлынуть на кого-то
rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки
rus_verbs:среагировать{}, // среагировать на сигнал
rus_verbs:претендовать{}, // претендовать на приз
rus_verbs:дунуть{}, // дунуть на одуванчик
rus_verbs:переводиться{}, // переводиться на другую работу
rus_verbs:перевезти{}, // перевезти на другую площадку
rus_verbs:топать{}, // топать на урок
rus_verbs:относить{}, // относить на склад
rus_verbs:сбивать{}, // сбивать на землю
rus_verbs:укладывать{}, // укладывать на спину
rus_verbs:укатить{}, // укатить на отдых
rus_verbs:убирать{}, // убирать на полку
rus_verbs:опасть{}, // опасть на землю
rus_verbs:ронять{}, // ронять на снег
rus_verbs:пялиться{}, // пялиться на тело
rus_verbs:глазеть{}, // глазеть на тело
rus_verbs:снижаться{}, // снижаться на безопасную высоту
rus_verbs:запрыгнуть{}, // запрыгнуть на платформу
rus_verbs:разбиваться{}, // разбиваться на главы
rus_verbs:сгодиться{}, // сгодиться на фарш
rus_verbs:перескочить{}, // перескочить на другую страницу
rus_verbs:нацелиться{}, // нацелиться на главную добычу
rus_verbs:заезжать{}, // заезжать на бордюр
rus_verbs:забираться{}, // забираться на крышу
rus_verbs:проорать{}, // проорать на всё село
rus_verbs:сбежаться{}, // сбежаться на шум
rus_verbs:сменять{}, // сменять на хлеб
rus_verbs:мотать{}, // мотать на ус
rus_verbs:раскалываться{}, // раскалываться на две половинки
rus_verbs:коситься{}, // коситься на режиссёра
rus_verbs:плевать{}, // плевать на законы
rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение
rus_verbs:наставить{}, // наставить на путь истинный
rus_verbs:завывать{}, // завывать на Луну
rus_verbs:опаздывать{}, // опаздывать на совещание
rus_verbs:залюбоваться{}, // залюбоваться на пейзаж
rus_verbs:повергнуть{}, // повергнуть на землю
rus_verbs:надвинуть{}, // надвинуть на лоб
rus_verbs:стекаться{}, // стекаться на площадь
rus_verbs:обозлиться{}, // обозлиться на тренера
rus_verbs:оттянуть{}, // оттянуть на себя
rus_verbs:истратить{}, // истратить на дешевых шлюх
rus_verbs:вышвырнуть{}, // вышвырнуть на улицу
rus_verbs:затолкать{}, // затолкать на верхнюю полку
rus_verbs:заскочить{}, // заскочить на огонек
rus_verbs:проситься{}, // проситься на улицу
rus_verbs:натыкаться{}, // натыкаться на борщевик
rus_verbs:обрушиваться{}, // обрушиваться на митингующих
rus_verbs:переписать{}, // переписать на чистовик
rus_verbs:переноситься{}, // переноситься на другое устройство
rus_verbs:напроситься{}, // напроситься на обидный ответ
rus_verbs:натягивать{}, // натягивать на ноги
rus_verbs:кидаться{}, // кидаться на прохожих
rus_verbs:откликаться{}, // откликаться на призыв
rus_verbs:поспевать{}, // поспевать на балет
rus_verbs:обратиться{}, // обратиться на кафедру
rus_verbs:полюбоваться{}, // полюбоваться на бюст
rus_verbs:таращиться{}, // таращиться на мустангов
rus_verbs:напороться{}, // напороться на колючки
rus_verbs:раздать{}, // раздать на руки
rus_verbs:дивиться{}, // дивиться на танцовщиц
rus_verbs:назначать{}, // назначать на ответственнейший пост
rus_verbs:кидать{}, // кидать на балкон
rus_verbs:нахлобучить{}, // нахлобучить на башку
rus_verbs:увлекать{}, // увлекать на луг
rus_verbs:ругнуться{}, // ругнуться на животину
rus_verbs:переселиться{}, // переселиться на хутор
rus_verbs:разрывать{}, // разрывать на части
rus_verbs:утащить{}, // утащить на дерево
rus_verbs:наставлять{}, // наставлять на путь
rus_verbs:соблазнить{}, // соблазнить на обмен
rus_verbs:накладывать{}, // накладывать на рану
rus_verbs:набрести{}, // набрести на грибную поляну
rus_verbs:наведываться{}, // наведываться на прежнюю работу
rus_verbs:погулять{}, // погулять на чужие деньги
rus_verbs:уклоняться{}, // уклоняться на два градуса влево
rus_verbs:слезать{}, // слезать на землю
rus_verbs:клевать{}, // клевать на мотыля
// rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:напялить{}, // напялить на голову
rus_verbs:натянуться{}, // натянуться на рамку
rus_verbs:разгневаться{}, // разгневаться на придворных
rus_verbs:эмигрировать{}, // эмигрировать на Кипр
rus_verbs:накатить{}, // накатить на основу
rus_verbs:пригнать{}, // пригнать на пастбище
rus_verbs:обречь{}, // обречь на мучения
rus_verbs:сокращаться{}, // сокращаться на четверть
rus_verbs:оттеснить{}, // оттеснить на пристань
rus_verbs:подбить{}, // подбить на аферу
rus_verbs:заманить{}, // заманить на дерево
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик
// деепричастие:пописав{ aux stress="поп^исать" },
rus_verbs:посходить{}, // посходить на перрон
rus_verbs:налечь{}, // налечь на мясцо
rus_verbs:отбирать{}, // отбирать на флот
rus_verbs:нашептывать{}, // нашептывать на ухо
rus_verbs:откладываться{}, // откладываться на будущее
rus_verbs:залаять{}, // залаять на грабителя
rus_verbs:настроиться{}, // настроиться на прием
rus_verbs:разбивать{}, // разбивать на куски
rus_verbs:пролиться{}, // пролиться на почву
rus_verbs:сетовать{}, // сетовать на объективные трудности
rus_verbs:подвезти{}, // подвезти на митинг
rus_verbs:припереться{}, // припереться на праздник
rus_verbs:подталкивать{}, // подталкивать на прыжок
rus_verbs:прорываться{}, // прорываться на сцену
rus_verbs:снижать{}, // снижать на несколько процентов
rus_verbs:нацелить{}, // нацелить на танк
rus_verbs:расколоть{}, // расколоть на два куска
rus_verbs:увозить{}, // увозить на обкатку
rus_verbs:оседать{}, // оседать на дно
rus_verbs:съедать{}, // съедать на ужин
rus_verbs:навлечь{}, // навлечь на себя
rus_verbs:равняться{}, // равняться на лучших
rus_verbs:сориентироваться{}, // сориентироваться на местности
rus_verbs:снизить{}, // снизить на несколько процентов
rus_verbs:перенестись{}, // перенестись на много лет назад
rus_verbs:завезти{}, // завезти на склад
rus_verbs:проложить{}, // проложить на гору
rus_verbs:понадеяться{}, // понадеяться на удачу
rus_verbs:заступить{}, // заступить на вахту
rus_verbs:засеменить{}, // засеменить на выход
rus_verbs:запирать{}, // запирать на ключ
rus_verbs:скатываться{}, // скатываться на землю
rus_verbs:дробить{}, // дробить на части
rus_verbs:разваливаться{}, // разваливаться на кусочки
rus_verbs:завозиться{}, // завозиться на склад
rus_verbs:нанимать{}, // нанимать на дневную работу
rus_verbs:поспеть{}, // поспеть на концерт
rus_verbs:променять{}, // променять на сытость
rus_verbs:переправить{}, // переправить на север
rus_verbs:налетать{}, // налетать на силовое поле
rus_verbs:затворить{}, // затворить на замок
rus_verbs:подогнать{}, // подогнать на пристань
rus_verbs:наехать{}, // наехать на камень
rus_verbs:распевать{}, // распевать на разные голоса
rus_verbs:разносить{}, // разносить на клочки
rus_verbs:преувеличивать{}, // преувеличивать на много килограммов
rus_verbs:хромать{}, // хромать на одну ногу
rus_verbs:телеграфировать{}, // телеграфировать на базу
rus_verbs:порезать{}, // порезать на лоскуты
rus_verbs:порваться{}, // порваться на части
rus_verbs:загонять{}, // загонять на дерево
rus_verbs:отбывать{}, // отбывать на место службы
rus_verbs:усаживаться{}, // усаживаться на трон
rus_verbs:накопить{}, // накопить на квартиру
rus_verbs:зыркнуть{}, // зыркнуть на визитера
rus_verbs:копить{}, // копить на машину
rus_verbs:помещать{}, // помещать на верхнюю грань
rus_verbs:сползать{}, // сползать на снег
rus_verbs:попроситься{}, // попроситься на улицу
rus_verbs:перетащить{}, // перетащить на чердак
rus_verbs:растащить{}, // растащить на сувениры
rus_verbs:ниспадать{}, // ниспадать на землю
rus_verbs:сфотографировать{}, // сфотографировать на память
rus_verbs:нагонять{}, // нагонять на конкурентов страх
rus_verbs:покушаться{}, // покушаться на понтифика
rus_verbs:покуситься{},
rus_verbs:наняться{}, // наняться на службу
rus_verbs:просачиваться{}, // просачиваться на поверхность
rus_verbs:пускаться{}, // пускаться на ветер
rus_verbs:отваживаться{}, // отваживаться на прыжок
rus_verbs:досадовать{}, // досадовать на объективные трудности
rus_verbs:унестись{}, // унестись на небо
rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов
rus_verbs:насадить{}, // насадить на копьё
rus_verbs:нагрянуть{}, // нагрянуть на праздник
rus_verbs:зашвырнуть{}, // зашвырнуть на полку
rus_verbs:грешить{}, // грешить на постояльцев
rus_verbs:просочиться{}, // просочиться на поверхность
rus_verbs:надоумить{}, // надоумить на глупость
rus_verbs:намотать{}, // намотать на шпиндель
rus_verbs:замкнуть{}, // замкнуть на корпус
rus_verbs:цыкнуть{}, // цыкнуть на детей
rus_verbs:переворачиваться{}, // переворачиваться на спину
rus_verbs:соваться{}, // соваться на площать
rus_verbs:отлучиться{}, // отлучиться на обед
rus_verbs:пенять{}, // пенять на себя
rus_verbs:нарезать{}, // нарезать на ломтики
rus_verbs:поставлять{}, // поставлять на Кипр
rus_verbs:залезать{}, // залезать на балкон
rus_verbs:отлучаться{}, // отлучаться на обед
rus_verbs:сбиваться{}, // сбиваться на шаг
rus_verbs:таращить{}, // таращить глаза на вошедшего
rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню
rus_verbs:опережать{}, // опережать на пару сантиметров
rus_verbs:переставить{}, // переставить на стол
rus_verbs:раздирать{}, // раздирать на части
rus_verbs:затвориться{}, // затвориться на засовы
rus_verbs:материться{}, // материться на кого-то
rus_verbs:наскочить{}, // наскочить на риф
rus_verbs:набираться{}, // набираться на борт
rus_verbs:покрикивать{}, // покрикивать на помощников
rus_verbs:заменяться{}, // заменяться на более новый
rus_verbs:подсадить{}, // подсадить на верхнюю полку
rus_verbs:проковылять{}, // проковылять на кухню
rus_verbs:прикатить{}, // прикатить на старт
rus_verbs:залететь{}, // залететь на чужую территорию
rus_verbs:загрузить{}, // загрузить на конвейер
rus_verbs:уплывать{}, // уплывать на материк
rus_verbs:опозорить{}, // опозорить на всю деревню
rus_verbs:провоцировать{}, // провоцировать на ответную агрессию
rus_verbs:забивать{}, // забивать на учебу
rus_verbs:набегать{}, // набегать на прибрежные деревни
rus_verbs:запираться{}, // запираться на ключ
rus_verbs:фотографировать{}, // фотографировать на мыльницу
rus_verbs:подымать{}, // подымать на недосягаемую высоту
rus_verbs:съезжаться{}, // съезжаться на симпозиум
rus_verbs:отвлекаться{}, // отвлекаться на игру
rus_verbs:проливать{}, // проливать на брюки
rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца
rus_verbs:уползти{}, // уползти на вершину холма
rus_verbs:переместить{}, // переместить на вторую палубу
rus_verbs:превысить{}, // превысить на несколько метров
rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку
rus_verbs:спровоцировать{}, // спровоцировать на бросок
rus_verbs:сместиться{}, // сместиться на соседнюю клетку
rus_verbs:заготовить{}, // заготовить на зиму
rus_verbs:плеваться{}, // плеваться на пол
rus_verbs:переселить{}, // переселить на север
rus_verbs:напирать{}, // напирать на дверь
rus_verbs:переезжать{}, // переезжать на другой этаж
rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров
rus_verbs:трогаться{}, // трогаться на красный свет
rus_verbs:надвинуться{}, // надвинуться на глаза
rus_verbs:засмотреться{}, // засмотреться на купальники
rus_verbs:убыть{}, // убыть на фронт
rus_verbs:передвигать{}, // передвигать на второй уровень
rus_verbs:отвозить{}, // отвозить на свалку
rus_verbs:обрекать{}, // обрекать на гибель
rus_verbs:записываться{}, // записываться на танцы
rus_verbs:настраивать{}, // настраивать на другой диапазон
rus_verbs:переписывать{}, // переписывать на диск
rus_verbs:израсходовать{}, // израсходовать на гонки
rus_verbs:обменять{}, // обменять на перспективного игрока
rus_verbs:трубить{}, // трубить на всю округу
rus_verbs:набрасываться{}, // набрасываться на жертву
rus_verbs:чихать{}, // чихать на правила
rus_verbs:наваливаться{}, // наваливаться на рычаг
rus_verbs:сподобиться{}, // сподобиться на повторный анализ
rus_verbs:намазать{}, // намазать на хлеб
rus_verbs:прореагировать{}, // прореагировать на вызов
rus_verbs:зачислить{}, // зачислить на факультет
rus_verbs:наведаться{}, // наведаться на склад
rus_verbs:откидываться{}, // откидываться на спинку кресла
rus_verbs:захромать{}, // захромать на левую ногу
rus_verbs:перекочевать{}, // перекочевать на другой берег
rus_verbs:накатываться{}, // накатываться на песчаный берег
rus_verbs:приостановить{}, // приостановить на некоторое время
rus_verbs:запрятать{}, // запрятать на верхнюю полочку
rus_verbs:прихрамывать{}, // прихрамывать на правую ногу
rus_verbs:упорхнуть{}, // упорхнуть на свободу
rus_verbs:расстегивать{}, // расстегивать на пальто
rus_verbs:напуститься{}, // напуститься на бродягу
rus_verbs:накатывать{}, // накатывать на оригинал
rus_verbs:наезжать{}, // наезжать на простофилю
rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека
rus_verbs:отрядить{}, // отрядить на починку
rus_verbs:положиться{}, // положиться на главаря
rus_verbs:опрокидывать{}, // опрокидывать на голову
rus_verbs:поторапливаться{}, // поторапливаться на рейс
rus_verbs:налагать{}, // налагать на заемщика
rus_verbs:скопировать{}, // скопировать на диск
rus_verbs:опадать{}, // опадать на землю
rus_verbs:купиться{}, // купиться на посулы
rus_verbs:гневаться{}, // гневаться на слуг
rus_verbs:слететься{}, // слететься на раздачу
rus_verbs:убавить{}, // убавить на два уровня
rus_verbs:спихнуть{}, // спихнуть на соседа
rus_verbs:накричать{}, // накричать на ребенка
rus_verbs:приберечь{}, // приберечь на ужин
rus_verbs:приклеить{}, // приклеить на ветровое стекло
rus_verbs:ополчиться{}, // ополчиться на посредников
rus_verbs:тратиться{}, // тратиться на сувениры
rus_verbs:слетаться{}, // слетаться на свет
rus_verbs:доставляться{}, // доставляться на базу
rus_verbs:поплевать{}, // поплевать на руки
rus_verbs:огрызаться{}, // огрызаться на замечание
rus_verbs:попереться{}, // попереться на рынок
rus_verbs:растягиваться{}, // растягиваться на полу
rus_verbs:повергать{}, // повергать на землю
rus_verbs:ловиться{}, // ловиться на мотыля
rus_verbs:наседать{}, // наседать на обороняющихся
rus_verbs:развалить{}, // развалить на кирпичи
rus_verbs:разломить{}, // разломить на несколько частей
rus_verbs:примерить{}, // примерить на себя
rus_verbs:лепиться{}, // лепиться на стену
rus_verbs:скопить{}, // скопить на старость
rus_verbs:затратить{}, // затратить на ликвидацию последствий
rus_verbs:притащиться{}, // притащиться на гулянку
rus_verbs:осерчать{}, // осерчать на прислугу
rus_verbs:натравить{}, // натравить на медведя
rus_verbs:ссыпать{}, // ссыпать на землю
rus_verbs:подвозить{}, // подвозить на пристань
rus_verbs:мобилизовать{}, // мобилизовать на сборы
rus_verbs:смотаться{}, // смотаться на работу
rus_verbs:заглядеться{}, // заглядеться на девчонок
rus_verbs:таскаться{}, // таскаться на работу
rus_verbs:разгружать{}, // разгружать на транспортер
rus_verbs:потреблять{}, // потреблять на кондиционирование
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу
деепричастие:сгоняв{},
rus_verbs:посылаться{}, // посылаться на разведку
rus_verbs:окрыситься{}, // окрыситься на кого-то
rus_verbs:отлить{}, // отлить на сковороду
rus_verbs:шикнуть{}, // шикнуть на детишек
rus_verbs:уповать{}, // уповать на бескорысную помощь
rus_verbs:класться{}, // класться на стол
rus_verbs:поковылять{}, // поковылять на выход
rus_verbs:навевать{}, // навевать на собравшихся скуку
rus_verbs:накладываться{}, // накладываться на грунтовку
rus_verbs:наноситься{}, // наноситься на чистую кожу
// rus_verbs:запланировать{}, // запланировать на среду
rus_verbs:кувыркнуться{}, // кувыркнуться на землю
rus_verbs:гавкнуть{}, // гавкнуть на хозяина
rus_verbs:перестроиться{}, // перестроиться на новый лад
rus_verbs:расходоваться{}, // расходоваться на образование
rus_verbs:дуться{}, // дуться на бабушку
rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол
rus_verbs:издаться{}, // издаться на деньги спонсоров
rus_verbs:смещаться{}, // смещаться на несколько миллиметров
rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу
rus_verbs:пикировать{}, // пикировать на окопы
rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей
rus_verbs:зудить{}, // зудить на ухо
rus_verbs:подразделяться{}, // подразделяться на группы
rus_verbs:изливаться{}, // изливаться на землю
rus_verbs:помочиться{}, // помочиться на траву
rus_verbs:примерять{}, // примерять на себя
rus_verbs:разрядиться{}, // разрядиться на землю
rus_verbs:мотнуться{}, // мотнуться на крышу
rus_verbs:налегать{}, // налегать на весла
rus_verbs:зацокать{}, // зацокать на куриц
rus_verbs:наниматься{}, // наниматься на корабль
rus_verbs:сплевывать{}, // сплевывать на землю
rus_verbs:настучать{}, // настучать на саботажника
rus_verbs:приземляться{}, // приземляться на брюхо
rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности
rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу
rus_verbs:серчать{}, // серчать на нерасторопную помощницу
rus_verbs:сваливать{}, // сваливать на подоконник
rus_verbs:засобираться{}, // засобираться на работу
rus_verbs:распилить{}, // распилить на одинаковые бруски
//rus_verbs:умножать{}, // умножать на константу
rus_verbs:копировать{}, // копировать на диск
rus_verbs:накрутить{}, // накрутить на руку
rus_verbs:навалить{}, // навалить на телегу
rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль
rus_verbs:шлепаться{}, // шлепаться на бетон
rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства
rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение
rus_verbs:посягнуть{}, // посягнуть на святое
rus_verbs:разменять{}, // разменять на мелочь
rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции
rus_verbs:усаживать{}, // усаживать на скамейку
rus_verbs:натаскать{}, // натаскать на поиск наркотиков
rus_verbs:зашикать{}, // зашикать на кошку
rus_verbs:разломать{}, // разломать на равные части
rus_verbs:приглашаться{}, // приглашаться на сцену
rus_verbs:присягать{}, // присягать на верность
rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку
rus_verbs:расщедриться{}, // расщедриться на новый компьютер
rus_verbs:насесть{}, // насесть на двоечников
rus_verbs:созывать{}, // созывать на собрание
rus_verbs:позариться{}, // позариться на чужое добро
rus_verbs:перекидываться{}, // перекидываться на соседние здания
rus_verbs:наползать{}, // наползать на неповрежденную ткань
rus_verbs:изрубить{}, // изрубить на мелкие кусочки
rus_verbs:наворачиваться{}, // наворачиваться на глаза
rus_verbs:раскричаться{}, // раскричаться на всю округу
rus_verbs:переползти{}, // переползти на светлую сторону
rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию
rus_verbs:мочиться{}, // мочиться на трупы убитых врагов
rus_verbs:радировать{}, // радировать на базу
rus_verbs:промотать{}, // промотать на начало
rus_verbs:заснять{}, // заснять на видео
rus_verbs:подбивать{}, // подбивать на матч-реванш
rus_verbs:наплевать{}, // наплевать на справедливость
rus_verbs:подвывать{}, // подвывать на луну
rus_verbs:расплескать{}, // расплескать на пол
rus_verbs:польститься{}, // польститься на бесплатный сыр
rus_verbs:помчать{}, // помчать на работу
rus_verbs:съезжать{}, // съезжать на обочину
rus_verbs:нашептать{}, // нашептать кому-то на ухо
rus_verbs:наклеить{}, // наклеить на доску объявлений
rus_verbs:завозить{}, // завозить на склад
rus_verbs:заявляться{}, // заявляться на любимую работу
rus_verbs:наглядеться{}, // наглядеться на воробьев
rus_verbs:хлопнуться{}, // хлопнуться на живот
rus_verbs:забредать{}, // забредать на поляну
rus_verbs:посягать{}, // посягать на исконные права собственности
rus_verbs:сдвигать{}, // сдвигать на одну позицию
rus_verbs:спрыгивать{}, // спрыгивать на землю
rus_verbs:сдвигаться{}, // сдвигаться на две позиции
rus_verbs:разделать{}, // разделать на орехи
rus_verbs:разлагать{}, // разлагать на элементарные элементы
rus_verbs:обрушивать{}, // обрушивать на головы врагов
rus_verbs:натечь{}, // натечь на пол
rus_verbs:политься{}, // вода польется на землю
rus_verbs:успеть{}, // Они успеют на поезд.
инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш },
деепричастие:мигрируя{},
инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш },
деепричастие:мигрировав{},
rus_verbs:двинуться{}, // Мы скоро двинемся на дачу.
rus_verbs:подойти{}, // Он не подойдёт на должность секретаря.
rus_verbs:потянуть{}, // Он не потянет на директора.
rus_verbs:тянуть{}, // Он не тянет на директора.
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:жаловаться{}, // Он жалуется на нездоровье.
rus_verbs:издать{}, // издать на деньги спонсоров
rus_verbs:показаться{}, // показаться на глаза
rus_verbs:высаживать{}, // высаживать на необитаемый остров
rus_verbs:вознестись{}, // вознестись на самую вершину славы
rus_verbs:залить{}, // залить на youtube
rus_verbs:закачать{}, // закачать на youtube
rus_verbs:сыграть{}, // сыграть на деньги
rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных
инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных
глагол:экстраполироваться{ вид:несоверш},
инфинитив:экстраполироваться{ вид:соверш},
глагол:экстраполироваться{ вид:соверш},
деепричастие:экстраполируясь{},
инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы
глагол:акцентировать{вид:соверш},
инфинитив:акцентировать{вид:несоверш},
глагол:акцентировать{вид:несоверш},
прилагательное:акцентировавший{вид:несоверш},
//прилагательное:акцентировавший{вид:соверш},
прилагательное:акцентирующий{},
деепричастие:акцентировав{},
деепричастие:акцентируя{},
rus_verbs:бабахаться{}, // он бабахался на пол
rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт
rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина
rus_verbs:бахаться{}, // Наездники бахались на землю
rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю
rus_verbs:благословить{}, // батюшка благословил отрока на подвиг
rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг
rus_verbs:блевануть{}, // Он блеванул на землю
rus_verbs:блевать{}, // Он блюет на землю
rus_verbs:бухнуться{}, // Наездник бухнулся на землю
rus_verbs:валить{}, // Ветер валил деревья на землю
rus_verbs:спилить{}, // Спиленное дерево валится на землю
rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню
rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес
rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход
rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес
rus_verbs:вестись{}, // Не ведись на эти уловки!
rus_verbs:вешать{}, // Гости вешают одежду на вешалку
rus_verbs:вешаться{}, // Одежда вешается на вешалки
rus_verbs:вещать{}, // радиостанция вещает на всю страну
rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм
rus_verbs:взбредать{}, // Что иногда взбредает на ум
rus_verbs:взбрести{}, // Что-то взбрело на ум
rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство
rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи
rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи
rus_verbs:взглянуть{}, // Кошка взглянула на мышку
rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол
rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол
rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол
rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул
rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект
rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух
rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух
rus_verbs:взобраться{}, // Туристы взобрались на гору
rus_verbs:взойти{}, // Туристы взошли на гору
rus_verbs:взъесться{}, // Отец взъелся на непутевого сына
rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына
rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус
rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус
rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка
rus_verbs:водворить{}, // водворить нарушителя на место
rus_verbs:водвориться{}, // водвориться на свое место
rus_verbs:водворять{}, // водворять вещь на свое место
rus_verbs:водворяться{}, // водворяться на свое место
rus_verbs:водружать{}, // водружать флаг на флагшток
rus_verbs:водружаться{}, // Флаг водружается на флагшток
rus_verbs:водрузить{}, // водрузить флаг на флагшток
rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы
rus_verbs:воздействовать{}, // Излучение воздействует на кожу
rus_verbs:воззреть{}, // воззреть на поле боя
rus_verbs:воззриться{}, // воззриться на поле боя
rus_verbs:возить{}, // возить туристов на гору
rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу
rus_verbs:возлагаться{}, // Ответственность возлагается на начальство
rus_verbs:возлечь{}, // возлечь на лежанку
rus_verbs:возложить{}, // возложить цветы на могилу поэта
rus_verbs:вознести{}, // вознести кого-то на вершину славы
rus_verbs:возноситься{}, // возносится на вершину успеха
rus_verbs:возносить{}, // возносить счастливчика на вершину успеха
rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж
rus_verbs:подняться{}, // Мы поднялись на восьмой этаж
rus_verbs:вонять{}, // Кусок сыра воняет на всю округу
rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги
rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги
rus_verbs:ворчать{}, // Старый пес ворчит на прохожих
rus_verbs:воспринимать{}, // воспринимать сообщение на слух
rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух
rus_verbs:воспринять{}, // воспринять сообщение на слух
rus_verbs:восприняться{}, // восприняться на слух
rus_verbs:воссесть{}, // Коля воссел на трон
rus_verbs:вправить{}, // вправить мозг на место
rus_verbs:вправлять{}, // вправлять мозги на место
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:врубать{}, // врубать на полную мощность
rus_verbs:врубить{}, // врубить на полную мощность
rus_verbs:врубиться{}, // врубиться на полную мощность
rus_verbs:врываться{}, // врываться на собрание
rus_verbs:вскарабкаться{}, // вскарабкаться на утёс
rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс
rus_verbs:вскочить{}, // вскочить на ноги
rus_verbs:всплывать{}, // всплывать на поверхность воды
rus_verbs:всплыть{}, // всплыть на поверхность воды
rus_verbs:вспрыгивать{}, // вспрыгивать на платформу
rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу
rus_verbs:встать{}, // встать на защиту чести и достоинства
rus_verbs:вторгаться{}, // вторгаться на чужую территорию
rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию
rus_verbs:въезжать{}, // въезжать на пандус
rus_verbs:наябедничать{}, // наябедничать на соседа по парте
rus_verbs:выблевать{}, // выблевать завтрак на пол
rus_verbs:выблеваться{}, // выблеваться на пол
rus_verbs:выблевывать{}, // выблевывать завтрак на пол
rus_verbs:выблевываться{}, // выблевываться на пол
rus_verbs:вывезти{}, // вывезти мусор на свалку
rus_verbs:вывесить{}, // вывесить белье на просушку
rus_verbs:вывести{}, // вывести собаку на прогулку
rus_verbs:вывешивать{}, // вывешивать белье на веревку
rus_verbs:вывозить{}, // вывозить детей на природу
rus_verbs:вызывать{}, // Начальник вызывает на ковер
rus_verbs:выйти{}, // выйти на свободу
rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение
rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение
rus_verbs:выливать{}, // выливать на землю
rus_verbs:выливаться{}, // выливаться на землю
rus_verbs:вылить{}, // вылить жидкость на землю
rus_verbs:вылиться{}, // Топливо вылилось на землю
rus_verbs:выложить{}, // выложить на берег
rus_verbs:выменивать{}, // выменивать золото на хлеб
rus_verbs:вымениваться{}, // Золото выменивается на хлеб
rus_verbs:выменять{}, // выменять золото на хлеб
rus_verbs:выпадать{}, // снег выпадает на землю
rus_verbs:выплевывать{}, // выплевывать на землю
rus_verbs:выплевываться{}, // выплевываться на землю
rus_verbs:выплескать{}, // выплескать на землю
rus_verbs:выплескаться{}, // выплескаться на землю
rus_verbs:выплескивать{}, // выплескивать на землю
rus_verbs:выплескиваться{}, // выплескиваться на землю
rus_verbs:выплывать{}, // выплывать на поверхность
rus_verbs:выплыть{}, // выплыть на поверхность
rus_verbs:выплюнуть{}, // выплюнуть на пол
rus_verbs:выползать{}, // выползать на свежий воздух
rus_verbs:выпроситься{}, // выпроситься на улицу
rus_verbs:выпрыгивать{}, // выпрыгивать на свободу
rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон
rus_verbs:выпускать{}, // выпускать на свободу
rus_verbs:выпустить{}, // выпустить на свободу
rus_verbs:выпучивать{}, // выпучивать на кого-то глаза
rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то
rus_verbs:выпучить{}, // выпучить глаза на кого-то
rus_verbs:выпучиться{}, // выпучиться на кого-то
rus_verbs:выронить{}, // выронить на землю
rus_verbs:высадить{}, // высадить на берег
rus_verbs:высадиться{}, // высадиться на берег
rus_verbs:высаживаться{}, // высаживаться на остров
rus_verbs:выскальзывать{}, // выскальзывать на землю
rus_verbs:выскочить{}, // выскочить на сцену
rus_verbs:высморкаться{}, // высморкаться на землю
rus_verbs:высморкнуться{}, // высморкнуться на землю
rus_verbs:выставить{}, // выставить на всеобщее обозрение
rus_verbs:выставиться{}, // выставиться на всеобщее обозрение
rus_verbs:выставлять{}, // выставлять на всеобщее обозрение
rus_verbs:выставляться{}, // выставляться на всеобщее обозрение
инфинитив:высыпать{вид:соверш}, // высыпать на землю
инфинитив:высыпать{вид:несоверш},
глагол:высыпать{вид:соверш},
глагол:высыпать{вид:несоверш},
деепричастие:высыпав{},
деепричастие:высыпая{},
прилагательное:высыпавший{вид:соверш},
//++прилагательное:высыпавший{вид:несоверш},
прилагательное:высыпающий{вид:несоверш},
rus_verbs:высыпаться{}, // высыпаться на землю
rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя
rus_verbs:вытаращиваться{}, // вытаращиваться на медведя
rus_verbs:вытаращить{}, // вытаращить глаза на медведя
rus_verbs:вытаращиться{}, // вытаращиться на медведя
rus_verbs:вытекать{}, // вытекать на землю
rus_verbs:вытечь{}, // вытечь на землю
rus_verbs:выучиваться{}, // выучиваться на кого-то
rus_verbs:выучиться{}, // выучиться на кого-то
rus_verbs:посмотреть{}, // посмотреть на экран
rus_verbs:нашить{}, // нашить что-то на одежду
rus_verbs:придти{}, // придти на помощь кому-то
инфинитив:прийти{}, // прийти на помощь кому-то
глагол:прийти{},
деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты.
rus_verbs:поднять{}, // поднять на вершину
rus_verbs:согласиться{}, // согласиться на ничью
rus_verbs:послать{}, // послать на фронт
rus_verbs:слать{}, // слать на фронт
rus_verbs:надеяться{}, // надеяться на лучшее
rus_verbs:крикнуть{}, // крикнуть на шалунов
rus_verbs:пройти{}, // пройти на пляж
rus_verbs:прислать{}, // прислать на экспертизу
rus_verbs:жить{}, // жить на подачки
rus_verbs:становиться{}, // становиться на ноги
rus_verbs:наслать{}, // наслать на кого-то
rus_verbs:принять{}, // принять на заметку
rus_verbs:собираться{}, // собираться на экзамен
rus_verbs:оставить{}, // оставить на всякий случай
rus_verbs:звать{}, // звать на помощь
rus_verbs:направиться{}, // направиться на прогулку
rus_verbs:отвечать{}, // отвечать на звонки
rus_verbs:отправиться{}, // отправиться на прогулку
rus_verbs:поставить{}, // поставить на пол
rus_verbs:обернуться{}, // обернуться на зов
rus_verbs:отозваться{}, // отозваться на просьбу
rus_verbs:закричать{}, // закричать на собаку
rus_verbs:опустить{}, // опустить на землю
rus_verbs:принести{}, // принести на пляж свой жезлонг
rus_verbs:указать{}, // указать на дверь
rus_verbs:ходить{}, // ходить на занятия
rus_verbs:уставиться{}, // уставиться на листок
rus_verbs:приходить{}, // приходить на экзамен
rus_verbs:махнуть{}, // махнуть на пляж
rus_verbs:явиться{}, // явиться на допрос
rus_verbs:оглянуться{}, // оглянуться на дорогу
rus_verbs:уехать{}, // уехать на заработки
rus_verbs:повести{}, // повести на штурм
rus_verbs:опуститься{}, // опуститься на колени
//rus_verbs:передать{}, // передать на проверку
rus_verbs:побежать{}, // побежать на занятия
rus_verbs:прибыть{}, // прибыть на место службы
rus_verbs:кричать{}, // кричать на медведя
rus_verbs:стечь{}, // стечь на землю
rus_verbs:обратить{}, // обратить на себя внимание
rus_verbs:подать{}, // подать на пропитание
rus_verbs:привести{}, // привести на съемки
rus_verbs:испытывать{}, // испытывать на животных
rus_verbs:перевести{}, // перевести на жену
rus_verbs:купить{}, // купить на заемные деньги
rus_verbs:собраться{}, // собраться на встречу
rus_verbs:заглянуть{}, // заглянуть на огонёк
rus_verbs:нажать{}, // нажать на рычаг
rus_verbs:поспешить{}, // поспешить на праздник
rus_verbs:перейти{}, // перейти на русский язык
rus_verbs:поверить{}, // поверить на честное слово
rus_verbs:глянуть{}, // глянуть на обложку
rus_verbs:зайти{}, // зайти на огонёк
rus_verbs:проходить{}, // проходить на сцену
rus_verbs:глядеть{}, // глядеть на актрису
//rus_verbs:решиться{}, // решиться на прыжок
rus_verbs:пригласить{}, // пригласить на танец
rus_verbs:позвать{}, // позвать на экзамен
rus_verbs:усесться{}, // усесться на стул
rus_verbs:поступить{}, // поступить на математический факультет
rus_verbs:лечь{}, // лечь на живот
rus_verbs:потянуться{}, // потянуться на юг
rus_verbs:присесть{}, // присесть на корточки
rus_verbs:наступить{}, // наступить на змею
rus_verbs:заорать{}, // заорать на попрошаек
rus_verbs:надеть{}, // надеть на голову
rus_verbs:поглядеть{}, // поглядеть на девчонок
rus_verbs:принимать{}, // принимать на гарантийное обслуживание
rus_verbs:привезти{}, // привезти на испытания
rus_verbs:рухнуть{}, // рухнуть на асфальт
rus_verbs:пускать{}, // пускать на корм
rus_verbs:отвести{}, // отвести на приём
rus_verbs:отправить{}, // отправить на утилизацию
rus_verbs:двигаться{}, // двигаться на восток
rus_verbs:нести{}, // нести на пляж
rus_verbs:падать{}, // падать на руки
rus_verbs:откинуться{}, // откинуться на спинку кресла
rus_verbs:рявкнуть{}, // рявкнуть на детей
rus_verbs:получать{}, // получать на проживание
rus_verbs:полезть{}, // полезть на рожон
rus_verbs:направить{}, // направить на дообследование
rus_verbs:приводить{}, // приводить на проверку
rus_verbs:потребоваться{}, // потребоваться на замену
rus_verbs:кинуться{}, // кинуться на нападавшего
rus_verbs:учиться{}, // учиться на токаря
rus_verbs:приподнять{}, // приподнять на один метр
rus_verbs:налить{}, // налить на стол
rus_verbs:играть{}, // играть на деньги
rus_verbs:рассчитывать{}, // рассчитывать на подмогу
rus_verbs:шепнуть{}, // шепнуть на ухо
rus_verbs:швырнуть{}, // швырнуть на землю
rus_verbs:прыгнуть{}, // прыгнуть на оленя
rus_verbs:предлагать{}, // предлагать на выбор
rus_verbs:садиться{}, // садиться на стул
rus_verbs:лить{}, // лить на землю
rus_verbs:испытать{}, // испытать на животных
rus_verbs:фыркнуть{}, // фыркнуть на детеныша
rus_verbs:годиться{}, // мясо годится на фарш
rus_verbs:проверить{}, // проверить высказывание на истинность
rus_verbs:откликнуться{}, // откликнуться на призывы
rus_verbs:полагаться{}, // полагаться на интуицию
rus_verbs:покоситься{}, // покоситься на соседа
rus_verbs:повесить{}, // повесить на гвоздь
инфинитив:походить{вид:соверш}, // походить на занятия
глагол:походить{вид:соверш},
деепричастие:походив{},
прилагательное:походивший{},
rus_verbs:помчаться{}, // помчаться на экзамен
rus_verbs:ставить{}, // ставить на контроль
rus_verbs:свалиться{}, // свалиться на землю
rus_verbs:валиться{}, // валиться на землю
rus_verbs:подарить{}, // подарить на день рожденья
rus_verbs:сбежать{}, // сбежать на необитаемый остров
rus_verbs:стрелять{}, // стрелять на поражение
rus_verbs:обращать{}, // обращать на себя внимание
rus_verbs:наступать{}, // наступать на те же грабли
rus_verbs:сбросить{}, // сбросить на землю
rus_verbs:обидеться{}, // обидеться на друга
rus_verbs:устроиться{}, // устроиться на стажировку
rus_verbs:погрузиться{}, // погрузиться на большую глубину
rus_verbs:течь{}, // течь на землю
rus_verbs:отбросить{}, // отбросить на землю
rus_verbs:метать{}, // метать на дно
rus_verbs:пустить{}, // пустить на переплавку
rus_verbs:прожить{}, // прожить на пособие
rus_verbs:полететь{}, // полететь на континент
rus_verbs:пропустить{}, // пропустить на сцену
rus_verbs:указывать{}, // указывать на ошибку
rus_verbs:наткнуться{}, // наткнуться на клад
rus_verbs:рвануть{}, // рвануть на юг
rus_verbs:ступать{}, // ступать на землю
rus_verbs:спрыгнуть{}, // спрыгнуть на берег
rus_verbs:заходить{}, // заходить на огонёк
rus_verbs:нырнуть{}, // нырнуть на глубину
rus_verbs:рвануться{}, // рвануться на свободу
rus_verbs:натянуть{}, // натянуть на голову
rus_verbs:забраться{}, // забраться на стол
rus_verbs:помахать{}, // помахать на прощание
rus_verbs:содержать{}, // содержать на спонсорскую помощь
rus_verbs:приезжать{}, // приезжать на праздники
rus_verbs:проникнуть{}, // проникнуть на территорию
rus_verbs:подъехать{}, // подъехать на митинг
rus_verbs:устремиться{}, // устремиться на волю
rus_verbs:посадить{}, // посадить на стул
rus_verbs:ринуться{}, // ринуться на голкипера
rus_verbs:подвигнуть{}, // подвигнуть на подвиг
rus_verbs:отдавать{}, // отдавать на перевоспитание
rus_verbs:отложить{}, // отложить на черный день
rus_verbs:убежать{}, // убежать на танцы
rus_verbs:поднимать{}, // поднимать на верхний этаж
rus_verbs:переходить{}, // переходить на цифровой сигнал
rus_verbs:отослать{}, // отослать на переаттестацию
rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола
rus_verbs:назначить{}, // назначить на должность
rus_verbs:осесть{}, // осесть на дно
rus_verbs:торопиться{}, // торопиться на экзамен
rus_verbs:менять{}, // менять на еду
rus_verbs:доставить{}, // доставить на шестой этаж
rus_verbs:заслать{}, // заслать на проверку
rus_verbs:дуть{}, // дуть на воду
rus_verbs:сослать{}, // сослать на каторгу
rus_verbs:останавливаться{}, // останавливаться на отдых
rus_verbs:сдаваться{}, // сдаваться на милость победителя
rus_verbs:сослаться{}, // сослаться на презумпцию невиновности
rus_verbs:рассердиться{}, // рассердиться на дочь
rus_verbs:кинуть{}, // кинуть на землю
rus_verbs:расположиться{}, // расположиться на ночлег
rus_verbs:осмелиться{}, // осмелиться на подлог
rus_verbs:шептать{}, // шептать на ушко
rus_verbs:уронить{}, // уронить на землю
rus_verbs:откинуть{}, // откинуть на спинку кресла
rus_verbs:перенести{}, // перенести на рабочий стол
rus_verbs:сдаться{}, // сдаться на милость победителя
rus_verbs:светить{}, // светить на дорогу
rus_verbs:мчаться{}, // мчаться на бал
rus_verbs:нестись{}, // нестись на свидание
rus_verbs:поглядывать{}, // поглядывать на экран
rus_verbs:орать{}, // орать на детей
rus_verbs:уложить{}, // уложить на лопатки
rus_verbs:решаться{}, // решаться на поступок
rus_verbs:попадать{}, // попадать на карандаш
rus_verbs:сплюнуть{}, // сплюнуть на землю
rus_verbs:снимать{}, // снимать на телефон
rus_verbs:опоздать{}, // опоздать на работу
rus_verbs:посылать{}, // посылать на проверку
rus_verbs:погнать{}, // погнать на пастбище
rus_verbs:поступать{}, // поступать на кибернетический факультет
rus_verbs:спускаться{}, // спускаться на уровень моря
rus_verbs:усадить{}, // усадить на диван
rus_verbs:проиграть{}, // проиграть на спор
rus_verbs:прилететь{}, // прилететь на фестиваль
rus_verbs:повалиться{}, // повалиться на спину
rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина
rus_verbs:задавать{}, // задавать на выходные
rus_verbs:запасть{}, // запасть на девочку
rus_verbs:лезть{}, // лезть на забор
rus_verbs:потащить{}, // потащить на выборы
rus_verbs:направляться{}, // направляться на экзамен
rus_verbs:определять{}, // определять на вкус
rus_verbs:поползти{}, // поползти на стену
rus_verbs:поплыть{}, // поплыть на берег
rus_verbs:залезть{}, // залезть на яблоню
rus_verbs:сдать{}, // сдать на мясокомбинат
rus_verbs:приземлиться{}, // приземлиться на дорогу
rus_verbs:лаять{}, // лаять на прохожих
rus_verbs:перевернуть{}, // перевернуть на бок
rus_verbs:ловить{}, // ловить на живца
rus_verbs:отнести{}, // отнести животное на хирургический стол
rus_verbs:плюнуть{}, // плюнуть на условности
rus_verbs:передавать{}, // передавать на проверку
rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек
rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике
инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали
инфинитив:рассыпаться{вид:соверш},
глагол:рассыпаться{вид:несоверш},
глагол:рассыпаться{вид:соверш},
деепричастие:рассыпавшись{},
деепричастие:рассыпаясь{},
прилагательное:рассыпавшийся{вид:несоверш},
прилагательное:рассыпавшийся{вид:соверш},
прилагательное:рассыпающийся{},
rus_verbs:зарычать{}, // Медведица зарычала на медвежонка
rus_verbs:призвать{}, // призвать на сборы
rus_verbs:увезти{}, // увезти на дачу
rus_verbs:содержаться{}, // содержаться на пожертвования
rus_verbs:навести{}, // навести на скопление телескоп
rus_verbs:отправляться{}, // отправляться на утилизацию
rus_verbs:улечься{}, // улечься на животик
rus_verbs:налететь{}, // налететь на препятствие
rus_verbs:перевернуться{}, // перевернуться на спину
rus_verbs:улететь{}, // улететь на родину
rus_verbs:ложиться{}, // ложиться на бок
rus_verbs:класть{}, // класть на место
rus_verbs:отреагировать{}, // отреагировать на выступление
rus_verbs:доставлять{}, // доставлять на дом
rus_verbs:отнять{}, // отнять на благо правящей верхушки
rus_verbs:ступить{}, // ступить на землю
rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы
rus_verbs:унести{}, // унести на работу
rus_verbs:сходить{}, // сходить на концерт
rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги
rus_verbs:соскочить{}, // соскочить на землю
rus_verbs:пожаловаться{}, // пожаловаться на соседей
rus_verbs:тащить{}, // тащить на замену
rus_verbs:замахать{}, // замахать руками на паренька
rus_verbs:заглядывать{}, // заглядывать на обед
rus_verbs:соглашаться{}, // соглашаться на равный обмен
rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик
rus_verbs:увести{}, // увести на осмотр
rus_verbs:успевать{}, // успевать на контрольную работу
rus_verbs:опрокинуть{}, // опрокинуть на себя
rus_verbs:подавать{}, // подавать на апелляцию
rus_verbs:прибежать{}, // прибежать на вокзал
rus_verbs:отшвырнуть{}, // отшвырнуть на замлю
rus_verbs:привлекать{}, // привлекать на свою сторону
rus_verbs:опереться{}, // опереться на палку
rus_verbs:перебраться{}, // перебраться на маленький островок
rus_verbs:уговорить{}, // уговорить на новые траты
rus_verbs:гулять{}, // гулять на спонсорские деньги
rus_verbs:переводить{}, // переводить на другой путь
rus_verbs:заколебаться{}, // заколебаться на один миг
rus_verbs:зашептать{}, // зашептать на ушко
rus_verbs:привстать{}, // привстать на цыпочки
rus_verbs:хлынуть{}, // хлынуть на берег
rus_verbs:наброситься{}, // наброситься на еду
rus_verbs:напасть{}, // повстанцы, напавшие на конвой
rus_verbs:убрать{}, // книга, убранная на полку
rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию
rus_verbs:засматриваться{}, // засматриваться на девчонок
rus_verbs:застегнуться{}, // застегнуться на все пуговицы
rus_verbs:провериться{}, // провериться на заболевания
rus_verbs:проверяться{}, // проверяться на заболевания
rus_verbs:тестировать{}, // тестировать на профпригодность
rus_verbs:протестировать{}, // протестировать на профпригодность
rus_verbs:уходить{}, // отец, уходящий на работу
rus_verbs:налипнуть{}, // снег, налипший на провода
rus_verbs:налипать{}, // снег, налипающий на провода
rus_verbs:улетать{}, // Многие птицы улетают осенью на юг.
rus_verbs:поехать{}, // она поехала на встречу с заказчиком
rus_verbs:переключать{}, // переключать на резервную линию
rus_verbs:переключаться{}, // переключаться на резервную линию
rus_verbs:подписаться{}, // подписаться на обновление
rus_verbs:нанести{}, // нанести на кожу
rus_verbs:нарываться{}, // нарываться на неприятности
rus_verbs:выводить{}, // выводить на орбиту
rus_verbs:вернуться{}, // вернуться на родину
rus_verbs:возвращаться{}, // возвращаться на родину
прилагательное:падкий{}, // Он падок на деньги.
прилагательное:обиженный{}, // Он обижен на отца.
rus_verbs:косить{}, // Он косит на оба глаза.
rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок.
прилагательное:готовый{}, // Он готов на всякие жертвы.
rus_verbs:говорить{}, // Он говорит на скользкую тему.
прилагательное:глухой{}, // Он глух на одно ухо.
rus_verbs:взять{}, // Он взял ребёнка себе на колени.
rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия.
rus_verbs:вести{}, // Лестница ведёт на третий этаж.
rus_verbs:уполномочивать{}, // уполномочивать на что-либо
глагол:спешить{ вид:несоверш }, // Я спешу на поезд.
rus_verbs:брать{}, // Я беру всю ответственность на себя.
rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление.
rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики.
rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку.
rus_verbs:разбираться{}, // Эта машина разбирается на части.
rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние.
rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп.
rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье.
rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно.
rus_verbs:делиться{}, // Тридцать делится на пять без остатка.
rus_verbs:удаляться{}, // Суд удаляется на совещание.
rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север.
rus_verbs:сохранить{}, // Сохраните это на память обо мне.
rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию.
rus_verbs:лететь{}, // Самолёт летит на север.
rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров.
// rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи.
rus_verbs:смотреть{}, // Она смотрит на нас из окна.
rus_verbs:отдать{}, // Она отдала мне деньги на сохранение.
rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину.
rus_verbs:любоваться{}, // гости любовались на картину
rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь.
прилагательное:действительный{}, // Прививка оспы действительна только на три года.
rus_verbs:спуститься{}, // На город спустился смог
прилагательное:нечистый{}, // Он нечист на руку.
прилагательное:неспособный{}, // Он неспособен на такую низость.
прилагательное:злой{}, // кот очень зол на хозяина
rus_verbs:пойти{}, // Девочка не пошла на урок физультуры
rus_verbs:прибывать{}, // мой поезд прибывает на первый путь
rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу
rus_verbs:идти{}, // Дело идёт на лад.
rus_verbs:лазить{}, // Он лазил на чердак.
rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры.
// rus_verbs:действовать{}, // действующий на нервы
rus_verbs:выходить{}, // Балкон выходит на площадь.
rus_verbs:работать{}, // Время работает на нас.
глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина.
rus_verbs:бросить{}, // Они бросили все силы на строительство.
// глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков.
rus_verbs:броситься{}, // Она радостно бросилась мне на шею.
rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью.
rus_verbs:ответить{}, // Она не ответила на мой поклон.
rus_verbs:нашивать{}, // Она нашивала заплату на локоть.
rus_verbs:молиться{}, // Она молится на свою мать.
rus_verbs:запереть{}, // Она заперла дверь на замок.
rus_verbs:заявить{}, // Она заявила свои права на наследство.
rus_verbs:уйти{}, // Все деньги ушли на путешествие.
rus_verbs:вступить{}, // Водолаз вступил на берег.
rus_verbs:сойти{}, // Ночь сошла на землю.
rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано.
rus_verbs:рыдать{}, // Не рыдай так безумно над ним.
rus_verbs:подписать{}, // Не забудьте подписать меня на газету.
rus_verbs:держать{}, // Наш пароход держал курс прямо на север.
rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира.
rus_verbs:ехать{}, // Мы сейчас едем на завод.
rus_verbs:выбросить{}, // Волнами лодку выбросило на берег.
ГЛ_ИНФ(сесть), // сесть на снег
ГЛ_ИНФ(записаться),
ГЛ_ИНФ(положить) // положи книгу на стол
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: залить на youtube
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} }
then return true
}
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } }
then return true
}
// смещаться на несколько миллиметров
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} наречие:*{} }
then return true
}
// партия взяла на себя нереалистичные обязательства
fact гл_предл
{
if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} }
then return true
}
#endregion ВИНИТЕЛЬНЫЙ
// Все остальные варианты с предлогом 'НА' по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:вин } }
then return false,-4
}
// Этот вариант нужен для обработки конструкций с числительными:
// Президентские выборы разделили Венесуэлу на два непримиримых лагеря
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:род } }
then return false,-4
}
// Продавать на eBay
fact гл_предл
{
if context { * предлог:на{} * }
then return false,-6
}
#endregion Предлог_НА
#region Предлог_С
// ------------- ПРЕДЛОГ 'С' -----------------
// У этого предлога предпочтительная семантика привязывает его обычно к существительному.
// Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим.
#region ТВОРИТЕЛЬНЫЙ
wordentry_set Гл_С_Твор={
rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов
rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться
rus_verbs:забраться{},
rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ)
rus_verbs:БИТЬСЯ{}, //
rus_verbs:ПОДРАТЬСЯ{}, //
прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ)
rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ)
rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ)
rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ)
rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ)
прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра
rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом.
rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ)
rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ)
rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ)
rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ)
rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом
rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками
rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу
rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ)
rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ)
rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ)
rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ)
rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ)
rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ)
rus_verbs:отправить{}, // вы можете отправить со мной человека
rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам
rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор)
rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С)
rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С)
прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С)
rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С)
rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С)
rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С)
rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С)
rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С)
rus_verbs:СВЫКАТЬСЯ{},
rus_verbs:стаскиваться{},
rus_verbs:спиливаться{},
rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С)
rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор)
rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С)
rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С)
rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С)
rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С)
rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С)
rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С)
rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С)
rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С)
rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор)
rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С)
rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С)
rus_verbs:согласиться{}, // с этим согласились все (согласиться с)
rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор)
rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С)
rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С)
rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор)
rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор)
rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С)
rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С)
rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор)
rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор)
rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор)
rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор)
rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор)
rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор)
rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор)
rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор)
rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор)
rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ)
rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ)
rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много)
rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С)
rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С)
rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С)
rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С)
rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С)
rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор)
rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С)
rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С)
rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С)
rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С)
rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С)
инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара.
инфинитив:кристаллизоваться{ вид:несоверш },
глагол:кристаллизоваться{ вид:соверш },
глагол:кристаллизоваться{ вид:несоверш },
rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С)
rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С)
rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С)
rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С)
rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С)
rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор)
rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С)
rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С)
rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с)
rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с)
rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с)
rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с)
rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело.
rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором
rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором
rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором
rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором
rus_verbs:стирать{}, // стирать с мылом рубашку в тазу
rus_verbs:прыгать{}, // парашютист прыгает с парашютом
rus_verbs:выступить{}, // Он выступил с приветствием съезду.
rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят.
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой.
rus_verbs:вставать{}, // он встаёт с зарёй
rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером.
rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью.
rus_verbs:договориться{}, // мы договоримся с вами
rus_verbs:побыть{}, // он хотел побыть с тобой
rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью
rus_verbs:вязаться{}, // вязаться с фактами
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:относиться{}, // относиться с пониманием
rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов.
rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней
rus_verbs:гулять{}, // бабушка гуляет с внуком
rus_verbs:разбираться{}, // разбираться с задачей
rus_verbs:сверить{}, // Данные были сверены с эталонными значениями
rus_verbs:делать{}, // Что делать со старым телефоном
rus_verbs:осматривать{}, // осматривать с удивлением
rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре
rus_verbs:попрощаться{}, // попрощаться с талантливым актером
rus_verbs:задремать{}, // задремать с кружкой чая в руке
rus_verbs:связать{}, // связать катастрофу с действиями конкурентов
rus_verbs:носиться{}, // носиться с безумной идеей
rus_verbs:кончать{}, // кончать с собой
rus_verbs:обмениваться{}, // обмениваться с собеседниками
rus_verbs:переговариваться{}, // переговариваться с маяком
rus_verbs:общаться{}, // общаться с полицией
rus_verbs:завершить{}, // завершить с ошибкой
rus_verbs:обняться{}, // обняться с подругой
rus_verbs:сливаться{}, // сливаться с фоном
rus_verbs:смешаться{}, // смешаться с толпой
rus_verbs:договариваться{}, // договариваться с потерпевшим
rus_verbs:обедать{}, // обедать с гостями
rus_verbs:сообщаться{}, // сообщаться с подземной рекой
rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц
rus_verbs:читаться{}, // читаться с трудом
rus_verbs:смириться{}, // смириться с утратой
rus_verbs:разделить{}, // разделить с другими ответственность
rus_verbs:роднить{}, // роднить с медведем
rus_verbs:медлить{}, // медлить с ответом
rus_verbs:скрестить{}, // скрестить с ужом
rus_verbs:покоиться{}, // покоиться с миром
rus_verbs:делиться{}, // делиться с друзьями
rus_verbs:познакомить{}, // познакомить с Олей
rus_verbs:порвать{}, // порвать с Олей
rus_verbs:завязать{}, // завязать с Олей знакомство
rus_verbs:суетиться{}, // суетиться с изданием романа
rus_verbs:соединиться{}, // соединиться с сервером
rus_verbs:справляться{}, // справляться с нуждой
rus_verbs:замешкаться{}, // замешкаться с ответом
rus_verbs:поссориться{}, // поссориться с подругой
rus_verbs:ссориться{}, // ссориться с друзьями
rus_verbs:торопить{}, // торопить с решением
rus_verbs:поздравить{}, // поздравить с победой
rus_verbs:проститься{}, // проститься с человеком
rus_verbs:поработать{}, // поработать с деревом
rus_verbs:приключиться{}, // приключиться с Колей
rus_verbs:сговориться{}, // сговориться с Ваней
rus_verbs:отъехать{}, // отъехать с ревом
rus_verbs:объединять{}, // объединять с другой кампанией
rus_verbs:употребить{}, // употребить с молоком
rus_verbs:перепутать{}, // перепутать с другой книгой
rus_verbs:запоздать{}, // запоздать с ответом
rus_verbs:подружиться{}, // подружиться с другими детьми
rus_verbs:дружить{}, // дружить с Сережей
rus_verbs:поравняться{}, // поравняться с финишной чертой
rus_verbs:ужинать{}, // ужинать с гостями
rus_verbs:расставаться{}, // расставаться с приятелями
rus_verbs:завтракать{}, // завтракать с семьей
rus_verbs:объединиться{}, // объединиться с соседями
rus_verbs:сменяться{}, // сменяться с напарником
rus_verbs:соединить{}, // соединить с сетью
rus_verbs:разговориться{}, // разговориться с охранником
rus_verbs:преподнести{}, // преподнести с помпой
rus_verbs:напечатать{}, // напечатать с картинками
rus_verbs:соединять{}, // соединять с сетью
rus_verbs:расправиться{}, // расправиться с беззащитным человеком
rus_verbs:распрощаться{}, // распрощаться с деньгами
rus_verbs:сравнить{}, // сравнить с конкурентами
rus_verbs:ознакомиться{}, // ознакомиться с выступлением
инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой
деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{},
rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия
rus_verbs:прощаться{}, // прощаться с боевым товарищем
rus_verbs:сравнивать{}, // сравнивать с конкурентами
rus_verbs:складывать{}, // складывать с весом упаковки
rus_verbs:повестись{}, // повестись с ворами
rus_verbs:столкнуть{}, // столкнуть с отбойником
rus_verbs:переглядываться{}, // переглядываться с соседом
rus_verbs:поторопить{}, // поторопить с откликом
rus_verbs:развлекаться{}, // развлекаться с подружками
rus_verbs:заговаривать{}, // заговаривать с незнакомцами
rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой
инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим
деепричастие:согласуясь{}, прилагательное:согласующийся{},
rus_verbs:совпасть{}, // совпасть с оригиналом
rus_verbs:соединяться{}, // соединяться с куратором
rus_verbs:повстречаться{}, // повстречаться с героями
rus_verbs:поужинать{}, // поужинать с родителями
rus_verbs:развестись{}, // развестись с первым мужем
rus_verbs:переговорить{}, // переговорить с коллегами
rus_verbs:сцепиться{}, // сцепиться с бродячей собакой
rus_verbs:сожрать{}, // сожрать с потрохами
rus_verbs:побеседовать{}, // побеседовать со шпаной
rus_verbs:поиграть{}, // поиграть с котятами
rus_verbs:сцепить{}, // сцепить с тягачом
rus_verbs:помириться{}, // помириться с подружкой
rus_verbs:связываться{}, // связываться с бандитами
rus_verbs:совещаться{}, // совещаться с мастерами
rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой
rus_verbs:переплестись{}, // переплестись с кустами
rus_verbs:мутить{}, // мутить с одногрупницами
rus_verbs:приглядываться{}, // приглядываться с интересом
rus_verbs:сблизиться{}, // сблизиться с врагами
rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой
rus_verbs:растереть{}, // растереть с солью
rus_verbs:смешиваться{}, // смешиваться с известью
rus_verbs:соприкоснуться{}, // соприкоснуться с тайной
rus_verbs:ладить{}, // ладить с родственниками
rus_verbs:сотрудничать{}, // сотрудничать с органами дознания
rus_verbs:съехаться{}, // съехаться с родственниками
rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов
rus_verbs:советоваться{}, // советоваться с отчимом
rus_verbs:сравниться{}, // сравниться с лучшими
rus_verbs:знакомиться{}, // знакомиться с абитуриентами
rus_verbs:нырять{}, // нырять с аквалангом
rus_verbs:забавляться{}, // забавляться с куклой
rus_verbs:перекликаться{}, // перекликаться с другой статьей
rus_verbs:тренироваться{}, // тренироваться с партнершей
rus_verbs:поспорить{}, // поспорить с казночеем
инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком
деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш },
rus_verbs:примириться{}, // примириться с утратой
rus_verbs:раскланяться{}, // раскланяться с фрейлинами
rus_verbs:слечь{}, // слечь с ангиной
rus_verbs:соприкасаться{}, // соприкасаться со стеной
rus_verbs:смешать{}, // смешать с грязью
rus_verbs:пересекаться{}, // пересекаться с трассой
rus_verbs:путать{}, // путать с государственной шерстью
rus_verbs:поболтать{}, // поболтать с ученицами
rus_verbs:здороваться{}, // здороваться с профессором
rus_verbs:просчитаться{}, // просчитаться с покупкой
rus_verbs:сторожить{}, // сторожить с собакой
rus_verbs:обыскивать{}, // обыскивать с собаками
rus_verbs:переплетаться{}, // переплетаться с другой веткой
rus_verbs:обниматься{}, // обниматься с Ксюшей
rus_verbs:объединяться{}, // объединяться с конкурентами
rus_verbs:погорячиться{}, // погорячиться с покупкой
rus_verbs:мыться{}, // мыться с мылом
rus_verbs:свериться{}, // свериться с эталоном
rus_verbs:разделаться{}, // разделаться с кем-то
rus_verbs:чередоваться{}, // чередоваться с партнером
rus_verbs:налететь{}, // налететь с соратниками
rus_verbs:поспать{}, // поспать с включенным светом
rus_verbs:управиться{}, // управиться с собакой
rus_verbs:согрешить{}, // согрешить с замужней
rus_verbs:определиться{}, // определиться с победителем
rus_verbs:перемешаться{}, // перемешаться с гранулами
rus_verbs:затрудняться{}, // затрудняться с ответом
rus_verbs:обождать{}, // обождать со стартом
rus_verbs:фыркать{}, // фыркать с презрением
rus_verbs:засидеться{}, // засидеться с приятелем
rus_verbs:крепнуть{}, // крепнуть с годами
rus_verbs:пировать{}, // пировать с дружиной
rus_verbs:щебетать{}, // щебетать с сестричками
rus_verbs:маяться{}, // маяться с кашлем
rus_verbs:сближать{}, // сближать с центральным светилом
rus_verbs:меркнуть{}, // меркнуть с возрастом
rus_verbs:заспорить{}, // заспорить с оппонентами
rus_verbs:граничить{}, // граничить с Ливаном
rus_verbs:перестараться{}, // перестараться со стимуляторами
rus_verbs:объединить{}, // объединить с филиалом
rus_verbs:свыкнуться{}, // свыкнуться с утратой
rus_verbs:посоветоваться{}, // посоветоваться с адвокатами
rus_verbs:напутать{}, // напутать с ведомостями
rus_verbs:нагрянуть{}, // нагрянуть с обыском
rus_verbs:посовещаться{}, // посовещаться с судьей
rus_verbs:провернуть{}, // провернуть с друганом
rus_verbs:разделяться{}, // разделяться с сотрапезниками
rus_verbs:пересечься{}, // пересечься с второй колонной
rus_verbs:опережать{}, // опережать с большим запасом
rus_verbs:перепутаться{}, // перепутаться с другой линией
rus_verbs:соотноситься{}, // соотноситься с затратами
rus_verbs:смешивать{}, // смешивать с золой
rus_verbs:свидеться{}, // свидеться с тобой
rus_verbs:переспать{}, // переспать с графиней
rus_verbs:поладить{}, // поладить с соседями
rus_verbs:протащить{}, // протащить с собой
rus_verbs:разминуться{}, // разминуться с встречным потоком
rus_verbs:перемежаться{}, // перемежаться с успехами
rus_verbs:рассчитаться{}, // рассчитаться с кредиторами
rus_verbs:срастись{}, // срастись с телом
rus_verbs:знакомить{}, // знакомить с родителями
rus_verbs:поругаться{}, // поругаться с родителями
rus_verbs:совладать{}, // совладать с чувствами
rus_verbs:обручить{}, // обручить с богатой невестой
rus_verbs:сближаться{}, // сближаться с вражеским эсминцем
rus_verbs:замутить{}, // замутить с Ксюшей
rus_verbs:повозиться{}, // повозиться с настройкой
rus_verbs:торговаться{}, // торговаться с продавцами
rus_verbs:уединиться{}, // уединиться с девчонкой
rus_verbs:переборщить{}, // переборщить с добавкой
rus_verbs:ознакомить{}, // ознакомить с пожеланиями
rus_verbs:прочесывать{}, // прочесывать с собаками
rus_verbs:переписываться{}, // переписываться с корреспондентами
rus_verbs:повздорить{}, // повздорить с сержантом
rus_verbs:разлучить{}, // разлучить с семьей
rus_verbs:соседствовать{}, // соседствовать с цыганами
rus_verbs:застукать{}, // застукать с проститутками
rus_verbs:напуститься{}, // напуститься с кулаками
rus_verbs:сдружиться{}, // сдружиться с ребятами
rus_verbs:соперничать{}, // соперничать с параллельным классом
rus_verbs:прочесать{}, // прочесать с собаками
rus_verbs:кокетничать{}, // кокетничать с гимназистками
rus_verbs:мириться{}, // мириться с убытками
rus_verbs:оплошать{}, // оплошать с билетами
rus_verbs:отождествлять{}, // отождествлять с литературным героем
rus_verbs:хитрить{}, // хитрить с зарплатой
rus_verbs:провозиться{}, // провозиться с задачкой
rus_verbs:коротать{}, // коротать с друзьями
rus_verbs:соревноваться{}, // соревноваться с машиной
rus_verbs:уживаться{}, // уживаться с местными жителями
rus_verbs:отождествляться{}, // отождествляться с литературным героем
rus_verbs:сопоставить{}, // сопоставить с эталоном
rus_verbs:пьянствовать{}, // пьянствовать с друзьями
rus_verbs:залетать{}, // залетать с паленой водкой
rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой
rus_verbs:запаздывать{}, // запаздывать с кормлением
rus_verbs:таскаться{}, // таскаться с сумками
rus_verbs:контрастировать{}, // контрастировать с туфлями
rus_verbs:сшибиться{}, // сшибиться с форвардом
rus_verbs:состязаться{}, // состязаться с лучшей командой
rus_verbs:затрудниться{}, // затрудниться с объяснением
rus_verbs:объясниться{}, // объясниться с пострадавшими
rus_verbs:разводиться{}, // разводиться со сварливой женой
rus_verbs:препираться{}, // препираться с адвокатами
rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками
rus_verbs:свестись{}, // свестись с нулевым счетом
rus_verbs:обговорить{}, // обговорить с директором
rus_verbs:обвенчаться{}, // обвенчаться с ведьмой
rus_verbs:экспериментировать{}, // экспериментировать с генами
rus_verbs:сверять{}, // сверять с таблицей
rus_verbs:сверяться{}, // свериться с таблицей
rus_verbs:сблизить{}, // сблизить с точкой
rus_verbs:гармонировать{}, // гармонировать с обоями
rus_verbs:перемешивать{}, // перемешивать с молоком
rus_verbs:трепаться{}, // трепаться с сослуживцами
rus_verbs:перемигиваться{}, // перемигиваться с соседкой
rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем
rus_verbs:распить{}, // распить с собутыльниками
rus_verbs:скрестись{}, // скрестись с дикой лошадью
rus_verbs:передраться{}, // передраться с дворовыми собаками
rus_verbs:умыть{}, // умыть с мылом
rus_verbs:грызться{}, // грызться с соседями
rus_verbs:переругиваться{}, // переругиваться с соседями
rus_verbs:доиграться{}, // доиграться со спичками
rus_verbs:заладиться{}, // заладиться с подругой
rus_verbs:скрещиваться{}, // скрещиваться с дикими видами
rus_verbs:повидаться{}, // повидаться с дедушкой
rus_verbs:повоевать{}, // повоевать с орками
rus_verbs:сразиться{}, // сразиться с лучшим рыцарем
rus_verbs:кипятить{}, // кипятить с отбеливателем
rus_verbs:усердствовать{}, // усердствовать с наказанием
rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером
rus_verbs:пошептаться{}, // пошептаться с судьями
rus_verbs:сравняться{}, // сравняться с лучшими экземплярами
rus_verbs:церемониться{}, // церемониться с пьяницами
rus_verbs:консультироваться{}, // консультироваться со специалистами
rus_verbs:переусердствовать{}, // переусердствовать с наказанием
rus_verbs:проноситься{}, // проноситься с собой
rus_verbs:перемешать{}, // перемешать с гипсом
rus_verbs:темнить{}, // темнить с долгами
rus_verbs:сталкивать{}, // сталкивать с черной дырой
rus_verbs:увольнять{}, // увольнять с волчьим билетом
rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным
rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами
rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт
rus_verbs:созвониться{}, // созвониться с мамой
rus_verbs:спеться{}, // спеться с отъявленными хулиганами
rus_verbs:интриговать{}, // интриговать с придворными
rus_verbs:приобрести{}, // приобрести со скидкой
rus_verbs:задержаться{}, // задержаться со сдачей работы
rus_verbs:плавать{}, // плавать со спасательным кругом
rus_verbs:якшаться{}, // Не якшайся с врагами
инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
инфинитив:ассоциировать{вид:несоверш},
глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
глагол:ассоциировать{вид:несоверш},
//+прилагательное:ассоциировавший{вид:несоверш},
прилагательное:ассоциировавший{вид:соверш},
прилагательное:ассоциирующий{},
деепричастие:ассоциируя{},
деепричастие:ассоциировав{},
rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем
rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов
rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов
//+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом
//+глагол:аффилировать{вид:соверш},
прилагательное:аффилированный{},
rus_verbs:баловаться{}, // мальчик баловался с молотком
rus_verbs:балясничать{}, // женщина балясничала с товарками
rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями
rus_verbs:бодаться{}, // теленок бодается с деревом
rus_verbs:боксировать{}, // Майкл дважды боксировал с ним
rus_verbs:брататься{}, // Солдаты братались с бойцами союзников
rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:происходить{}, // Что происходит с мировой экономикой?
rus_verbs:произойти{}, // Что произошло с экономикой?
rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами
rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями
rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:водиться{}, // Няня водится с детьми
rus_verbs:воевать{}, // Фермеры воевали с волками
rus_verbs:возиться{}, // Няня возится с детьми
rus_verbs:ворковать{}, // Голубь воркует с голубкой
rus_verbs:воссоединиться{}, // Дети воссоединились с семьей
rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей
rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой
rus_verbs:враждовать{}, // враждовать с соседями
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:расстаться{}, // я не могу расстаться с тобой
rus_verbs:выдирать{}, // выдирать с мясом
rus_verbs:выдираться{}, // выдираться с мясом
rus_verbs:вытворить{}, // вытворить что-либо с чем-либо
rus_verbs:вытворять{}, // вытворять что-либо с чем-либо
rus_verbs:сделать{}, // сделать с чем-то
rus_verbs:домыть{}, // домыть с мылом
rus_verbs:случиться{}, // случиться с кем-то
rus_verbs:остаться{}, // остаться с кем-то
rus_verbs:случать{}, // случать с породистым кобельком
rus_verbs:послать{}, // послать с весточкой
rus_verbs:работать{}, // работать с роботами
rus_verbs:провести{}, // провести с девчонками время
rus_verbs:заговорить{}, // заговорить с незнакомкой
rus_verbs:прошептать{}, // прошептать с придыханием
rus_verbs:читать{}, // читать с выражением
rus_verbs:слушать{}, // слушать с повышенным вниманием
rus_verbs:принести{}, // принести с собой
rus_verbs:спать{}, // спать с женщинами
rus_verbs:закончить{}, // закончить с приготовлениями
rus_verbs:помочь{}, // помочь с перестановкой
rus_verbs:уехать{}, // уехать с семьей
rus_verbs:случаться{}, // случаться с кем-то
rus_verbs:кутить{}, // кутить с проститутками
rus_verbs:разговаривать{}, // разговаривать с ребенком
rus_verbs:погодить{}, // погодить с ликвидацией
rus_verbs:считаться{}, // считаться с чужим мнением
rus_verbs:носить{}, // носить с собой
rus_verbs:хорошеть{}, // хорошеть с каждым днем
rus_verbs:приводить{}, // приводить с собой
rus_verbs:прыгнуть{}, // прыгнуть с парашютом
rus_verbs:петь{}, // петь с чувством
rus_verbs:сложить{}, // сложить с результатом
rus_verbs:познакомиться{}, // познакомиться с другими студентами
rus_verbs:обращаться{}, // обращаться с животными
rus_verbs:съесть{}, // съесть с хлебом
rus_verbs:ошибаться{}, // ошибаться с дозировкой
rus_verbs:столкнуться{}, // столкнуться с медведем
rus_verbs:справиться{}, // справиться с нуждой
rus_verbs:торопиться{}, // торопиться с ответом
rus_verbs:поздравлять{}, // поздравлять с победой
rus_verbs:объясняться{}, // объясняться с начальством
rus_verbs:пошутить{}, // пошутить с подругой
rus_verbs:поздороваться{}, // поздороваться с коллегами
rus_verbs:поступать{}, // Как поступать с таким поведением?
rus_verbs:определяться{}, // определяться с кандидатами
rus_verbs:связаться{}, // связаться с поставщиком
rus_verbs:спорить{}, // спорить с собеседником
rus_verbs:разобраться{}, // разобраться с делами
rus_verbs:ловить{}, // ловить с удочкой
rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос
rus_verbs:шутить{}, // шутить с диким зверем
rus_verbs:разорвать{}, // разорвать с поставщиком контракт
rus_verbs:увезти{}, // увезти с собой
rus_verbs:унести{}, // унести с собой
rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее
rus_verbs:складываться{}, // складываться с первым импульсом
rus_verbs:соглашаться{}, // соглашаться с предложенным договором
//rus_verbs:покончить{}, // покончить с развратом
rus_verbs:прихватить{}, // прихватить с собой
rus_verbs:похоронить{}, // похоронить с почестями
rus_verbs:связывать{}, // связывать с компанией свою судьбу
rus_verbs:совпадать{}, // совпадать с предсказанием
rus_verbs:танцевать{}, // танцевать с девушками
rus_verbs:поделиться{}, // поделиться с выжившими
rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате.
rus_verbs:беседовать{}, // преподаватель, беседующий со студентами
rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью
rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой
rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками
rus_verbs:поговорить{}, // поговорить с виновниками
rus_verbs:сказать{}, // сказать с трудом
rus_verbs:произнести{}, // произнести с трудом
rus_verbs:говорить{}, // говорить с акцентом
rus_verbs:произносить{}, // произносить с трудом
rus_verbs:встречаться{}, // кто с Антонио встречался?
rus_verbs:посидеть{}, // посидеть с друзьями
rus_verbs:расквитаться{}, // расквитаться с обидчиком
rus_verbs:поквитаться{}, // поквитаться с обидчиком
rus_verbs:ругаться{}, // ругаться с женой
rus_verbs:поскандалить{}, // поскандалить с женой
rus_verbs:потанцевать{}, // потанцевать с подругой
rus_verbs:скандалить{}, // скандалить с соседями
rus_verbs:разругаться{}, // разругаться с другом
rus_verbs:болтать{}, // болтать с подругами
rus_verbs:потрепаться{}, // потрепаться с соседкой
rus_verbs:войти{}, // войти с регистрацией
rus_verbs:входить{}, // входить с регистрацией
rus_verbs:возвращаться{}, // возвращаться с триумфом
rus_verbs:опоздать{}, // Он опоздал с подачей сочинения.
rus_verbs:молчать{}, // Он молчал с ледяным спокойствием.
rus_verbs:сражаться{}, // Он героически сражался с врагами.
rus_verbs:выходить{}, // Он всегда выходит с зонтиком.
rus_verbs:сличать{}, // сличать перевод с оригиналом
rus_verbs:начать{}, // я начал с товарищем спор о религии
rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки
rus_verbs:приходить{}, // Приходите с нею.
rus_verbs:жить{}, // кто с тобой жил?
rus_verbs:расходиться{}, // Маша расходится с Петей
rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой
rus_verbs:торговать{}, // мы торгуем с ними нефтью
rus_verbs:уединяться{}, // уединяться с подругой в доме
rus_verbs:уладить{}, // уладить конфликт с соседями
rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем.
rus_verbs:разделять{}, // Я разделяю с вами горе и радость.
rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи.
rus_verbs:захватить{}, // Я не захватил с собой денег.
прилагательное:знакомый{}, // Я знаком с ними обоими.
rus_verbs:вести{}, // Я веду с ней переписку.
прилагательное:сопряженный{}, // Это сопряжено с большими трудностями.
прилагательное:связанный{причастие}, // Это дело связано с риском.
rus_verbs:поехать{}, // Хотите поехать со мной в театр?
rus_verbs:проснуться{}, // Утром я проснулся с ясной головой.
rus_verbs:лететь{}, // Самолёт летел со скоростью звука.
rus_verbs:играть{}, // С огнём играть опасно!
rus_verbs:поделать{}, // С ним ничего не поделаешь.
rus_verbs:стрястись{}, // С ней стряслось несчастье.
rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием.
rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием.
rus_verbs:разойтись{}, // Она разошлась с мужем.
rus_verbs:пристать{}, // Она пристала ко мне с расспросами.
rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением.
rus_verbs:поступить{}, // Она плохо поступила с ним.
rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом.
rus_verbs:взять{}, // Возьмите с собой только самое необходимое.
rus_verbs:наплакаться{}, // Наплачется она с ним.
rus_verbs:лежать{}, // Он лежит с воспалением лёгких.
rus_verbs:дышать{}, // дышащий с трудом
rus_verbs:брать{}, // брать с собой
rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой.
rus_verbs:упасть{}, // Ваза упала со звоном.
rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком
rus_verbs:сидеть{}, // Она сидит дома с ребенком
rus_verbs:встретиться{}, // встречаться с кем-либо
ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом
ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{},
rus_verbs:мыть{}
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} }
then return true
}
#endregion ТВОРИТЕЛЬНЫЙ
#region РОДИТЕЛЬНЫЙ
wordentry_set Гл_С_Род=
{
rus_verbs:УХОДИТЬ{}, // Но с базы не уходить.
rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ)
rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ)
rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ)
rus_verbs:РАЗГЛЯДЕТЬ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ)
rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ)
rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ)
rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ)
rus_verbs:ЗАРЕВЕТЬ{}, //
rus_verbs:ПРОРЕВЕТЬ{}, //
rus_verbs:ЗАОРАТЬ{}, //
rus_verbs:ПРООРАТЬ{}, //
rus_verbs:ОРАТЬ{}, //
rus_verbs:ЗАКРИЧАТЬ{},
rus_verbs:ВОПИТЬ{}, //
rus_verbs:ЗАВОПИТЬ{}, //
rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ)
rus_verbs:СТАСКИВАТЬ{}, //
rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ)
rus_verbs:ЗАВЫТЬ{}, //
rus_verbs:ВЫТЬ{}, //
rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ)
rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:собирать{}, // мальчики начали собирать со столов посуду
rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал
rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ)
rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ)
rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ)
rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ)
rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ)
rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род)
rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род)
rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С)
rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С)
rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род)
rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С)
rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С)
rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С)
rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род)
rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род)
rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род)
rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род)
rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род)
rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С)
rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род)
rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род)
rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род)
rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род)
rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род)
rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род)
rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С)
rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род)
rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род)
rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род)
rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С)
rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С)
rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С)
прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С)
rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С)
rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род)
rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С)
rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с)
rus_verbs:спасть{}, // тяжесть спала с души. (спасть с)
rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С)
rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С)
rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С)
rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то)
rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С)
rus_verbs:приближаться{}, // со стороны острова приближалась лодка.
rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С)
rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с)
rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с)
rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С)
rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С)
rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С)
rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С)
rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С)
rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С)
rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С)
rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С)
rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С)
rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С)
rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с)
rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С)
rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с)
rus_verbs:вставать{}, // Он не встает с кровати. (вставать с)
rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с)
rus_verbs:причитаться{}, // С вас причитается 50 рублей.
rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки.
rus_verbs:сократить{}, // Его сократили со службы.
rus_verbs:поднять{}, // рука подняла с пола
rus_verbs:поднимать{},
rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни.
rus_verbs:полететь{}, // Мальчик полетел с лестницы.
rus_verbs:литься{}, // вода льется с неба
rus_verbs:натечь{}, // натечь с сапог
rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая
rus_verbs:съезжать{}, // съезжать с заявленной темы
rus_verbs:покатываться{}, // покатываться со смеху
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:сдирать{}, // сдирать с тела кожу
rus_verbs:соскальзывать{}, // соскальзывать с крючка
rus_verbs:сметать{}, // сметать с прилавков
rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки
rus_verbs:прокаркать{}, // прокаркать с ветки
rus_verbs:стряхивать{}, // стряхивать с одежды
rus_verbs:сваливаться{}, // сваливаться с лестницы
rus_verbs:слизнуть{}, // слизнуть с лица
rus_verbs:доставляться{}, // доставляться с фермы
rus_verbs:обступать{}, // обступать с двух сторон
rus_verbs:повскакивать{}, // повскакивать с мест
rus_verbs:обозревать{}, // обозревать с вершины
rus_verbs:слинять{}, // слинять с урока
rus_verbs:смывать{}, // смывать с лица
rus_verbs:спихнуть{}, // спихнуть со стола
rus_verbs:обозреть{}, // обозреть с вершины
rus_verbs:накупить{}, // накупить с рук
rus_verbs:схлынуть{}, // схлынуть с берега
rus_verbs:спикировать{}, // спикировать с километровой высоты
rus_verbs:уползти{}, // уползти с поля боя
rus_verbs:сбиваться{}, // сбиваться с пути
rus_verbs:отлучиться{}, // отлучиться с поста
rus_verbs:сигануть{}, // сигануть с крыши
rus_verbs:сместить{}, // сместить с поста
rus_verbs:списать{}, // списать с оригинального устройства
инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы
деепричастие:слетая{},
rus_verbs:напиваться{}, // напиваться с горя
rus_verbs:свесить{}, // свесить с крыши
rus_verbs:заполучить{}, // заполучить со склада
rus_verbs:спадать{}, // спадать с глаз
rus_verbs:стартовать{}, // стартовать с мыса
rus_verbs:спереть{}, // спереть со склада
rus_verbs:согнать{}, // согнать с живота
rus_verbs:скатываться{}, // скатываться со стога
rus_verbs:сняться{}, // сняться с выборов
rus_verbs:слезать{}, // слезать со стола
rus_verbs:деваться{}, // деваться с подводной лодки
rus_verbs:огласить{}, // огласить с трибуны
rus_verbs:красть{}, // красть со склада
rus_verbs:расширить{}, // расширить с торца
rus_verbs:угадывать{}, // угадывать с полуслова
rus_verbs:оскорбить{}, // оскорбить со сцены
rus_verbs:срывать{}, // срывать с головы
rus_verbs:сшибить{}, // сшибить с коня
rus_verbs:сбивать{}, // сбивать с одежды
rus_verbs:содрать{}, // содрать с посетителей
rus_verbs:столкнуть{}, // столкнуть с горы
rus_verbs:отряхнуть{}, // отряхнуть с одежды
rus_verbs:сбрасывать{}, // сбрасывать с борта
rus_verbs:расстреливать{}, // расстреливать с борта вертолета
rus_verbs:придти{}, // мать скоро придет с работы
rus_verbs:съехать{}, // Миша съехал с горки
rus_verbs:свисать{}, // свисать с веток
rus_verbs:стянуть{}, // стянуть с кровати
rus_verbs:скинуть{}, // скинуть снег с плеча
rus_verbs:загреметь{}, // загреметь со стула
rus_verbs:сыпаться{}, // сыпаться с неба
rus_verbs:стряхнуть{}, // стряхнуть с головы
rus_verbs:сползти{}, // сползти со стула
rus_verbs:стереть{}, // стереть с экрана
rus_verbs:прогнать{}, // прогнать с фермы
rus_verbs:смахнуть{}, // смахнуть со стола
rus_verbs:спускать{}, // спускать с поводка
rus_verbs:деться{}, // деться с подводной лодки
rus_verbs:сдернуть{}, // сдернуть с себя
rus_verbs:сдвинуться{}, // сдвинуться с места
rus_verbs:слететь{}, // слететь с катушек
rus_verbs:обступить{}, // обступить со всех сторон
rus_verbs:снести{}, // снести с плеч
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков
деепричастие:сбегая{}, прилагательное:сбегающий{},
// прилагательное:сбегавший{ вид:несоверш },
rus_verbs:запить{}, // запить с горя
rus_verbs:рубануть{}, // рубануть с плеча
rus_verbs:чертыхнуться{}, // чертыхнуться с досады
rus_verbs:срываться{}, // срываться с цепи
rus_verbs:смыться{}, // смыться с уроков
rus_verbs:похитить{}, // похитить со склада
rus_verbs:смести{}, // смести со своего пути
rus_verbs:отгружать{}, // отгружать со склада
rus_verbs:отгрузить{}, // отгрузить со склада
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя
rus_verbs:взиматься{}, // Плата взимается с любого посетителя
rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги
rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги
rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков
rus_verbs:вспархивать{}, // вспархивать с цветка
rus_verbs:вспорхнуть{}, // вспорхнуть с ветки
rus_verbs:выбросить{}, // выбросить что-то с балкона
rus_verbs:выводить{}, // выводить с одежды пятна
rus_verbs:снять{}, // снять с головы
rus_verbs:начинать{}, // начинать с эскиза
rus_verbs:двинуться{}, // двинуться с места
rus_verbs:начинаться{}, // начинаться с гардероба
rus_verbs:стечь{}, // стечь с крыши
rus_verbs:слезть{}, // слезть с кучи
rus_verbs:спуститься{}, // спуститься с крыши
rus_verbs:сойти{}, // сойти с пьедестала
rus_verbs:свернуть{}, // свернуть с пути
rus_verbs:сорвать{}, // сорвать с цепи
rus_verbs:сорваться{}, // сорваться с поводка
rus_verbs:тронуться{}, // тронуться с места
rus_verbs:угадать{}, // угадать с первой попытки
rus_verbs:спустить{}, // спустить с лестницы
rus_verbs:соскочить{}, // соскочить с крючка
rus_verbs:сдвинуть{}, // сдвинуть с места
rus_verbs:подниматься{}, // туман, поднимающийся с болота
rus_verbs:подняться{}, // туман, поднявшийся с болота
rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног.
rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног.
rus_verbs:донестись{}, // С улицы донесся шум дождя.
rus_verbs:опасть{}, // Опавшие с дерева листья.
rus_verbs:махнуть{}, // Он махнул с берега в воду.
rus_verbs:исчезнуть{}, // исчезнуть с экрана
rus_verbs:свалиться{}, // свалиться со сцены
rus_verbs:упасть{}, // упасть с дерева
rus_verbs:вернуться{}, // Он ещё не вернулся с работы.
rus_verbs:сдувать{}, // сдувать пух с одуванчиков
rus_verbs:свергать{}, // свергать царя с трона
rus_verbs:сбиться{}, // сбиться с пути
rus_verbs:стирать{}, // стирать тряпкой надпись с доски
rus_verbs:убирать{}, // убирать мусор c пола
rus_verbs:удалять{}, // удалять игрока с поля
rus_verbs:окружить{}, // Япония окружена со всех сторон морями.
rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение.
глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы.
прилагательное:спокойный{}, // С этой стороны я спокоен.
rus_verbs:спросить{}, // С тебя за всё спросят.
rus_verbs:течь{}, // С него течёт пот.
rus_verbs:дуть{}, // С моря дует ветер.
rus_verbs:капать{}, // С его лица капали крупные капли пота.
rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол.
rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня.
rus_verbs:встать{}, // Все встали со стульев.
rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто.
rus_verbs:взять{}, // Возьми книгу с полки.
rus_verbs:спускаться{}, // Мы спускались с горы.
rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы.
rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок.
rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы.
rus_verbs:двигаться{}, // Он не двигался с места.
rus_verbs:отходить{}, // мой поезд отходит с первого пути
rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции
rus_verbs:падать{}, // снег падает с ветвей
rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия.
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:род} }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:парт} }
then return true
}
#endregion РОДИТЕЛЬНЫЙ
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:твор } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:род } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:с{} * }
then return false,-5
}
#endregion Предлог_С
/*
#region Предлог_ПОД
// -------------- ПРЕДЛОГ 'ПОД' -----------------------
fact гл_предл
{
if context { * предлог:под{} @regex("[a-z]+[0-9]*") }
then return true
}
// ПОД+вин.п. не может присоединяться к существительным, поэтому
// он присоединяется к любым глаголам.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:вин } }
then return true
}
wordentry_set Гл_ПОД_твор=
{
rus_verbs:извиваться{}, // извивалась под его длинными усами
rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ)
rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ)
rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ)
rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ)
rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ)
rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ)
rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть)
rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ)
rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ)
rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ)
rus_verbs:ПРОПОЛЗТИ{}, //
rus_verbs:ПРОПОЛЗАТЬ{}, //
rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ)
rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ)
rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ)
rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ)
rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ)
rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом
rus_verbs:иметься{}, // у каждого под рукой имелся арбалет
rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ)
rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ)
rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ)
rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ)
rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ)
rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ)
rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ)
rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ)
rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ)
rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ)
rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ)
rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ)
rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ)
rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор)
rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ)
rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ)
rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ)
rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ)
rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ)
rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ)
rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ)
rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ)
rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ)
rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ)
rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ)
rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ)
rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ)
rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ)
rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ)
rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ)
rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ)
rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ)
rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ)
rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ)
rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД)
rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ)
rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД)
rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ)
rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ)
rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ)
rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ)
rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ)
rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ)
rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ)
rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ)
rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ)
rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ)
rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ)
rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ)
rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ)
rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ)
rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ)
rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ)
rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ)
rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ)
rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ)
rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ)
rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ)
rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ)
rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ)
rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ)
rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ)
rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ)
rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ)
rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ)
rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ)
rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ)
rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД)
rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД)
rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД)
rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД)
rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД)
rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД)
rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД)
rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД)
rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор)
rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД)
rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД)
rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД)
rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД)
rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД)
rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД)
rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД)
rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД)
rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД)
rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД)
rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД)
rus_verbs:уснуть{}, // Миша уснет под одеялом
rus_verbs:пошевелиться{}, // пошевелиться под одеялом
rus_verbs:задохнуться{}, // задохнуться под слоем снега
rus_verbs:потечь{}, // потечь под избыточным давлением
rus_verbs:уцелеть{}, // уцелеть под завалами
rus_verbs:мерцать{}, // мерцать под лучами софитов
rus_verbs:поискать{}, // поискать под кроватью
rus_verbs:гудеть{}, // гудеть под нагрузкой
rus_verbs:посидеть{}, // посидеть под навесом
rus_verbs:укрыться{}, // укрыться под навесом
rus_verbs:утихнуть{}, // утихнуть под одеялом
rus_verbs:заскрипеть{}, // заскрипеть под тяжестью
rus_verbs:шелохнуться{}, // шелохнуться под одеялом
инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень
деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш },
инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш },
деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш },
rus_verbs:пониматься{}, // пониматься под успехом
rus_verbs:подразумеваться{}, // подразумеваться под правильным решением
rus_verbs:промокнуть{}, // промокнуть под проливным дождем
rus_verbs:засосать{}, // засосать под ложечкой
rus_verbs:подписаться{}, // подписаться под воззванием
rus_verbs:укрываться{}, // укрываться под навесом
rus_verbs:запыхтеть{}, // запыхтеть под одеялом
rus_verbs:мокнуть{}, // мокнуть под лождем
rus_verbs:сгибаться{}, // сгибаться под тяжестью снега
rus_verbs:намокнуть{}, // намокнуть под дождем
rus_verbs:подписываться{}, // подписываться под обращением
rus_verbs:тарахтеть{}, // тарахтеть под окнами
инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача.
деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{},
rus_verbs:лежать{}, // лежать под капельницей
rus_verbs:вымокать{}, // вымокать под дождём
rus_verbs:вымокнуть{}, // вымокнуть под дождём
rus_verbs:проворчать{}, // проворчать под нос
rus_verbs:хмыкнуть{}, // хмыкнуть под нос
rus_verbs:отыскать{}, // отыскать под кроватью
rus_verbs:дрогнуть{}, // дрогнуть под ударами
rus_verbs:проявляться{}, // проявляться под нагрузкой
rus_verbs:сдержать{}, // сдержать под контролем
rus_verbs:ложиться{}, // ложиться под клиента
rus_verbs:таять{}, // таять под весенним солнцем
rus_verbs:покатиться{}, // покатиться под откос
rus_verbs:лечь{}, // он лег под навесом
rus_verbs:идти{}, // идти под дождем
прилагательное:известный{}, // Он известен под этим именем.
rus_verbs:стоять{}, // Ящик стоит под столом.
rus_verbs:отступить{}, // Враг отступил под ударами наших войск.
rus_verbs:царапаться{}, // Мышь царапается под полом.
rus_verbs:спать{}, // заяц спокойно спал у себя под кустом
rus_verbs:загорать{}, // мы загораем под солнцем
ГЛ_ИНФ(мыть), // мыть руки под струёй воды
ГЛ_ИНФ(закопать),
ГЛ_ИНФ(спрятать),
ГЛ_ИНФ(прятать),
ГЛ_ИНФ(перепрятать)
}
fact гл_предл
{
if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } }
then return true
}
// для глаголов вне списка - запрещаем.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:твор } }
then return false,-10
}
fact гл_предл
{
if context { * предлог:под{} *:*{} }
then return false,-11
}
#endregion Предлог_ПОД
*/
#region Предлог_ОБ
// -------------- ПРЕДЛОГ 'ОБ' -----------------------
wordentry_set Гл_ОБ_предл=
{
rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ)
rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ)
rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ)
rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом?
rus_verbs:забывать{}, // Мы не можем забывать об их участи.
rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ)
rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ)
rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ)
rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ)
rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ)
rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ)
rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ)
rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ)
rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ)
rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ)
rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об)
rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об)
rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ)
rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ)
rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ)
rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе.
rus_verbs:кричать{}, // Все газеты кричат об этом событии.
rus_verbs:советоваться{}, // Она обо всём советуется с матерью.
rus_verbs:говориться{}, // об остальном говорилось легко.
rus_verbs:подумать{}, // нужно крепко обо всем подумать.
rus_verbs:напомнить{}, // черный дым напомнил об опасности.
rus_verbs:забыть{}, // забудь об этой роскоши.
rus_verbs:думать{}, // приходится обо всем думать самой.
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:информировать{}, // информировать об изменениях
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:заговорить{}, // заговорить об оплате
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:попросить{}, // попросить об услуге
rus_verbs:объявить{}, // объявить об отставке
rus_verbs:предупредить{}, // предупредить об аварии
rus_verbs:предупреждать{}, // предупреждать об опасности
rus_verbs:твердить{}, // твердить об обязанностях
rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:прочитать{}, // он читал об этом в учебнике
rus_verbs:узнать{}, // он узнал об этом из фильмов
rus_verbs:рассказать{}, // рассказать об экзаменах
rus_verbs:рассказывать{},
rus_verbs:договориться{}, // договориться об оплате
rus_verbs:договариваться{}, // договариваться об обмене
rus_verbs:болтать{}, // Не болтай об этом!
rus_verbs:проболтаться{}, // Не проболтайся об этом!
rus_verbs:заботиться{}, // кто заботится об урегулировании
rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне
rus_verbs:помнить{}, // всем советую об этом помнить
rus_verbs:мечтать{} // Мечтать об успехе
}
fact гл_предл
{
if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { * предлог:об{} @regex("[a-z]+[0-9]*") }
then return true
}
// остальные глаголы не могут связываться
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:предл } }
then return false, -4
}
wordentry_set Гл_ОБ_вин=
{
rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ)
rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ)
rus_verbs:опереться{}, // Он опёрся об стену.
rus_verbs:опираться{},
rus_verbs:постучать{}, // постучал лбом об пол.
rus_verbs:удариться{}, // бутылка глухо ударилась об землю.
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:царапаться{} // Днище лодки царапалось обо что-то.
}
fact гл_предл
{
if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:об{} *:*{} }
then return false,-5
}
#endregion Предлог_ОБ
#region Предлог_О
// ------------------- С ПРЕДЛОГОМ 'О' ----------------------
wordentry_set Гл_О_Вин={
rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену.
rus_verbs:болтать{}, // Болтали чаще всего о пустяках.
rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг.
rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол.
rus_verbs:бахнуться{}, // Бахнуться головой о стол.
rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ)
rus_verbs:ВЫТИРАТЬ{}, //
rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ)
rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ)
rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ)
rus_verbs:ЛЯЗГАТЬ{}, //
rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки
rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ)
rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ)
rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ)
rus_verbs:колотиться{}, // сердце его колотилось о ребра
rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей.
rus_verbs:биться{}, // биться головой о стену? (биться о)
rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о)
rus_verbs:разбиваться{}, // волны разбивались о скалу
rus_verbs:разбивать{}, // Разбивает голову о прутья клетки.
rus_verbs:облокотиться{}, // облокотиться о стену
rus_verbs:точить{}, // точить о точильный камень
rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень
rus_verbs:потереться{}, // потереться о дерево
rus_verbs:ушибиться{}, // ушибиться о дерево
rus_verbs:тереться{}, // тереться о ствол
rus_verbs:шмякнуться{}, // шмякнуться о землю
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:тереть{}, // тереть о камень
rus_verbs:потереть{}, // потереть о колено
rus_verbs:удариться{}, // удариться о край
rus_verbs:споткнуться{}, // споткнуться о камень
rus_verbs:запнуться{}, // запнуться о камень
rus_verbs:запинаться{}, // запинаться о камни
rus_verbs:ударяться{}, // ударяться о бортик
rus_verbs:стукнуться{}, // стукнуться о бортик
rus_verbs:стукаться{}, // стукаться о бортик
rus_verbs:опереться{}, // Он опёрся локтями о стол.
rus_verbs:плескаться{} // Вода плещется о берег.
}
fact гл_предл
{
if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:вин } }
then return false,-5
}
wordentry_set Гл_О_предл={
rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ)
rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ)
rus_verbs:РАССПРАШИВАТЬ{}, //
rus_verbs:слушать{}, // ты будешь слушать о них?
rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно
rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ)
rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ)
rus_verbs:сложить{}, // о вас сложены легенды
rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О)
rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О)
rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О)
rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О)
rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О)
rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О)
rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О)
rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О)
rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О)
rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О)
rus_verbs:осведомиться{}, // офицер осведомился о цели визита
rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о)
rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О)
rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о)
rus_verbs:зайти{}, // Разговор зашёл о политике.
rus_verbs:порассказать{}, // порассказать о своих путешествиях
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви
деепричастие:спев{}, прилагательное:спевший{ вид:соверш },
прилагательное:спетый{},
rus_verbs:напеть{},
rus_verbs:разговаривать{}, // разговаривать с другом о жизни
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
//rus_verbs:заботиться{}, // заботиться о престарелых родителях
rus_verbs:раздумывать{}, // раздумывать о новой работе
rus_verbs:договариваться{}, // договариваться о сумме компенсации
rus_verbs:молить{}, // молить о пощаде
rus_verbs:отзываться{}, // отзываться о книге
rus_verbs:подумывать{}, // подумывать о новом подходе
rus_verbs:поговаривать{}, // поговаривать о загадочном звере
rus_verbs:обмолвиться{}, // обмолвиться о проклятии
rus_verbs:условиться{}, // условиться о поддержке
rus_verbs:призадуматься{}, // призадуматься о последствиях
rus_verbs:известить{}, // известить о поступлении
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:напевать{}, // напевать о любви
rus_verbs:помышлять{}, // помышлять о новом деле
rus_verbs:переговорить{}, // переговорить о правилах
rus_verbs:повествовать{}, // повествовать о событиях
rus_verbs:слыхивать{}, // слыхивать о чудище
rus_verbs:потолковать{}, // потолковать о планах
rus_verbs:проговориться{}, // проговориться о планах
rus_verbs:умолчать{}, // умолчать о штрафах
rus_verbs:хлопотать{}, // хлопотать о премии
rus_verbs:уведомить{}, // уведомить о поступлении
rus_verbs:горевать{}, // горевать о потере
rus_verbs:запамятовать{}, // запамятовать о важном мероприятии
rus_verbs:заикнуться{}, // заикнуться о прибавке
rus_verbs:информировать{}, // информировать о событиях
rus_verbs:проболтаться{}, // проболтаться о кладе
rus_verbs:поразмыслить{}, // поразмыслить о судьбе
rus_verbs:заикаться{}, // заикаться о деньгах
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:печься{}, // печься о всеобщем благе
rus_verbs:разглагольствовать{}, // разглагольствовать о правах
rus_verbs:размечтаться{}, // размечтаться о будущем
rus_verbs:лепетать{}, // лепетать о невиновности
rus_verbs:грезить{}, // грезить о большой и чистой любви
rus_verbs:залепетать{}, // залепетать о сокровищах
rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде
rus_verbs:протрубить{}, // протрубить о победе
rus_verbs:извещать{}, // извещать о поступлении
rus_verbs:трубить{}, // трубить о поимке разбойников
rus_verbs:осведомляться{}, // осведомляться о судьбе
rus_verbs:поразмышлять{}, // поразмышлять о неизбежном
rus_verbs:слагать{}, // слагать о подвигах викингов
rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи
rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании
rus_verbs:закидывать{}, // закидывать сообщениями об ошибках
rus_verbs:базарить{}, // пацаны базарили о телках
rus_verbs:балагурить{}, // мужики балагурили о новом председателе
rus_verbs:балакать{}, // мужики балакали о новом председателе
rus_verbs:беспокоиться{}, // Она беспокоится о детях
rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве
rus_verbs:возмечтать{}, // возмечтать о счастливом мире
rus_verbs:вопить{}, // Кто-то вопил о несправедливости
rus_verbs:сказать{}, // сказать что-то новое о ком-то
rus_verbs:знать{}, // знать о ком-то что-то пикантное
rus_verbs:подумать{}, // подумать о чём-то
rus_verbs:думать{}, // думать о чём-то
rus_verbs:узнать{}, // узнать о происшествии
rus_verbs:помнить{}, // помнить о задании
rus_verbs:просить{}, // просить о коде доступа
rus_verbs:забыть{}, // забыть о своих обязанностях
rus_verbs:сообщить{}, // сообщить о заложенной мине
rus_verbs:заявить{}, // заявить о пропаже
rus_verbs:задуматься{}, // задуматься о смерти
rus_verbs:спрашивать{}, // спрашивать о поступлении товара
rus_verbs:догадаться{}, // догадаться о причинах
rus_verbs:договориться{}, // договориться о собеседовании
rus_verbs:мечтать{}, // мечтать о сцене
rus_verbs:поговорить{}, // поговорить о наболевшем
rus_verbs:размышлять{}, // размышлять о насущном
rus_verbs:напоминать{}, // напоминать о себе
rus_verbs:пожалеть{}, // пожалеть о содеянном
rus_verbs:ныть{}, // ныть о прибавке
rus_verbs:сообщать{}, // сообщать о победе
rus_verbs:догадываться{}, // догадываться о первопричине
rus_verbs:поведать{}, // поведать о тайнах
rus_verbs:умолять{}, // умолять о пощаде
rus_verbs:сожалеть{}, // сожалеть о случившемся
rus_verbs:жалеть{}, // жалеть о случившемся
rus_verbs:забывать{}, // забывать о случившемся
rus_verbs:упоминать{}, // упоминать о предках
rus_verbs:позабыть{}, // позабыть о своем обещании
rus_verbs:запеть{}, // запеть о любви
rus_verbs:скорбеть{}, // скорбеть о усопшем
rus_verbs:задумываться{}, // задумываться о смене работы
rus_verbs:позаботиться{}, // позаботиться о престарелых родителях
rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината
rus_verbs:попросить{}, // попросить о замене
rus_verbs:предупредить{}, // предупредить о замене
rus_verbs:предупреждать{}, // предупреждать о замене
rus_verbs:твердить{}, // твердить о замене
rus_verbs:заявлять{}, // заявлять о подлоге
rus_verbs:петь{}, // певица, поющая о лете
rus_verbs:проинформировать{}, // проинформировать о переговорах
rus_verbs:порассказывать{}, // порассказывать о событиях
rus_verbs:послушать{}, // послушать о новинках
rus_verbs:заговорить{}, // заговорить о плате
rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой.
rus_verbs:оставить{}, // Он оставил о себе печальную память.
rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях
rus_verbs:спорить{}, // они спорили о законе
глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия.
глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия.
rus_verbs:прочитать{}, // Я прочитал о тебе
rus_verbs:услышать{}, // Я услышал о нем
rus_verbs:помечтать{}, // Девочки помечтали о принце
rus_verbs:слышать{}, // Мальчик слышал о приведениях
rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке
rus_verbs:грустить{}, // Я грущу о тебе
rus_verbs:осведомить{}, // о последних достижениях науки
rus_verbs:рассказывать{}, // Антонио рассказывает о работе
rus_verbs:говорить{}, // говорим о трех больших псах
rus_verbs:идти{} // Вопрос идёт о войне.
}
fact гл_предл
{
if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } }
then return true
}
// Мы поделились впечатлениями о выставке.
// ^^^^^^^^^^ ^^^^^^^^^^
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:о{} *:*{} }
then return false,-5
}
#endregion Предлог_О
#region Предлог_ПО
// ------------------- С ПРЕДЛОГОМ 'ПО' ----------------------
// для этих глаголов - запрещаем связывание с ПО+дат.п.
wordentry_set Глаг_ПО_Дат_Запр=
{
rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:закончить{},
rus_verbs:мочь{},
rus_verbs:хотеть{}
}
fact гл_предл
{
if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } }
then return false,-10
}
// По умолчанию разрешаем связывание в паттернах типа
// Я иду по шоссе
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:дат } }
then return true
}
wordentry_set Глаг_ПО_Вин=
{
rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ)
rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО)
rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера
rus_verbs:засадить{}, // засадить по рукоятку
rus_verbs:увязнуть{} // увязнуть по колено
}
fact гл_предл
{
if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_ПО
#region Предлог_К
// ------------------- С ПРЕДЛОГОМ 'К' ----------------------
wordentry_set Гл_К_Дат={
rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна.
rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску.
прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ)
rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ)
rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ)
rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ)
rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ)
rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ)
rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ)
rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ)
rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ)
rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, //
rus_verbs:ПРИНОРОВИТЬСЯ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ)
rus_verbs:СПИКИРОВАТЬ{}, //
rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С)
rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ)
rus_verbs:ПРОТЯНУТЬ{}, //
rus_verbs:ТЯНУТЬ{}, //
rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,,
rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, //
rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, //
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, //
rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ)
rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке.
rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ)
rus_verbs:хотеть{},
rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ)
rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ)
rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ)
rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ)
rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ)
rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ)
rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ)
rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ)
rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ)
rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г
rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ)
rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ)
rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К)
rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К)
rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К)
rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К)
rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К)
прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К)
безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К)
rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К)
rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К)
rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К)
rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К)
rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К)
rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К)
rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К)
rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К)
rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К)
rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К)
rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К)
rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К)
rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К)
rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К)
rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К)
rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К)
rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К)
rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К)
rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К)
rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К)
rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К)
rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К)
rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К)
глагол:быть{}, // к тебе есть вопросы.
прилагательное:равнодушный{}, // Он равнодушен к музыке.
rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К)
rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К)
инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К)
rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К)
rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к)
rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К)
rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К)
rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К)
rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К)
rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К)
rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К)
rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К)
rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к)
rus_verbs:просить{}, // Директор просит вас к себе. (просить к)
rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к)
rus_verbs:присесть{}, // старик присел к огню. (присесть к)
rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К)
rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к)
rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к)
rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К)
rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К)
rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К)
rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К)
rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к)
rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К)
rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К)
rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К)
rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К)
rus_verbs:подходить{}, // цвет подходил ей к лицу.
rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К)
rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К)
rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К)
rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К)
rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К)
rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К)
rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к)
rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К)
rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К)
rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к)
rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к)
rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К)
rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К)
rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К)
rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К)
rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к)
rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к)
rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к)
rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К)
rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к)
rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к)
rus_verbs:требовать{}, // вас требует к себе император. (требовать к)
rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к)
rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к)
rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К)
rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К)
rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к)
rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К)
rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К)
rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к)
rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к)
rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к)
rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К)
rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к)
rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к)
rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к)
rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К)
rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К)
rus_verbs:выехать{}, // почти сразу мы выехали к реке.
rus_verbs:пододвигаться{}, // пододвигайся к окну
rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам.
rus_verbs:представить{}, // Его представили к ордену.
rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу.
rus_verbs:выскочить{}, // тем временем они выскочили к реке.
rus_verbs:выйти{}, // тем временем они вышли к лестнице.
rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе.
rus_verbs:приложить{}, // приложить к детали повышенное усилие
rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку)
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю
rus_verbs:прыгать{}, // прыгать к хозяину на стол
rus_verbs:приглашать{}, // приглашать к доктору
rus_verbs:рваться{}, // Чужие люди рвутся к власти
rus_verbs:понестись{}, // понестись к обрыву
rus_verbs:питать{}, // питать привязанность к алкоголю
rus_verbs:заехать{}, // Коля заехал к Оле
rus_verbs:переехать{}, // переехать к родителям
rus_verbs:ползти{}, // ползти к дороге
rus_verbs:сводиться{}, // сводиться к элементарному действию
rus_verbs:добавлять{}, // добавлять к общей сумме
rus_verbs:подбросить{}, // подбросить к потолку
rus_verbs:призывать{}, // призывать к спокойствию
rus_verbs:пробираться{}, // пробираться к партизанам
rus_verbs:отвезти{}, // отвезти к родителям
rus_verbs:применяться{}, // применяться к уравнению
rus_verbs:сходиться{}, // сходиться к точному решению
rus_verbs:допускать{}, // допускать к сдаче зачета
rus_verbs:свести{}, // свести к нулю
rus_verbs:придвинуть{}, // придвинуть к мальчику
rus_verbs:подготовить{}, // подготовить к печати
rus_verbs:подобраться{}, // подобраться к оленю
rus_verbs:заторопиться{}, // заторопиться к выходу
rus_verbs:пристать{}, // пристать к берегу
rus_verbs:поманить{}, // поманить к себе
rus_verbs:припасть{}, // припасть к алтарю
rus_verbs:притащить{}, // притащить к себе домой
rus_verbs:прижимать{}, // прижимать к груди
rus_verbs:подсесть{}, // подсесть к симпатичной девочке
rus_verbs:придвинуться{}, // придвинуться к окну
rus_verbs:отпускать{}, // отпускать к другу
rus_verbs:пригнуться{}, // пригнуться к земле
rus_verbs:пристроиться{}, // пристроиться к колонне
rus_verbs:сгрести{}, // сгрести к себе
rus_verbs:удрать{}, // удрать к цыганам
rus_verbs:прибавиться{}, // прибавиться к общей сумме
rus_verbs:присмотреться{}, // присмотреться к покупке
rus_verbs:подкатить{}, // подкатить к трюму
rus_verbs:клонить{}, // клонить ко сну
rus_verbs:проследовать{}, // проследовать к выходу
rus_verbs:пододвинуть{}, // пододвинуть к себе
rus_verbs:применять{}, // применять к сотрудникам
rus_verbs:прильнуть{}, // прильнуть к экранам
rus_verbs:подвинуть{}, // подвинуть к себе
rus_verbs:примчаться{}, // примчаться к папе
rus_verbs:подкрасться{}, // подкрасться к жертве
rus_verbs:привязаться{}, // привязаться к собаке
rus_verbs:забирать{}, // забирать к себе
rus_verbs:прорваться{}, // прорваться к кассе
rus_verbs:прикасаться{}, // прикасаться к коже
rus_verbs:уносить{}, // уносить к себе
rus_verbs:подтянуться{}, // подтянуться к месту
rus_verbs:привозить{}, // привозить к ветеринару
rus_verbs:подползти{}, // подползти к зайцу
rus_verbs:приблизить{}, // приблизить к глазам
rus_verbs:применить{}, // применить к уравнению простое преобразование
rus_verbs:приглядеться{}, // приглядеться к изображению
rus_verbs:приложиться{}, // приложиться к ручке
rus_verbs:приставать{}, // приставать к девчонкам
rus_verbs:запрещаться{}, // запрещаться к показу
rus_verbs:прибегать{}, // прибегать к насилию
rus_verbs:побудить{}, // побудить к действиям
rus_verbs:притягивать{}, // притягивать к себе
rus_verbs:пристроить{}, // пристроить к полезному делу
rus_verbs:приговорить{}, // приговорить к смерти
rus_verbs:склоняться{}, // склоняться к прекращению разработки
rus_verbs:подъезжать{}, // подъезжать к вокзалу
rus_verbs:привалиться{}, // привалиться к забору
rus_verbs:наклоняться{}, // наклоняться к щенку
rus_verbs:подоспеть{}, // подоспеть к обеду
rus_verbs:прилипнуть{}, // прилипнуть к окну
rus_verbs:приволочь{}, // приволочь к себе
rus_verbs:устремляться{}, // устремляться к вершине
rus_verbs:откатиться{}, // откатиться к исходным позициям
rus_verbs:побуждать{}, // побуждать к действиям
rus_verbs:прискакать{}, // прискакать к кормежке
rus_verbs:присматриваться{}, // присматриваться к новичку
rus_verbs:прижиматься{}, // прижиматься к борту
rus_verbs:жаться{}, // жаться к огню
rus_verbs:передвинуть{}, // передвинуть к окну
rus_verbs:допускаться{}, // допускаться к экзаменам
rus_verbs:прикрепить{}, // прикрепить к корпусу
rus_verbs:отправлять{}, // отправлять к специалистам
rus_verbs:перебежать{}, // перебежать к врагам
rus_verbs:притронуться{}, // притронуться к реликвии
rus_verbs:заспешить{}, // заспешить к семье
rus_verbs:ревновать{}, // ревновать к сопернице
rus_verbs:подступить{}, // подступить к горлу
rus_verbs:уводить{}, // уводить к ветеринару
rus_verbs:побросать{}, // побросать к ногам
rus_verbs:подаваться{}, // подаваться к ужину
rus_verbs:приписывать{}, // приписывать к достижениям
rus_verbs:относить{}, // относить к растениям
rus_verbs:принюхаться{}, // принюхаться к ароматам
rus_verbs:подтащить{}, // подтащить к себе
rus_verbs:прислонить{}, // прислонить к стене
rus_verbs:подплыть{}, // подплыть к бую
rus_verbs:опаздывать{}, // опаздывать к стилисту
rus_verbs:примкнуть{}, // примкнуть к деомнстрантам
rus_verbs:стекаться{}, // стекаются к стенам тюрьмы
rus_verbs:подготовиться{}, // подготовиться к марафону
rus_verbs:приглядываться{}, // приглядываться к новичку
rus_verbs:присоединяться{}, // присоединяться к сообществу
rus_verbs:клониться{}, // клониться ко сну
rus_verbs:привыкать{}, // привыкать к хорошему
rus_verbs:принудить{}, // принудить к миру
rus_verbs:уплыть{}, // уплыть к далекому берегу
rus_verbs:утащить{}, // утащить к детенышам
rus_verbs:приплыть{}, // приплыть к финишу
rus_verbs:подбегать{}, // подбегать к хозяину
rus_verbs:лишаться{}, // лишаться средств к существованию
rus_verbs:приступать{}, // приступать к операции
rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике
rus_verbs:подключить{}, // подключить к трубе
rus_verbs:подключиться{}, // подключиться к сети
rus_verbs:прилить{}, // прилить к лицу
rus_verbs:стучаться{}, // стучаться к соседям
rus_verbs:пристегнуть{}, // пристегнуть к креслу
rus_verbs:присоединить{}, // присоединить к сети
rus_verbs:отбежать{}, // отбежать к противоположной стене
rus_verbs:подвезти{}, // подвезти к набережной
rus_verbs:прибегнуть{}, // прибегнуть к хитрости
rus_verbs:приучить{}, // приучить к туалету
rus_verbs:подталкивать{}, // подталкивать к выходу
rus_verbs:прорываться{}, // прорываться к выходу
rus_verbs:увозить{}, // увозить к ветеринару
rus_verbs:засеменить{}, // засеменить к выходу
rus_verbs:крепиться{}, // крепиться к потолку
rus_verbs:прибрать{}, // прибрать к рукам
rus_verbs:пристраститься{}, // пристраститься к наркотикам
rus_verbs:поспеть{}, // поспеть к обеду
rus_verbs:привязывать{}, // привязывать к дереву
rus_verbs:прилагать{}, // прилагать к документам
rus_verbs:переправить{}, // переправить к дедушке
rus_verbs:подогнать{}, // подогнать к воротам
rus_verbs:тяготеть{}, // тяготеть к социализму
rus_verbs:подбираться{}, // подбираться к оленю
rus_verbs:подступать{}, // подступать к горлу
rus_verbs:примыкать{}, // примыкать к первому элементу
rus_verbs:приладить{}, // приладить к велосипеду
rus_verbs:подбрасывать{}, // подбрасывать к потолку
rus_verbs:перевозить{}, // перевозить к новому месту дислокации
rus_verbs:усаживаться{}, // усаживаться к окну
rus_verbs:приближать{}, // приближать к глазам
rus_verbs:попроситься{}, // попроситься к бабушке
rus_verbs:прибить{}, // прибить к доске
rus_verbs:перетащить{}, // перетащить к себе
rus_verbs:прицепить{}, // прицепить к паровозу
rus_verbs:прикладывать{}, // прикладывать к ране
rus_verbs:устареть{}, // устареть к началу войны
rus_verbs:причалить{}, // причалить к пристани
rus_verbs:приспособиться{}, // приспособиться к опозданиям
rus_verbs:принуждать{}, // принуждать к миру
rus_verbs:соваться{}, // соваться к директору
rus_verbs:протолкаться{}, // протолкаться к прилавку
rus_verbs:приковать{}, // приковать к батарее
rus_verbs:подкрадываться{}, // подкрадываться к суслику
rus_verbs:подсадить{}, // подсадить к арестонту
rus_verbs:прикатить{}, // прикатить к финишу
rus_verbs:протащить{}, // протащить к владыке
rus_verbs:сужаться{}, // сужаться к основанию
rus_verbs:присовокупить{}, // присовокупить к пожеланиям
rus_verbs:пригвоздить{}, // пригвоздить к доске
rus_verbs:отсылать{}, // отсылать к первоисточнику
rus_verbs:изготовиться{}, // изготовиться к прыжку
rus_verbs:прилагаться{}, // прилагаться к покупке
rus_verbs:прицепиться{}, // прицепиться к вагону
rus_verbs:примешиваться{}, // примешиваться к вину
rus_verbs:переселить{}, // переселить к старшекурсникам
rus_verbs:затрусить{}, // затрусить к выходе
rus_verbs:приспособить{}, // приспособить к обогреву
rus_verbs:примериться{}, // примериться к аппарату
rus_verbs:прибавляться{}, // прибавляться к пенсии
rus_verbs:подкатиться{}, // подкатиться к воротам
rus_verbs:стягивать{}, // стягивать к границе
rus_verbs:дописать{}, // дописать к роману
rus_verbs:подпустить{}, // подпустить к корове
rus_verbs:склонять{}, // склонять к сотрудничеству
rus_verbs:припечатать{}, // припечатать к стене
rus_verbs:охладеть{}, // охладеть к музыке
rus_verbs:пришить{}, // пришить к шинели
rus_verbs:принюхиваться{}, // принюхиваться к ветру
rus_verbs:подрулить{}, // подрулить к барышне
rus_verbs:наведаться{}, // наведаться к оракулу
rus_verbs:клеиться{}, // клеиться к конверту
rus_verbs:перетянуть{}, // перетянуть к себе
rus_verbs:переметнуться{}, // переметнуться к конкурентам
rus_verbs:липнуть{}, // липнуть к сокурсницам
rus_verbs:поковырять{}, // поковырять к выходу
rus_verbs:подпускать{}, // подпускать к пульту управления
rus_verbs:присосаться{}, // присосаться к источнику
rus_verbs:приклеить{}, // приклеить к стеклу
rus_verbs:подтягивать{}, // подтягивать к себе
rus_verbs:подкатывать{}, // подкатывать к даме
rus_verbs:притрагиваться{}, // притрагиваться к опухоли
rus_verbs:слетаться{}, // слетаться к водопою
rus_verbs:хаживать{}, // хаживать к батюшке
rus_verbs:привлекаться{}, // привлекаться к административной ответственности
rus_verbs:подзывать{}, // подзывать к себе
rus_verbs:прикладываться{}, // прикладываться к иконе
rus_verbs:подтягиваться{}, // подтягиваться к парламенту
rus_verbs:прилепить{}, // прилепить к стенке холодильника
rus_verbs:пододвинуться{}, // пододвинуться к экрану
rus_verbs:приползти{}, // приползти к дереву
rus_verbs:запаздывать{}, // запаздывать к обеду
rus_verbs:припереть{}, // припереть к стене
rus_verbs:нагибаться{}, // нагибаться к цветку
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам
деепричастие:сгоняв{},
rus_verbs:поковылять{}, // поковылять к выходу
rus_verbs:привалить{}, // привалить к столбу
rus_verbs:отпроситься{}, // отпроситься к родителям
rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям
rus_verbs:прилипать{}, // прилипать к рукам
rus_verbs:подсоединить{}, // подсоединить к приборам
rus_verbs:приливать{}, // приливать к голове
rus_verbs:подселить{}, // подселить к другим новичкам
rus_verbs:прилепиться{}, // прилепиться к шкуре
rus_verbs:подлетать{}, // подлетать к пункту назначения
rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями
rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг
rus_verbs:льнуть{}, // льнуть к заботливому хозяину
rus_verbs:привязываться{}, // привязываться к любящему хозяину
rus_verbs:приклеиться{}, // приклеиться к спине
rus_verbs:стягиваться{}, // стягиваться к сенату
rus_verbs:подготавливать{}, // подготавливать к выходу на арену
rus_verbs:приглашаться{}, // приглашаться к доктору
rus_verbs:причислять{}, // причислять к отличникам
rus_verbs:приколоть{}, // приколоть к лацкану
rus_verbs:наклонять{}, // наклонять к горизонту
rus_verbs:припадать{}, // припадать к первоисточнику
rus_verbs:приобщиться{}, // приобщиться к культурному наследию
rus_verbs:придираться{}, // придираться к мелким ошибкам
rus_verbs:приучать{}, // приучать к лотку
rus_verbs:промотать{}, // промотать к началу
rus_verbs:прихлынуть{}, // прихлынуть к голове
rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу
rus_verbs:прикрутить{}, // прикрутить к велосипеду
rus_verbs:подплывать{}, // подплывать к лодке
rus_verbs:приравниваться{}, // приравниваться к побегу
rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами
rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы
rus_verbs:приткнуться{}, // приткнуться к первой группе туристов
rus_verbs:приручить{}, // приручить котика к лотку
rus_verbs:приковывать{}, // приковывать к себе все внимание прессы
rus_verbs:приготовляться{}, // приготовляться к первому экзамену
rus_verbs:остыть{}, // Вода остынет к утру.
rus_verbs:приехать{}, // Он приедет к концу будущей недели.
rus_verbs:подсаживаться{},
rus_verbs:успевать{}, // успевать к стилисту
rus_verbs:привлекать{}, // привлекать к себе внимание
прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму
rus_verbs:прийтись{}, // прийтись ко двору
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы
инфинитив:адаптироваться{вид:несоверш},
глагол:адаптироваться{вид:соверш},
глагол:адаптироваться{вид:несоверш},
деепричастие:адаптировавшись{},
деепричастие:адаптируясь{},
прилагательное:адаптировавшийся{вид:соверш},
//+прилагательное:адаптировавшийся{вид:несоверш},
прилагательное:адаптирующийся{},
rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей
rus_verbs:близиться{}, // Шторм близится к побережью
rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне
rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки
rus_verbs:причислить{}, // Мы причислили его к числу экспертов
rus_verbs:вести{}, // Наша партия ведет народ к процветанию
rus_verbs:взывать{}, // Учителя взывают к совести хулигана
rus_verbs:воззвать{}, // воззвать соплеменников к оружию
rus_verbs:возревновать{}, // возревновать к поклонникам
rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью
rus_verbs:восходить{}, // восходить к вершине
rus_verbs:восшествовать{}, // восшествовать к вершине
rus_verbs:успеть{}, // успеть к обеду
rus_verbs:повернуться{}, // повернуться к кому-то
rus_verbs:обратиться{}, // обратиться к охраннику
rus_verbs:звать{}, // звать к столу
rus_verbs:отправиться{}, // отправиться к парикмахеру
rus_verbs:обернуться{}, // обернуться к зовущему
rus_verbs:явиться{}, // явиться к следователю
rus_verbs:уехать{}, // уехать к родне
rus_verbs:прибыть{}, // прибыть к перекличке
rus_verbs:привыкнуть{}, // привыкнуть к голоду
rus_verbs:уходить{}, // уходить к цыганам
rus_verbs:привести{}, // привести к себе
rus_verbs:шагнуть{}, // шагнуть к славе
rus_verbs:относиться{}, // относиться к прежним периодам
rus_verbs:подослать{}, // подослать к врагам
rus_verbs:поспешить{}, // поспешить к обеду
rus_verbs:зайти{}, // зайти к подруге
rus_verbs:позвать{}, // позвать к себе
rus_verbs:потянуться{}, // потянуться к рычагам
rus_verbs:пускать{}, // пускать к себе
rus_verbs:отвести{}, // отвести к врачу
rus_verbs:приблизиться{}, // приблизиться к решению задачи
rus_verbs:прижать{}, // прижать к стене
rus_verbs:отправить{}, // отправить к доктору
rus_verbs:падать{}, // падать к многолетним минимумам
rus_verbs:полезть{}, // полезть к дерущимся
rus_verbs:лезть{}, // Ты сама ко мне лезла!
rus_verbs:направить{}, // направить к майору
rus_verbs:приводить{}, // приводить к дантисту
rus_verbs:кинуться{}, // кинуться к двери
rus_verbs:поднести{}, // поднести к глазам
rus_verbs:подниматься{}, // подниматься к себе
rus_verbs:прибавить{}, // прибавить к результату
rus_verbs:зашагать{}, // зашагать к выходу
rus_verbs:склониться{}, // склониться к земле
rus_verbs:стремиться{}, // стремиться к вершине
rus_verbs:лететь{}, // лететь к родственникам
rus_verbs:ездить{}, // ездить к любовнице
rus_verbs:приближаться{}, // приближаться к финише
rus_verbs:помчаться{}, // помчаться к стоматологу
rus_verbs:прислушаться{}, // прислушаться к происходящему
rus_verbs:изменить{}, // изменить к лучшему собственную жизнь
rus_verbs:проявить{}, // проявить к погибшим сострадание
rus_verbs:подбежать{}, // подбежать к упавшему
rus_verbs:терять{}, // терять к партнерам доверие
rus_verbs:пропустить{}, // пропустить к певцу
rus_verbs:подвести{}, // подвести к глазам
rus_verbs:меняться{}, // меняться к лучшему
rus_verbs:заходить{}, // заходить к другу
rus_verbs:рвануться{}, // рвануться к воде
rus_verbs:привлечь{}, // привлечь к себе внимание
rus_verbs:присоединиться{}, // присоединиться к сети
rus_verbs:приезжать{}, // приезжать к дедушке
rus_verbs:дернуться{}, // дернуться к борту
rus_verbs:подъехать{}, // подъехать к воротам
rus_verbs:готовиться{}, // готовиться к дождю
rus_verbs:убежать{}, // убежать к маме
rus_verbs:поднимать{}, // поднимать к источнику сигнала
rus_verbs:отослать{}, // отослать к руководителю
rus_verbs:приготовиться{}, // приготовиться к худшему
rus_verbs:приступить{}, // приступить к выполнению обязанностей
rus_verbs:метнуться{}, // метнуться к фонтану
rus_verbs:прислушиваться{}, // прислушиваться к голосу разума
rus_verbs:побрести{}, // побрести к выходу
rus_verbs:мчаться{}, // мчаться к успеху
rus_verbs:нестись{}, // нестись к обрыву
rus_verbs:попадать{}, // попадать к хорошему костоправу
rus_verbs:опоздать{}, // опоздать к психотерапевту
rus_verbs:посылать{}, // посылать к доктору
rus_verbs:поплыть{}, // поплыть к берегу
rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе
rus_verbs:отнести{}, // отнести животное к ветеринару
rus_verbs:прислониться{}, // прислониться к стволу
rus_verbs:наклонить{}, // наклонить к миске с молоком
rus_verbs:прикоснуться{}, // прикоснуться к поверхности
rus_verbs:увезти{}, // увезти к бабушке
rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия
rus_verbs:подозвать{}, // подозвать к себе
rus_verbs:улететь{}, // улететь к теплым берегам
rus_verbs:ложиться{}, // ложиться к мужу
rus_verbs:убираться{}, // убираться к чертовой бабушке
rus_verbs:класть{}, // класть к другим документам
rus_verbs:доставлять{}, // доставлять к подъезду
rus_verbs:поворачиваться{}, // поворачиваться к источнику шума
rus_verbs:заглядывать{}, // заглядывать к любовнице
rus_verbs:занести{}, // занести к заказчикам
rus_verbs:прибежать{}, // прибежать к папе
rus_verbs:притянуть{}, // притянуть к причалу
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:подать{}, // он подал лимузин к подъезду
rus_verbs:подавать{}, // она подавала соус к мясу
rus_verbs:приобщаться{}, // приобщаться к культуре
прилагательное:неспособный{}, // Наша дочка неспособна к учению.
прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару
прилагательное:предназначенный{}, // Старый дом предназначен к сносу.
прилагательное:внимательный{}, // Она всегда внимательна к гостям.
прилагательное:назначенный{}, // Дело назначено к докладу.
прилагательное:разрешенный{}, // Эта книга разрешена к печати.
прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам.
прилагательное:готовый{}, // Я готов к экзаменам.
прилагательное:требовательный{}, // Он очень требователен к себе.
прилагательное:жадный{}, // Он жаден к деньгам.
прилагательное:глухой{}, // Он глух к моей просьбе.
прилагательное:добрый{}, // Он добр к детям.
rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам.
rus_verbs:плыть{}, // Пароход плыл к берегу.
rus_verbs:пойти{}, // я пошел к доктору
rus_verbs:придти{}, // придти к выводу
rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом.
rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений.
rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам.
rus_verbs:спускаться{}, // Улица круто спускается к реке.
rus_verbs:спуститься{}, // Мы спустились к реке.
rus_verbs:пустить{}, // пускать ко дну
rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью!
rus_verbs:отойти{}, // Дом отошёл к племяннику.
rus_verbs:отходить{}, // Коля отходил ко сну.
rus_verbs:приходить{}, // местные жители к нему приходили лечиться
rus_verbs:кидаться{}, // не кидайся к столу
rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу.
rus_verbs:закончиться{}, // Собрание закончилось к вечеру.
rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему.
rus_verbs:направиться{}, // Мы сошли на берег и направились к городу.
rus_verbs:направляться{},
rus_verbs:свестись{}, // Всё свелось к нулю.
rus_verbs:прислать{}, // Пришлите кого-нибудь к ней.
rus_verbs:присылать{}, // Он присылал к должнику своих головорезов
rus_verbs:подлететь{}, // Самолёт подлетел к лесу.
rus_verbs:возвращаться{}, // он возвращается к старой работе
глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{},
прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая.
rus_verbs:возвращать{}, // возвращать к жизни
rus_verbs:располагать{}, // Атмосфера располагает к работе.
rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому.
rus_verbs:поступить{}, // К нам поступила жалоба.
rus_verbs:поступать{}, // К нам поступают жалобы.
rus_verbs:прыгнуть{}, // Белка прыгнула к дереву
rus_verbs:торопиться{}, // пассажиры торопятся к выходу
rus_verbs:поторопиться{}, // поторопитесь к выходу
rus_verbs:вернуть{}, // вернуть к активной жизни
rus_verbs:припирать{}, // припирать к стенке
rus_verbs:проваливать{}, // Проваливай ко всем чертям!
rus_verbs:вбежать{}, // Коля вбежал ко мне
rus_verbs:вбегать{}, // Коля вбегал ко мне
глагол:забегать{ вид:несоверш }, // Коля забегал ко мне
rus_verbs:постучаться{}, // Коля постучался ко мне.
rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому
rus_verbs:понести{}, // Мы понесли кота к ветеринару
rus_verbs:принести{}, // Я принес кота к ветеринару
rus_verbs:устремиться{}, // Мы устремились к ручью.
rus_verbs:подводить{}, // Учитель подводил детей к аквариуму
rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения.
rus_verbs:пригласить{}, // Я пригласил к себе товарищей.
rus_verbs:собираться{}, // Я собираюсь к тебе в гости.
rus_verbs:собраться{}, // Маша собралась к дантисту
rus_verbs:сходить{}, // Я схожу к врачу.
rus_verbs:идти{}, // Маша уверенно шла к Пете
rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию.
rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию.
rus_verbs:заканчивать{}, // Заканчивайте к обеду
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:окончить{}, //
rus_verbs:дозвониться{}, // Я не мог к вам дозвониться.
глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор
rus_verbs:уйти{}, // Антонио ушел к Элеонор
rus_verbs:бежать{}, // Антонио бежит к Элеонор
rus_verbs:спешить{}, // Антонио спешит к Элеонор
rus_verbs:скакать{}, // Антонио скачет к Элеонор
rus_verbs:красться{}, // Антонио крадётся к Элеонор
rus_verbs:поскакать{}, // беглецы поскакали к холмам
rus_verbs:перейти{} // Антонио перешел к Элеонор
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } }
then return true
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:к{} *:*{} }
then return false,-5
}
#endregion Предлог_К
#region Предлог_ДЛЯ
// ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ----------------------
wordentry_set Гл_ДЛЯ_Род={
частица:нет{}, // для меня нет других путей.
частица:нету{},
rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ)
rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ)
rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться)
rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ)
rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ)
rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ)
rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей
rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ)
rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ)
rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство
rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ)
rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ)
rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ)
rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ)
rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ)
rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ)
rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ)
rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ)
rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ)
rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ)
rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ)
rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ)
rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ)
rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ)
rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ)
rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ)
rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ)
rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ)
rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ)
rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ)
прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ)
rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ)
rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ)
rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ)
rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ)
rus_verbs:оставить{}, // или вообще решили оставить планету для себя
rus_verbs:оставлять{},
rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ)
rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ)
rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ)
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ)
rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ)
rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ)
rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ)
rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ)
rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для)
rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ)
rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ)
rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ)
rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ)
rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ)
прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ)
прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ)
прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ)
rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ)
rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ)
rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ)
rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ)
rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ)
rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ)
rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ)
rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ)
rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ)
rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ)
rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ)
прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ)
rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ)
rus_verbs:вывести{}, // мы специально вывели этих животных для мяса.
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для)
rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ)
rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ)
rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ)
rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ)
rus_verbs:найтись{}, // у вас найдется для него работа?
rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для)
rus_verbs:заехать{}, // Коля заехал для обсуждения проекта
rus_verbs:созреть{}, // созреть для побега
rus_verbs:наметить{}, // наметить для проверки
rus_verbs:уяснить{}, // уяснить для себя
rus_verbs:нанимать{}, // нанимать для разовой работы
rus_verbs:приспособить{}, // приспособить для удовольствия
rus_verbs:облюбовать{}, // облюбовать для посиделок
rus_verbs:прояснить{}, // прояснить для себя
rus_verbs:задействовать{}, // задействовать для патрулирования
rus_verbs:приготовлять{}, // приготовлять для проверки
инфинитив:использовать{ вид:соверш }, // использовать для достижения цели
инфинитив:использовать{ вид:несоверш },
глагол:использовать{ вид:соверш },
глагол:использовать{ вид:несоверш },
прилагательное:использованный{},
деепричастие:используя{},
деепричастие:использовав{},
rus_verbs:напрячься{}, // напрячься для решительного рывка
rus_verbs:одобрить{}, // одобрить для использования
rus_verbs:одобрять{}, // одобрять для использования
rus_verbs:пригодиться{}, // пригодиться для тестирования
rus_verbs:готовить{}, // готовить для выхода в свет
rus_verbs:отобрать{}, // отобрать для участия в конкурсе
rus_verbs:потребоваться{}, // потребоваться для подтверждения
rus_verbs:пояснить{}, // пояснить для слушателей
rus_verbs:пояснять{}, // пояснить для экзаменаторов
rus_verbs:понадобиться{}, // понадобиться для обоснования
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
rus_verbs:найти{}, // Папа нашел для детей няню
прилагательное:вредный{}, // Это вредно для здоровья.
прилагательное:полезный{}, // Прогулки полезны для здоровья.
прилагательное:обязательный{}, // Этот пункт обязателен для исполнения
прилагательное:бесполезный{}, // Это лекарство бесполезно для него
прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления
rus_verbs:создать{}, // Он не создан для этого дела.
прилагательное:сложный{}, // задача сложна для младших школьников
прилагательное:несложный{},
прилагательное:лёгкий{},
прилагательное:сложноватый{},
rus_verbs:становиться{},
rus_verbs:представлять{}, // Это не представляет для меня интереса.
rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка
rus_verbs:пройти{}, // День прошёл спокойно для него.
rus_verbs:проходить{},
rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
rus_verbs:высаживаться{},
rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца.
rus_verbs:прибавить{},
rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов.
rus_verbs:составлять{},
rus_verbs:стараться{}, // Я старался для вас
rus_verbs:постараться{}, // Я постарался для вас
rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста.
rus_verbs:собраться{}, // собраться для обсуждения
rus_verbs:собираться{}, // собираться для обсуждения
rus_verbs:уполномочивать{},
rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров
rus_verbs:принести{}, // Я принёс эту книгу для вас.
rus_verbs:делать{}, // Я это делаю для удовольствия.
rus_verbs:сделать{}, // Я сделаю это для удовольствия.
rus_verbs:подготовить{}, // я подготовил для друзей сюрприз
rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз
rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села
rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села
rus_verbs:прибыть{} // они прибыли для участия
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } }
then return true
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:для{} *:*{} }
then return false,-4
}
#endregion Предлог_ДЛЯ
#region Предлог_ОТ
// попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_ОТ_Род_Запр=
{
rus_verbs:наслаждаться{}, // свободой от обязательств
rus_verbs:насладиться{},
rus_verbs:мочь{}, // Он не мог удержаться от смеха.
// rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:чувствовать{}, // все время от времени чувствуют его.
rus_verbs:планировать{},
rus_verbs:приняться{} // мы принялись обниматься от радости.
}
fact гл_предл
{
if context { Глаг_ОТ_Род_Запр предлог:от{} * }
then return false
}
#endregion Предлог_ОТ
#region Предлог_БЕЗ
/*
// запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_БЕЗ_Род_Запр=
{
rus_verbs:мочь{}, // Он мог читать часами без отдыха.
rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:планировать{},
rus_verbs:приняться{}
}
fact гл_предл
{
if context { Глаг_БЕЗ_Род_Запр предлог:без{} * }
then return false
}
*/
#endregion Предлог_БЕЗ
#region Предлог_КРОМЕ
fact гл_предл
{
if context { * ПредлогДляВсе * }
then return false,-5
}
#endregion Предлог_КРОМЕ
// ------------------------------------
// По умолчанию разрешаем все остальные сочетания.
fact гл_предл
{
if context { * * * }
then return true
}
|
обогнать в первом круге
|
rus_verbs:обогнать{},
| 5,481,316 |
[
1,
145,
127,
145,
114,
145,
127,
145,
116,
145,
126,
145,
113,
146,
229,
146,
239,
225,
145,
115,
225,
145,
128,
145,
118,
146,
227,
145,
115,
145,
127,
145,
125,
225,
145,
123,
146,
227,
146,
230,
145,
116,
145,
118,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
436,
407,
67,
502,
2038,
30,
145,
127,
145,
114,
145,
127,
145,
116,
145,
126,
145,
113,
146,
229,
146,
239,
2916,
16,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x311Fd8bdbeAE8F32a3BD68cDEC4e9b4770e7DC7c/sources/browser/JusToken.sol
|
* @notice Delegates votes from signatory to `delegatee` @param delegatee The address to delegate votes to @param nonce The contract state required to match the signature @param expiry The time at which to expire the signature @param v The recovery byte of the signature @param r Half of the ECDSA signature pair @param s Half of the ECDSA signature pair/
|
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "JUS::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "JUS::delegateBySig: invalid nonce");
require(now <= expiry, "JUS::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 739,685 |
[
1,
15608,
815,
19588,
628,
1573,
8452,
358,
1375,
22216,
73,
68,
225,
7152,
73,
1021,
1758,
358,
7152,
19588,
358,
225,
7448,
1021,
6835,
919,
1931,
358,
845,
326,
3372,
225,
10839,
1021,
813,
622,
1492,
358,
6930,
326,
3372,
225,
331,
1021,
11044,
1160,
434,
326,
3372,
225,
436,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
225,
272,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
288,
203,
3639,
1731,
1578,
2461,
6581,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
27025,
67,
2399,
15920,
16,
203,
7734,
417,
24410,
581,
5034,
12,
3890,
12,
529,
10756,
3631,
203,
7734,
30170,
548,
9334,
203,
7734,
1758,
12,
2211,
13,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1731,
1578,
1958,
2310,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
2030,
19384,
2689,
67,
2399,
15920,
16,
203,
7734,
7152,
73,
16,
203,
7734,
7448,
16,
203,
7734,
10839,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1731,
1578,
5403,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
1548,
92,
3657,
64,
92,
1611,
3113,
203,
7734,
2461,
6581,
16,
203,
7734,
1958,
2310,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1758,
1573,
8452,
273,
425,
1793,
3165,
12,
10171,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
2583,
12,
2977,
8452,
480,
1758,
12,
20,
3631,
315,
46,
3378,
2866,
22216,
858,
8267,
30,
2057,
3372,
8863,
203,
3639,
2583,
12,
12824,
422,
1661,
764,
63,
2977,
8452,
3737,
15,
16,
315,
46,
3378,
2866,
22216,
858,
8267,
30,
2057,
7448,
8863,
203,
3639,
2583,
12,
3338,
1648,
10839,
16,
315,
46,
3378,
2866,
22216,
858,
8267,
30,
3372,
7708,
8863,
203,
3639,
327,
389,
22216,
12,
2977,
8452,
16,
7152,
73,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-21
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity >=0.6.12;
interface VatLike {
function hope(address) external;
}
interface GemJoinLike {
function dec() external view returns (uint256);
function gem() external view returns (TokenLike);
function exit(address, uint256) external;
}
interface DaiJoinLike {
function dai() external view returns (TokenLike);
function vat() external view returns (VatLike);
function join(address, uint256) external;
}
interface TokenLike {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function balanceOf(address) external view returns (uint256);
}
interface OtcLike {
function buyAllAmount(address, uint256, address, uint256) external returns (uint256);
function sellAllAmount(address, uint256, address, uint256) external returns (uint256);
}
// Simple Callee Example to interact with MatchingMarket
// This Callee contract exists as a standalone contract
contract CalleeMakerOtc {
OtcLike public otc;
DaiJoinLike public daiJoin;
TokenLike public dai;
uint256 public constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(x, sub(y, 1)) / y;
}
function setUp(address otc_, address clip_, address daiJoin_) internal {
otc = OtcLike(otc_);
daiJoin = DaiJoinLike(daiJoin_);
dai = daiJoin.dai();
daiJoin.vat().hope(clip_);
dai.approve(daiJoin_, uint256(-1));
}
function _fromWad(address gemJoin, uint256 wad) internal view returns (uint256 amt) {
amt = wad / 10 ** (sub(18, GemJoinLike(gemJoin).dec()));
}
}
// Maker-Otc is MatchingMarket, which is the core contract of OasisDex
contract CalleeMakerOtcDai is CalleeMakerOtc {
constructor(address otc_, address clip_, address daiJoin_) public {
setUp(otc_, clip_, daiJoin_);
}
function clipperCall(
address sender, // Clipper Caller and Dai deliveryaddress
uint256 daiAmt, // Dai amount to payback[rad]
uint256 gemAmt, // Gem amount received [wad]
bytes calldata data // Extra data needed (gemJoin)
) external {
// Get address to send remaining DAI, gemJoin adapter and minProfit in DAI to make
(address to, address gemJoin, uint256 minProfit) = abi.decode(data, (address, address, uint256));
// Convert gem amount to token precision
gemAmt = _fromWad(gemJoin, gemAmt);
// Exit collateral to token version
GemJoinLike(gemJoin).exit(address(this), gemAmt);
// Approve otc to take gem
TokenLike gem = GemJoinLike(gemJoin).gem();
gem.approve(address(otc), gemAmt);
// Calculate amount of DAI to Join (as erc20 WAD value)
uint256 daiToJoin = divup(daiAmt, RAY);
// Do operation and get dai amount bought (checking the profit is achieved)
uint256 daiBought = otc.sellAllAmount(address(gem), gemAmt, address(dai), add(daiToJoin, minProfit));
// Although maker-otc reverts if order book is empty, this check is a sanity check for other exchnages
// Transfer any lingering gem to specified address
if (gem.balanceOf(address(this)) > 0) {
gem.transfer(to, gem.balanceOf(address(this)));
}
// Convert DAI bought to internal vat value of the msg.sneder of Clipper.take
daiJoin.join(sender, daiToJoin);
// Transfer remaining DAI to specified address
dai.transfer(to, dai.balanceOf(address(this)));
}
}
// Maker-Otc is MatchingMarket, which is the core contract of OasisDex
/* contract CalleeMakerOtcGem is CalleeMakerOtc {
constructor(address otc_, address clip_, address daiJoin_) public {
setUp(otc_, clip_, daiJoin_);
}
function clipperCall(
uint256 daiAmt, // Dai amount to payback[rad]
uint256 gemAmt, // Gem amount received [wad]
bytes calldata data // Extra data needed (gemJoin)
) external {
// Get address to send remaining Gem, gemJoin adapter and minProfit in Gem to make
(address to, address gemJoin, uint256 minProfit) = abi.decode(data, (address, address, uint256));
// Convert gem amount to token precision
gemAmt = _fromWad(gemJoin, gemAmt);
// Exit collateral to token version
GemJoinLike(gemJoin).exit(address(this), gemAmt);
// Approve otc to take gem
TokenLike gem = GemJoinLike(gemJoin).gem();
gem.approve(address(otc), gemAmt);
// Calculate amount of DAI to Join (as erc20 WAD value)
uint256 daiToJoin = daiAmt / RAY;
if (daiToJoin * RAY < daiAmt) {
daiToJoin = daiToJoin + 1;
}
// Do operation and get gem amount sold (checking the profit is achieved)
uint256 gemSold = otc.buyAllAmount(address(dai), daiToJoin, address(gem), gemAmt - minProfit);
// TODO: make sure daiToJoin is actually the amount received from buyAllAmount (due rounding)
// Convert DAI bought to internal vat value
daiJoin.join(address(this), daiToJoin);
// Transfer remaining gem to specified address
gem.transfer(to, gemAmt - gemSold);
}
} */
|
Simple Callee Example to interact with MatchingMarket This Callee contract exists as a standalone contract
|
contract CalleeMakerOtc {
OtcLike public otc;
DaiJoinLike public daiJoin;
TokenLike public dai;
uint256 public constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(x, sub(y, 1)) / y;
}
function setUp(address otc_, address clip_, address daiJoin_) internal {
otc = OtcLike(otc_);
daiJoin = DaiJoinLike(daiJoin_);
dai = daiJoin.dai();
daiJoin.vat().hope(clip_);
dai.approve(daiJoin_, uint256(-1));
}
function _fromWad(address gemJoin, uint256 wad) internal view returns (uint256 amt) {
amt = wad / 10 ** (sub(18, GemJoinLike(gemJoin).dec()));
}
}
| 1,965,048 |
[
1,
5784,
3596,
11182,
5090,
358,
16592,
598,
29349,
3882,
278,
1220,
3596,
11182,
6835,
1704,
487,
279,
17676,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
3596,
11182,
12373,
51,
5111,
288,
203,
565,
531,
5111,
8804,
540,
1071,
320,
5111,
31,
203,
565,
463,
10658,
4572,
8804,
377,
1071,
5248,
77,
4572,
31,
203,
565,
3155,
8804,
4202,
1071,
5248,
77,
31,
203,
203,
565,
2254,
5034,
540,
1071,
5381,
534,
5255,
273,
1728,
2826,
12732,
31,
203,
203,
565,
445,
527,
12,
11890,
619,
16,
2254,
677,
13,
2713,
16618,
1135,
261,
11890,
998,
13,
288,
203,
3639,
2583,
12443,
94,
273,
619,
397,
677,
13,
1545,
619,
16,
315,
2377,
17,
15949,
17,
1289,
17,
11512,
8863,
203,
565,
289,
203,
565,
445,
720,
12,
11890,
619,
16,
2254,
677,
13,
2713,
16618,
1135,
261,
11890,
998,
13,
288,
203,
3639,
2583,
12443,
94,
273,
619,
300,
677,
13,
1648,
619,
16,
315,
2377,
17,
15949,
17,
1717,
17,
9341,
2426,
8863,
203,
565,
289,
203,
565,
445,
3739,
416,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
261,
11890,
5034,
998,
13,
288,
203,
3639,
998,
273,
527,
12,
92,
16,
720,
12,
93,
16,
404,
3719,
342,
677,
31,
203,
565,
289,
203,
203,
565,
445,
24292,
12,
2867,
320,
5111,
67,
16,
1758,
6807,
67,
16,
1758,
5248,
77,
4572,
67,
13,
2713,
288,
203,
3639,
320,
5111,
273,
531,
5111,
8804,
12,
352,
71,
67,
1769,
203,
3639,
5248,
77,
4572,
273,
463,
10658,
4572,
8804,
12,
2414,
77,
4572,
67,
1769,
203,
3639,
5248,
77,
273,
5248,
77,
4572,
18,
2414,
77,
5621,
203,
203,
203,
3639,
2
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.